answer stringlengths 17 10.2M |
|---|
package loci.formats;
import java.io.IOException;
import java.util.Vector;
import loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.common.ReflectException;
import loci.common.ReflectedUniverse;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.meta.DummyMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.services.OMEXMLService;
import loci.formats.services.OMEXMLServiceImpl;
public final class FormatTools {
// -- Constants - pixel types --
/** Identifies the <i>INT8</i> data type used to store pixel values. */
public static final int INT8 = 0;
/** Identifies the <i>UINT8</i> data type used to store pixel values. */
public static final int UINT8 = 1;
/** Identifies the <i>INT16</i> data type used to store pixel values. */
public static final int INT16 = 2;
/** Identifies the <i>UINT16</i> data type used to store pixel values. */
public static final int UINT16 = 3;
/** Identifies the <i>INT32</i> data type used to store pixel values. */
public static final int INT32 = 4;
/** Identifies the <i>UINT32</i> data type used to store pixel values. */
public static final int UINT32 = 5;
/** Identifies the <i>FLOAT</i> data type used to store pixel values. */
public static final int FLOAT = 6;
/** Identifies the <i>DOUBLE</i> data type used to store pixel values. */
public static final int DOUBLE = 7;
/** Human readable pixel type. */
private static final String[] pixelTypes = makePixelTypes();
static String[] makePixelTypes() {
String[] pixelTypes = new String[8];
pixelTypes[INT8] = "int8";
pixelTypes[UINT8] = "uint8";
pixelTypes[INT16] = "int16";
pixelTypes[UINT16] = "uint16";
pixelTypes[INT32] = "int32";
pixelTypes[UINT32] = "uint32";
pixelTypes[FLOAT] = "float";
pixelTypes[DOUBLE] = "double";
return pixelTypes;
}
// -- Constants - dimensional labels --
/**
* Identifies the <i>Channel</i> dimensional type,
* representing a generic channel dimension.
*/
public static final String CHANNEL = "Channel";
/**
* Identifies the <i>Spectra</i> dimensional type,
* representing a dimension consisting of spectral channels.
*/
public static final String SPECTRA = "Spectra";
/**
* Identifies the <i>Lifetime</i> dimensional type,
* representing a dimension consisting of a lifetime histogram.
*/
public static final String LIFETIME = "Lifetime";
/**
* Identifies the <i>Polarization</i> dimensional type,
* representing a dimension consisting of polarization states.
*/
public static final String POLARIZATION = "Polarization";
/**
* Identifies the <i>Phase</i> dimensional type,
* representing a dimension consisting of phases.
*/
public static final String PHASE = "Phase";
/**
* Identifies the <i>Frequency</i> dimensional type,
* representing a dimension consisting of frequencies.
*/
public static final String FREQUENCY = "Frequency";
// -- Constants - miscellaneous --
/** File grouping options. */
public static final int MUST_GROUP = 0;
public static final int CAN_GROUP = 1;
public static final int CANNOT_GROUP = 2;
/** Patterns to be used when constructing a pattern for output filenames. */
public static final String SERIES_NUM = "%s";
public static final String SERIES_NAME = "%n";
public static final String CHANNEL_NUM = "%c";
public static final String CHANNEL_NAME = "%w";
public static final String Z_NUM = "%z";
public static final String T_NUM = "%t";
public static final String TIMESTAMP = "%A";
// -- Constants - versioning --
/**
* Current SVN revision.
* @deprecated After Git move, deprecated in favour of {@link #VCS_REVISION}.
*/
@Deprecated
public static final String SVN_REVISION = "@vcs.revision@";
/** Current VCS revision. */
public static final String VCS_REVISION = "@vcs.revision@";
/** Date on which this release was built. */
public static final String DATE = "@date@";
/** Version number of this release. */
public static final String VERSION = "4.5-DEV";
// -- Constants - domains --
/** Identifies the high content screening domain. */
public static final String HCS_DOMAIN = "High-Content Screening (HCS)";
/** Identifies the light microscopy domain. */
public static final String LM_DOMAIN = "Light Microscopy";
/** Identifies the electron microscopy domain. */
public static final String EM_DOMAIN = "Electron Microscopy (EM)";
/** Identifies the scanning probe microscopy domain. */
public static final String SPM_DOMAIN = "Scanning Probe Microscopy (SPM)";
/** Identifies the scanning electron microscopy domain. */
public static final String SEM_DOMAIN = "Scanning Electron Microscopy (SEM)";
/** Identifies the fluorescence-lifetime domain. */
public static final String FLIM_DOMAIN = "Fluorescence-Lifetime Imaging";
/** Identifies the medical imaging domain. */
public static final String MEDICAL_DOMAIN = "Medical Imaging";
/** Identifies the histology domain. */
public static final String HISTOLOGY_DOMAIN = "Histology";
/** Identifies the gel and blot imaging domain. */
public static final String GEL_DOMAIN = "Gel/Blot Imaging";
/** Identifies the astronomy domain. */
public static final String ASTRONOMY_DOMAIN = "Astronomy";
/**
* Identifies the graphics domain.
* This includes formats used exclusively by analysis software.
*/
public static final String GRAPHICS_DOMAIN = "Graphics";
/** Identifies an unknown domain. */
public static final String UNKNOWN_DOMAIN = "Unknown";
/** List of non-graphics domains. */
public static final String[] NON_GRAPHICS_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, HCS_DOMAIN, UNKNOWN_DOMAIN
};
/** List of non-HCS domains. */
public static final String[] NON_HCS_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN
};
/**
* List of domains that do not require special handling. Domains that
* require special handling are {@link #GRAPHICS_DOMAIN} and
* {@link #HCS_DOMAIN}.
*/
public static final String[] NON_SPECIAL_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN
};
/** List of all supported domains. */
public static final String[] ALL_DOMAINS = new String[] {
HCS_DOMAIN, LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN,
MEDICAL_DOMAIN, HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN,
GRAPHICS_DOMAIN, UNKNOWN_DOMAIN
};
// -- Constants - web pages --
/** URL of Bio-Formats web page. */
public static final String URL_BIO_FORMATS =
"http:
/** URL of 'Bio-Formats as a Java Library' web page. */
public static final String URL_BIO_FORMATS_LIBRARIES =
"http:
/** URL of OME-TIFF web page. */
public static final String URL_OME_TIFF =
"http://ome-xml.org/wiki/OmeTiff";
// -- Constructor --
private FormatTools() { }
// -- Utility methods - dimensional positions --
/**
* Gets the rasterized index corresponding
* to the given Z, C and T coordinates.
*/
public static int getIndex(IFormatReader reader, int z, int c, int t) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getIndex(order, zSize, cSize, tSize, num, z, c, t);
}
/**
* Gets the rasterized index corresponding
* to the given Z, C and T coordinates.
*
* @param order Dimension order.
* @param zSize Total number of focal planes.
* @param cSize Total number of channels.
* @param tSize Total number of time points.
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param z Z coordinate of ZCT coordinate triple to convert to 1D index.
* @param c C coordinate of ZCT coordinate triple to convert to 1D index.
* @param t T coordinate of ZCT coordinate triple to convert to 1D index.
*/
public static int getIndex(String order, int zSize, int cSize, int tSize,
int num, int z, int c, int t)
{
// check DimensionOrder
if (order == null) {
throw new IllegalArgumentException("Dimension order is null");
}
if (!order.startsWith("XY") && !order.startsWith("YX")) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
int iz = order.indexOf("Z") - 2;
int ic = order.indexOf("C") - 2;
int it = order.indexOf("T") - 2;
if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
// check SizeZ
if (zSize <= 0) {
throw new IllegalArgumentException("Invalid Z size: " + zSize);
}
if (z < 0 || z >= zSize) {
throw new IllegalArgumentException("Invalid Z index: " + z + "/" + zSize);
}
// check SizeC
if (cSize <= 0) {
throw new IllegalArgumentException("Invalid C size: " + cSize);
}
if (c < 0 || c >= cSize) {
throw new IllegalArgumentException("Invalid C index: " + c + "/" + cSize);
}
// check SizeT
if (tSize <= 0) {
throw new IllegalArgumentException("Invalid T size: " + tSize);
}
if (t < 0 || t >= tSize) {
throw new IllegalArgumentException("Invalid T index: " + t + "/" + tSize);
}
// check image count
if (num <= 0) {
throw new IllegalArgumentException("Invalid image count: " + num);
}
if (num != zSize * cSize * tSize) {
// if this happens, there is probably a bug in metadata population --
// either one of the ZCT sizes, or the total number of images --
// or else the input file is invalid
throw new IllegalArgumentException("ZCT size vs image count mismatch " +
"(sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize +
", total=" + num + ")");
}
// assign rasterization order
int v0 = iz == 0 ? z : (ic == 0 ? c : t);
int v1 = iz == 1 ? z : (ic == 1 ? c : t);
int v2 = iz == 2 ? z : (ic == 2 ? c : t);
int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize);
int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize);
return v0 + v1 * len0 + v2 * len0 * len1;
}
/**
* Gets the Z, C and T coordinates corresponding
* to the given rasterized index value.
*/
public static int[] getZCTCoords(IFormatReader reader, int index) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getZCTCoords(order, zSize, cSize, tSize, num, index);
}
/**
* Gets the Z, C and T coordinates corresponding to the given rasterized
* index value.
*
* @param order Dimension order.
* @param zSize Total number of focal planes.
* @param cSize Total number of channels.
* @param tSize Total number of time points.
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param index 1D (rasterized) index to convert to ZCT coordinate triple.
*/
public static int[] getZCTCoords(String order,
int zSize, int cSize, int tSize, int num, int index)
{
// check DimensionOrder
if (order == null) {
throw new IllegalArgumentException("Dimension order is null");
}
if (!order.startsWith("XY") && !order.startsWith("YX")) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
int iz = order.indexOf("Z") - 2;
int ic = order.indexOf("C") - 2;
int it = order.indexOf("T") - 2;
if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
// check SizeZ
if (zSize <= 0) {
throw new IllegalArgumentException("Invalid Z size: " + zSize);
}
// check SizeC
if (cSize <= 0) {
throw new IllegalArgumentException("Invalid C size: " + cSize);
}
// check SizeT
if (tSize <= 0) {
throw new IllegalArgumentException("Invalid T size: " + tSize);
}
// check image count
if (num <= 0) {
throw new IllegalArgumentException("Invalid image count: " + num);
}
if (num != zSize * cSize * tSize) {
// if this happens, there is probably a bug in metadata population --
// either one of the ZCT sizes, or the total number of images --
// or else the input file is invalid
throw new IllegalArgumentException("ZCT size vs image count mismatch " +
"(sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize +
", total=" + num + ")");
}
if (index < 0 || index >= num) {
throw new IllegalArgumentException("Invalid image index: " +
index + "/" + num);
}
// assign rasterization order
int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize);
int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize);
//int len2 = iz == 2 ? sizeZ : (ic == 2 ? sizeC : sizeT);
int v0 = index % len0;
int v1 = index / len0 % len1;
int v2 = index / len0 / len1;
int z = iz == 0 ? v0 : (iz == 1 ? v1 : v2);
int c = ic == 0 ? v0 : (ic == 1 ? v1 : v2);
int t = it == 0 ? v0 : (it == 1 ? v1 : v2);
return new int[] {z, c, t};
}
/**
* Converts index from the given dimension order to the reader's native one.
* This method is useful for shuffling the planar order around
* (rather than eassigning ZCT sizes as {@link DimensionSwapper} does).
*
* @throws FormatException Never actually thrown.
*/
public static int getReorderedIndex(IFormatReader reader,
String newOrder, int newIndex) throws FormatException
{
String origOrder = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getReorderedIndex(origOrder, newOrder,
zSize, cSize, tSize, num, newIndex);
}
/**
* Converts index from one dimension order to another.
* This method is useful for shuffling the planar order around
* (rather than eassigning ZCT sizes as {@link DimensionSwapper} does).
*
* @param origOrder Original dimension order.
* @param newOrder New dimension order.
* @param zSize Total number of focal planes.
* @param cSize Total number of channels.
* @param tSize Total number of time points.
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param newIndex 1D (rasterized) index according to new dimension order.
* @return rasterized index according to original dimension order.
*/
public static int getReorderedIndex(String origOrder, String newOrder,
int zSize, int cSize, int tSize, int num, int newIndex)
{
int[] zct = getZCTCoords(newOrder, zSize, cSize, tSize, num, newIndex);
return getIndex(origOrder,
zSize, cSize, tSize, num, zct[0], zct[1], zct[2]);
}
/**
* Computes a unique 1-D index corresponding
* to the given multidimensional position.
* @param lengths the maximum value for each positional dimension
* @param pos position along each dimensional axis
* @return rasterized index value
*/
public static int positionToRaster(int[] lengths, int[] pos) {
int offset = 1;
int raster = 0;
for (int i=0; i<pos.length; i++) {
raster += offset * pos[i];
offset *= lengths[i];
}
return raster;
}
/**
* Computes a unique N-D position corresponding
* to the given rasterized index value.
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @return position along each dimensional axis
*/
public static int[] rasterToPosition(int[] lengths, int raster) {
return rasterToPosition(lengths, raster, new int[lengths.length]);
}
/**
* Computes a unique N-D position corresponding
* to the given rasterized index value.
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @param pos preallocated position array to populate with the result
* @return position along each dimensional axis
*/
public static int[] rasterToPosition(int[] lengths, int raster, int[] pos) {
int offset = 1;
for (int i=0; i<pos.length; i++) {
int offset1 = offset * lengths[i];
int q = i < pos.length - 1 ? raster % offset1 : raster;
pos[i] = q / offset;
raster -= q;
offset = offset1;
}
return pos;
}
/**
* Computes the number of raster values for a positional array
* with the given lengths.
*/
public static int getRasterLength(int[] lengths) {
int len = 1;
for (int i=0; i<lengths.length; i++) len *= lengths[i];
return len;
}
// -- Utility methods - pixel types --
/**
* Takes a string value and maps it to one of the pixel type enumerations.
* @param pixelTypeAsString the pixel type as a string.
* @return type enumeration value for use with class constants.
*/
public static int pixelTypeFromString(String pixelTypeAsString) {
String lowercaseTypeAsString = pixelTypeAsString.toLowerCase();
for (int i = 0; i < pixelTypes.length; i++) {
if (pixelTypes[i].equals(lowercaseTypeAsString)) return i;
}
throw new IllegalArgumentException("Unknown type: '" +
pixelTypeAsString + "'");
}
/**
* Takes a pixel type value and gets a corresponding string representation.
* @param pixelType the pixel type.
* @return string value for human-readable output.
*/
public static String getPixelTypeString(int pixelType) {
if (pixelType < 0 || pixelType >= pixelTypes.length) {
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
return pixelTypes[pixelType];
}
/**
* Retrieves how many bytes per pixel the current plane or section has.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return the number of bytes per pixel.
* @see IFormatReader#getPixelType()
*/
public static int getBytesPerPixel(int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
return 1;
case INT16:
case UINT16:
return 2;
case INT32:
case UINT32:
case FLOAT:
return 4;
case DOUBLE:
return 8;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Retrieves the number of bytes per pixel in the current plane.
* @param pixelType the pixel type, as a String.
* @return the number of bytes per pixel.
* @see #pixelTypeFromString(String)
* @see #getBytesPerPixel(int)
*/
public static int getBytesPerPixel(String pixelType) {
return getBytesPerPixel(pixelTypeFromString(pixelType));
}
/**
* Determines whether the given pixel type is floating point or integer.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return true if the pixel type is floating point.
* @see IFormatReader#getPixelType()
*/
public static boolean isFloatingPoint(int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
case INT16:
case UINT16:
case INT32:
case UINT32:
return false;
case FLOAT:
case DOUBLE:
return true;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Determines whether the given pixel type is signed or unsigned.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return true if the pixel type is signed.
* @see IFormatReader#getPixelType()
*/
public static boolean isSigned(int pixelType) {
switch (pixelType) {
case INT8:
case INT16:
case INT32:
case FLOAT:
case DOUBLE:
return true;
case UINT8:
case UINT16:
case UINT32:
return false;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Returns an appropriate pixel type given the number of bytes per pixel.
*
* @param bytes number of bytes per pixel.
* @param signed whether or not the pixel type should be signed.
* @param fp whether or not these are floating point pixels.
*/
public static int pixelTypeFromBytes(int bytes, boolean signed, boolean fp)
throws FormatException
{
switch (bytes) {
case 1:
return signed ? INT8 : UINT8;
case 2:
return signed ? INT16: UINT16;
case 4:
return fp ? FLOAT : signed ? INT32: UINT32;
case 8:
return DOUBLE;
default:
throw new FormatException("Unsupported byte depth: " + bytes);
}
}
// -- Utility methods - sanity checking
public static void assertId(String currentId, boolean notNull, int depth) {
String msg = null;
if (currentId == null && notNull) {
msg = "Current file should not be null; call setId(String) first";
}
else if (currentId != null && !notNull) {
msg = "Current file should be null, but is '" +
currentId + "'; call close() first";
}
if (msg == null) return;
StackTraceElement[] ste = new Exception().getStackTrace();
String header;
if (depth > 0 && ste.length > depth) {
String c = ste[depth].getClassName();
if (c.startsWith("loci.formats.")) {
c = c.substring(c.lastIndexOf(".") + 1);
}
header = c + "." + ste[depth].getMethodName() + ": ";
}
else header = "";
throw new IllegalStateException(header + msg);
}
/**
* Convenience method for checking that the plane number, tile size and
* buffer sizes are all valid for the given reader.
* If 'bufLength' is less than 0, then the buffer length check is not
* performed.
*/
public static void checkPlaneParameters(IFormatReader r, int no,
int bufLength, int x, int y, int w, int h) throws FormatException
{
assertId(r.getCurrentFile(), true, 2);
checkPlaneNumber(r, no);
checkTileSize(r, x, y, w, h);
if (bufLength >= 0) checkBufferSize(r, bufLength, w, h);
}
/** Checks that the given plane number is valid for the given reader. */
public static void checkPlaneNumber(IFormatReader r, int no)
throws FormatException
{
int imageCount = r.getImageCount();
if (no < 0 || no >= imageCount) {
throw new FormatException("Invalid image number: " + no +
" (series=" + r.getSeries() + ", imageCount=" + imageCount + ")");
}
}
/** Checks that the given tile size is valid for the given reader. */
public static void checkTileSize(IFormatReader r, int x, int y, int w, int h)
throws FormatException
{
int width = r.getSizeX();
int height = r.getSizeY();
if (x < 0 || y < 0 || w < 0 || h < 0 || (x + w) > width ||
(y + h) > height)
{
throw new FormatException("Invalid tile size: x=" + x + ", y=" + y +
", w=" + w + ", h=" + h);
}
}
public static void checkBufferSize(IFormatReader r, int len)
throws FormatException
{
checkBufferSize(r, len, r.getSizeX(), r.getSizeY());
}
/**
* Checks that the given buffer size is large enough to hold a w * h
* image as returned by the given reader.
* @throws FormatException if the buffer is too small
*/
public static void checkBufferSize(IFormatReader r, int len, int w, int h)
throws FormatException
{
int size = getPlaneSize(r, w, h);
if (size > len) {
throw new FormatException("Buffer too small (got " + len +
", expected " + size + ").");
}
}
/**
* Returns true if the given RandomAccessInputStream conatins at least
* 'len' bytes.
*/
public static boolean validStream(RandomAccessInputStream stream, int len,
boolean littleEndian) throws IOException
{
stream.seek(0);
stream.order(littleEndian);
return stream.length() >= len;
}
/** Returns the size in bytes of a single plane. */
public static int getPlaneSize(IFormatReader r) {
return getPlaneSize(r, r.getSizeX(), r.getSizeY());
}
/** Returns the size in bytes of a w * h tile. */
public static int getPlaneSize(IFormatReader r, int w, int h) {
return w * h * r.getRGBChannelCount() * getBytesPerPixel(r.getPixelType());
}
// -- Utility methods -- export
/**
* @throws FormatException Never actually thrown.
* @throws IOException Never actually thrown.
*/
public static String getFilename(int series, int image, IFormatReader r,
String pattern) throws FormatException, IOException
{
MetadataStore store = r.getMetadataStore();
MetadataRetrieve retrieve = store instanceof MetadataRetrieve ?
(MetadataRetrieve) store : new DummyMetadata();
String filename = pattern.replaceAll(SERIES_NUM, String.valueOf(series));
String imageName = retrieve.getImageName(series);
if (imageName == null) imageName = "Series" + series;
imageName = imageName.replaceAll("/", "_");
imageName = imageName.replaceAll("\\\\", "_");
filename = filename.replaceAll(SERIES_NAME, imageName);
r.setSeries(series);
int[] coordinates = r.getZCTCoords(image);
filename = filename.replaceAll(Z_NUM, String.valueOf(coordinates[0]));
filename = filename.replaceAll(T_NUM, String.valueOf(coordinates[2]));
filename = filename.replaceAll(CHANNEL_NUM, String.valueOf(coordinates[1]));
String channelName = retrieve.getChannelName(series, coordinates[1]);
if (channelName == null) channelName = String.valueOf(coordinates[1]);
channelName = channelName.replaceAll("/", "_");
channelName = channelName.replaceAll("\\\\", "_");
filename = filename.replaceAll(CHANNEL_NAME, channelName);
String date = retrieve.getImageAcquisitionDate(series).getValue();
long stamp = 0;
if (retrieve.getPlaneCount(series) > image) {
Double deltaT = retrieve.getPlaneDeltaT(series, image);
if (deltaT != null) {
stamp = (long) (deltaT * 1000);
}
}
stamp += DateTools.getTime(date, DateTools.ISO8601_FORMAT);
date = DateTools.convertDate(stamp, (int) DateTools.UNIX_EPOCH);
filename = filename.replaceAll(TIMESTAMP, date);
return filename;
}
public static String[] getFilenames(String pattern, IFormatReader r)
throws FormatException, IOException
{
Vector<String> filenames = new Vector<String>();
String filename = null;
for (int series=0; series<r.getSeriesCount(); series++) {
r.setSeries(series);
for (int image=0; image<r.getImageCount(); image++) {
filename = getFilename(series, image, r, pattern);
if (!filenames.contains(filename)) filenames.add(filename);
}
}
return filenames.toArray(new String[0]);
}
public static int getImagesPerFile(String pattern, IFormatReader r)
throws FormatException, IOException
{
String[] filenames = getFilenames(pattern, r);
int totalPlanes = 0;
for (int series=0; series<r.getSeriesCount(); series++) {
r.setSeries(series);
totalPlanes += r.getImageCount();
}
return totalPlanes / filenames.length;
}
// -- Utility methods -- other
/**
* Recursively look for the first underlying reader that is an
* instance of the given class.
*/
public static IFormatReader getReader(IFormatReader r,
Class<? extends IFormatReader> c)
{
IFormatReader[] underlying = r.getUnderlyingReaders();
if (underlying != null) {
for (int i=0; i<underlying.length; i++) {
if (underlying[i].getClass().isInstance(c)) return underlying[i];
}
for (int i=0; i<underlying.length; i++) {
IFormatReader t = getReader(underlying[i], c);
if (t != null) return t;
}
}
return null;
}
/**
* Default implementation for {@link IFormatReader#openThumbBytes}.
*
* At the moment, it uses {@link java.awt.image.BufferedImage} objects
* to resize thumbnails, so it is not safe for use in headless contexts.
* In the future, we may reimplement the image scaling logic purely with
* byte arrays, but handling every case would be substantial effort, so
* doing so is currently a low priority item.
*/
public static byte[] openThumbBytes(IFormatReader reader, int no)
throws FormatException, IOException
{
// NB: Dependency on AWT here is unfortunate, but very difficult to
// eliminate in general. We use reflection to limit class loading
// problems with AWT on Mac OS X.
ReflectedUniverse r = new ReflectedUniverse();
byte[][] bytes = null;
try {
r.exec("import loci.formats.gui.AWTImageTools");
int planeSize = getPlaneSize(reader);
byte[] plane = null;
if (planeSize < 0) {
int width = reader.getThumbSizeX() * 4;
int height = reader.getThumbSizeY() * 4;
int x = (reader.getSizeX() - width) / 2;
int y = (reader.getSizeY() - height) / 2;
plane = reader.openBytes(no, x, y, width, height);
}
else {
plane = reader.openBytes(no);
}
r.setVar("plane", plane);
r.setVar("reader", reader);
r.setVar("sizeX", reader.getSizeX());
r.setVar("sizeY", reader.getSizeY());
r.setVar("thumbSizeX", reader.getThumbSizeX());
r.setVar("thumbSizeY", reader.getThumbSizeY());
r.setVar("little", reader.isLittleEndian());
r.exec("img = AWTImageTools.openImage(plane, reader, sizeX, sizeY)");
r.exec("img = AWTImageTools.makeUnsigned(img)");
r.exec("thumb = AWTImageTools.scale(img, thumbSizeX, thumbSizeY, false)");
bytes = (byte[][]) r.exec("AWTImageTools.getPixelBytes(thumb, little)");
}
catch (ReflectException exc) {
throw new FormatException(exc);
}
if (bytes.length == 1) return bytes[0];
int rgbChannelCount = reader.getRGBChannelCount();
byte[] rtn = new byte[rgbChannelCount * bytes[0].length];
if (!reader.isInterleaved()) {
for (int i=0; i<rgbChannelCount; i++) {
System.arraycopy(bytes[i], 0, rtn, bytes[0].length * i, bytes[i].length);
}
}
else {
int bpp = FormatTools.getBytesPerPixel(reader.getPixelType());
for (int i=0; i<bytes[0].length/bpp; i+=bpp) {
for (int j=0; j<rgbChannelCount; j++) {
System.arraycopy(bytes[j], i, rtn, (i * rgbChannelCount) + j * bpp, bpp);
}
}
}
return rtn;
}
// -- Conversion convenience methods --
/**
* Convenience method for converting the specified input file to the
* specified output file. The ImageReader and ImageWriter classes are used
* for input and output, respectively. To use other IFormatReader or
* IFormatWriter implementation,
* @see convert(IFormatReader, IFormatWriter, String).
*
* @param input the full path name of the existing input file
* @param output the full path name of the output file to be created
* @throws FormatException if there is a general problem reading from or
* writing to one of the files.
* @throws IOException if there is an I/O-related error.
*/
public static void convert(String input, String output)
throws FormatException, IOException
{
IFormatReader reader = new ImageReader();
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
reader.setMetadataStore(service.createOMEXMLMetadata());
}
catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
}
catch (ServiceException se) {
throw new FormatException(se);
}
reader.setId(input);
IFormatWriter writer = new ImageWriter();
convert(reader, writer, output);
}
/**
* Convenience method for writing all of the images and metadata obtained
* from the specified IFormatReader into the specified IFormatWriter.
*
* It is required that setId(String) be called on the IFormatReader
* object before it is passed to convert(...). setMetadataStore(...)
* should also have been called with an appropriate instance of IMetadata.
*
* The setId(String) method must not be called on the IFormatWriter
* object; this is taken care of internally. Additionally, the
* setMetadataRetrieve(...) method in IFormatWriter should not be called.
*
* @param input the pre-initialized IFormatReader used for reading data.
* @param output the uninitialized IFormatWriter used for writing data.
* @param outputFile the full path name of the output file to be created.
* @throws FormatException if there is a general problem reading from or
* writing to one of the files.
* @throws IOException if there is an I/O-related error.
*/
public static void convert(IFormatReader input, IFormatWriter output,
String outputFile)
throws FormatException, IOException
{
MetadataStore store = input.getMetadataStore();
MetadataRetrieve meta = null;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
meta = service.asRetrieve(store);
}
catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
}
output.setMetadataRetrieve(meta);
output.setId(outputFile);
for (int series=0; series<input.getSeriesCount(); series++) {
input.setSeries(series);
output.setSeries(series);
byte[] buf = new byte[getPlaneSize(input)];
for (int image=0; image<input.getImageCount(); image++) {
input.openBytes(image, buf);
output.saveBytes(image, buf);
}
}
input.close();
output.close();
}
/**
* Get the default range for the specified pixel type. Note that
* this is not necessarily the minimum and maximum value which may
* be stored, but the minimum and maximum which should be used for
* rendering.
*
* @param pixelType the pixel type.
* @returns an array containing the min and max as elements 0 and 1,
* respectively.
* @throws IOException if the pixel type is floating point or invalid.
*/
public static long[] defaultMinMax(int pixelType) {
long min = 0 , max = 0;
switch (pixelType) {
case INT8:
min = Byte.MIN_VALUE;
max = Byte.MAX_VALUE;
break;
case INT16:
min = Short.MIN_VALUE;
max = Short.MAX_VALUE;
break;
case INT32:
case FLOAT:
case DOUBLE:
min = Integer.MIN_VALUE;
max = Integer.MAX_VALUE;
break;
case UINT8:
min = 0;
max=(long) Math.pow(2, 8)-1;
break;
case UINT16:
min = 0;
max=(long) Math.pow(2, 16)-1;
break;
case UINT32:
min = 0;
max=(long) Math.pow(2, 32)-1;
break;
default:
throw new IllegalArgumentException("Invalid pixel type");
}
long[] values = {min, max};
return values;
}
} |
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
// Instance variables
private static BufferedReader dataStream;
// Main program
public static void main(String[] args) throws Exception{
// New Data Stream Instance
dataStream = new BufferedReader(new InputStreamReader(System.in));
// Parsing in Input
int n = Integer.parseInt(dataStream.readLine());
int k = Integer.parseInt(dataStream.readLine());
int[] candies = new int[n];
for(int i = 0;i < n;i++){
candies[i] = Integer.parseInt(dataStream.readLine());
}
// New solution instance
Solution soln = new Solution();
int result = soln.getMinUnfairness(candies,k);
// Printing the output to the console
System.out.println(result);
}
/** Sliding window algorithm on sorted candy array that determines min unfairness
* Complexity is O(n). Counting sort is done since N has an upper bound (finite).
* @param candies Unsorted array of candies
* @returns minUnfairness
*/
private int getMinUnfairness(int[] candies,int k){
// Sorting the candies
Arrays.sort(candies);
// Sliding on the window and recording the minUnfairness on all possible
// windows with the candies array
int result = candies[k-1] - candies[0];
for(int i = 1;i < candies.length-k;i++){
int curUnfairness = candies[i+k-1] - candies[i];
if(curUnfairness<result)
result = curUnfairness;
}
return result;
}
} |
package com.dptsolutions.pathbutton;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.Button;
/**
* A Button that draws a Path around the edges of itself, with
* curved ends. Path is the same color as the color of the text
* of the button, and defaults to 2dp width. Area inside path can
* be filled with a different color from the border.
*/
public class PathButton extends Button {
public PathButton(Context context) {
super(context);
init(context, null, R.attr.pathButtonStyle, R.style.PathButton);
}
public PathButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, R.attr.pathButtonStyle, R.style.PathButton);
}
public PathButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, R.style.PathButton);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public PathButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private Paint borderPaint;
private Path borderPath;
private Paint fillPaint;
private Path fillPath;
private ColorStateList fillColors;
private int currentFillColor;
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final int defaultStrokeWidth = context.getResources().getDimensionPixelSize(R.dimen.path_button_default_border_width);
int strokeWidth = defaultStrokeWidth;
if(attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PathButton, defStyleAttr, defStyleRes);
try {
strokeWidth = a.getDimensionPixelSize(R.styleable.PathButton_borderWidth, defaultStrokeWidth);
Drawable b = a.getDrawable(R.styleable.PathButton_android_background);
if (b != null) {
setBackground(b);
}
ColorStateList csl = a.getColorStateList(R.styleable.PathButton_android_textColor);
if (csl != null) {
setTextColor(csl);
}
fillColors = a.getColorStateList(R.styleable.PathButton_fillColor);
if(fillColors == null) {
fillColors = ColorStateList.valueOf(a.getColor(R.styleable.PathButton_fillColor, context.getResources().getColor(android.R.color.transparent)));
}
} finally {
a.recycle();
}
}
borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setStrokeWidth(strokeWidth);
borderPath = new Path();
fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
fillPaint.setStyle(Paint.Style.FILL);
fillPath = new Path();
}
private void updateFillColor() {
boolean shouldInvalidate = false;
//Only invalidate if fill color has changed
int color = fillColors.getColorForState(getDrawableState(), 0);
if(currentFillColor != color) {
currentFillColor = color;
shouldInvalidate = true;
}
if(shouldInvalidate) {
invalidate();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
final float strokeWidth = borderPaint.getStrokeWidth();
final float radius = (float)( (h - (2 * strokeWidth)) / 2.0);
final RectF outerLeftArcRect = new RectF(strokeWidth, strokeWidth, strokeWidth + radius * 2, h - strokeWidth);
final RectF outerRightArcRect = new RectF(w - strokeWidth - (2 * radius), strokeWidth, w - strokeWidth, h - strokeWidth);
borderPath.reset();
borderPath.addArc(outerLeftArcRect, 90, 180);
borderPath.addArc(outerRightArcRect, 270, 180);
borderPath.moveTo(strokeWidth + radius, strokeWidth);
borderPath.lineTo(w - strokeWidth - radius, strokeWidth);
borderPath.moveTo(strokeWidth + radius, h - strokeWidth);
borderPath.lineTo(w - strokeWidth - radius, h - strokeWidth);
fillPath.reset();
fillPath.addArc(outerLeftArcRect, 90, 180);
fillPath.addArc(outerRightArcRect, 270, 180);
fillPath.moveTo(strokeWidth + radius, strokeWidth);
fillPath.lineTo(w - strokeWidth - radius, strokeWidth);
fillPath.lineTo(w - strokeWidth - radius, h - strokeWidth);
fillPath.lineTo(strokeWidth + radius, h - strokeWidth);
fillPath.lineTo(strokeWidth + radius, strokeWidth);
fillPath.close();
}
@Override
protected void onDraw(Canvas canvas) {
fillPaint.setColor(currentFillColor);
canvas.drawPath(fillPath, fillPaint);
borderPaint.setColor(getCurrentTextColor());
canvas.drawPath(borderPath, borderPaint);
super.onDraw(canvas);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
//Update the current fill color only if it can change
if(fillColors != null && fillColors.isStateful()) {
updateFillColor();
}
}
/**
* Set the width of the border of the PathButton. Cannot be less than 2dp
*
* @see #getBorderWidth()
*
* @param pixels Width of the border to set, in pixels
*/
public void setBorderWidth(int pixels) {
final int defaultStrokeWidth = getContext().getResources().getDimensionPixelSize(R.dimen.path_button_default_border_width);
int strokeWidth = pixels < defaultStrokeWidth ? defaultStrokeWidth : pixels;
borderPaint.setStrokeWidth(strokeWidth);
invalidate();
}
/**
* Get the width of the border of the PathButton
*
* @see #setBorderWidth(int)
*
* @return Width of the border, in pixels
*/
public int getBorderWidth() {
return (int) borderPaint.getStrokeWidth();
}
/**
* Gets the fill colors for the different states (normal, pressed, focused) of the PathButton.
*
* @see #setFillColors(android.content.res.ColorStateList)
* @see #setFillColor(int)
*/
public ColorStateList getFillColors() {
return fillColors;
}
/**
* Sets the fill colors for the different states (normal, pressed, focused) of the PathButton.
*
* @see #getFillColors()
* @see #setFillColor(int)
*/
public void setFillColors(ColorStateList colors) {
if(colors == null) {
throw new NullPointerException();
}
fillColors = colors;
updateFillColor();
}
/**
* Sets the fill color for all the states (normal, pressed, focused) to be this color.
*
* @see #setFillColor(int)
* @see #getFillColors()
*/
public void setFillColor(int color) {
fillColors = ColorStateList.valueOf(color);
updateFillColor();
}
} |
package ru.revdaalex.oodsrp;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class CalculatorTest {
private static Calculator calculator;
/**
*Initialization Calculator object
*/
@BeforeClass
public static void runTest(){
calculator = new Calculator();
}
/**
* Test add method
* @throws Exception
*/
@Test
public void add() throws Exception {
int test = calculator.add(30, 27);
Assert.assertEquals(test, 57);
}
/**
* Test sub method
* @throws Exception
*/
@Test
public void sub() throws Exception {
int test = calculator.sub(200, 50);
Assert.assertEquals(test, 150);
}
/**
* Test mult method
* @throws Exception
*/
@Test
public void mult() throws Exception {
int test = calculator.mult(537, 34);
Assert.assertEquals(test, 18258);
}
/**
* Test div method
* @throws Exception
*/
@Test
public void div() throws Exception {
int test = calculator.div(2000, 50);
Assert.assertEquals(test, 40);
}
} |
package org.broad.igv.tools;
import org.broad.igv.Globals;
import org.broad.igv.tools.parsers.DataConsumer;
import org.broad.igv.track.TrackType;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* public CoverageCounter(String alignmentFile,
* DataConsumer consumer,
* int windowSize,
* int extFactor,
* File tdfFile, // For reference
* File wigFile,
* Genome genome,
* String options)
*/
public class CoverageCounterTest {
@BeforeClass
public static void init() {
Globals.setHeadless(true);
}
@Test
public void testMappingQualityFlag() throws IOException {
String bamURL = "http:
String options = "m=30,q@1:16731624-16731624";
int windowSize = 1;
TestDataConsumer dc = new TestDataConsumer();
CoverageCounter cc = new CoverageCounter(bamURL, dc, windowSize, 0, null, null, null, options);
cc.parse();
String totalCount = dc.attributes.get("totalCount");
assertEquals("19", totalCount);
}
@Test
public void testIncludeDuplicatesFlag() throws IOException {
String bamURL = "http:
String options = "d,q@chr1:153425249-153425249";
int windowSize = 1;
TestDataConsumer dc = new TestDataConsumer();
CoverageCounter cc = new CoverageCounter(bamURL, dc, windowSize, 0, null, null, null, options);
cc.parse();
String totalCount = dc.attributes.get("totalCount");
assertEquals("22", totalCount);
}
static class TestDataConsumer implements DataConsumer {
Map<String, String> attributes = new HashMap<String, String>();
public void setType(String type) {
}
public void addData(String chr, int start, int end, float[] data, String name) {
}
public void parsingComplete() {
}
public void setTrackParameters(TrackType trackType, String trackLine, String[] trackNames) {
}
public void setSortTolerance(int tolerance) {
}
public void setAttribute(String key, String value) {
attributes.put(key, value);
}
}
} |
package org.obolibrary.robot;
import java.util.*;
import java.util.stream.Collectors;
import org.obolibrary.robot.checks.InvalidReferenceChecker;
import org.obolibrary.robot.checks.InvalidReferenceViolation;
import org.obolibrary.robot.checks.InvalidReferenceViolation.Category;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.model.parameters.Imports;
import org.semanticweb.owlapi.util.OWLEntityRenamer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Repair an ontology */
public class RepairOperation {
/** Logger. */
private static final Logger logger = LoggerFactory.getLogger(RepairOperation.class);
/**
* Return a map from option name to default option value, for all the available repair options.
*
* @return a map with default values for all available options
*/
public static Map<String, String> getDefaultOptions() {
// options.put("remove-redundant-subclass-axioms", "true");
return new HashMap<>();
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
*/
public static void repair(OWLOntology ontology, IOHelper ioHelper) {
repair(ontology, ioHelper, getDefaultOptions());
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
* @param mergeAxiomAnnotations if true, merge annotations on duplicate axioms
*/
public static void repair(
OWLOntology ontology, IOHelper ioHelper, boolean mergeAxiomAnnotations) {
repair(ontology, ioHelper, getDefaultOptions(), mergeAxiomAnnotations);
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
* @param mergeAxiomAnnotations if true, merge annotations on duplicate axioms
* @param migrateAnnotations set of annotation properties for which to migrate values
*/
public static void repair(
OWLOntology ontology,
IOHelper ioHelper,
boolean mergeAxiomAnnotations,
Set<OWLAnnotationProperty> migrateAnnotations) {
repair(ontology, ioHelper, getDefaultOptions(), mergeAxiomAnnotations, migrateAnnotations);
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
* @param options map of repair options
*/
public static void repair(OWLOntology ontology, IOHelper ioHelper, Map<String, String> options) {
repair(ontology, ioHelper, options, false);
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
* @param options map of repair options
* @param mergeAxiomAnnotations if true, merge annotations on duplicate axioms
*/
public static void repair(
OWLOntology ontology,
IOHelper ioHelper,
Map<String, String> options,
boolean mergeAxiomAnnotations) {
repair(ontology, ioHelper, options, mergeAxiomAnnotations, Collections.emptySet());
}
/**
* Repairs ontology
*
* @param ontology the OWLOntology to repair
* @param ioHelper IOHelper to work with the ontology
* @param options map of repair options
* @param mergeAxiomAnnotations if true, merge annotations on duplicate axioms
* @param migrateAnnotations set of annotation properties for which to migrate values
*/
public static void repair(
OWLOntology ontology,
IOHelper ioHelper,
Map<String, String> options,
boolean mergeAxiomAnnotations,
Set<OWLAnnotationProperty> migrateAnnotations) {
Set<InvalidReferenceViolation> violations =
InvalidReferenceChecker.getInvalidReferenceViolations(ontology, true);
repairInvalidReferences(ioHelper, ontology, violations, migrateAnnotations);
if (mergeAxiomAnnotations) {
mergeAxiomAnnotations(ontology);
}
}
/**
* Given an ontology, merge the annotations of duplicate axioms to create one axiom with all
* annotations.
*
* @param ontology the OWLOntology to repair
*/
public static void mergeAxiomAnnotations(OWLOntology ontology) {
Map<OWLAxiom, Set<OWLAnnotation>> mergedAxioms = new HashMap<>();
Set<OWLAxiom> axiomsToMerge = new HashSet<>();
// Find duplicated axioms and collect their annotations
// OWLAPI should already merge non-annotated duplicates
for (OWLAxiom axiom : ontology.getAxioms()) {
if (axiom.isAnnotated()) {
axiomsToMerge.add(axiom);
OWLAxiom strippedAxiom = axiom.getAxiomWithoutAnnotations();
Set<OWLAnnotation> annotations = axiom.getAnnotations();
if (mergedAxioms.containsKey(strippedAxiom)) {
logger.info("Merging annotations on axiom: {}", strippedAxiom.toString());
Set<OWLAnnotation> mergeAnnotations = new HashSet<>();
mergeAnnotations.addAll(mergedAxioms.get(strippedAxiom));
mergeAnnotations.addAll(annotations);
mergedAxioms.put(strippedAxiom, mergeAnnotations);
} else {
mergedAxioms.put(strippedAxiom, annotations);
}
}
}
OWLOntologyManager manager = ontology.getOWLOntologyManager();
OWLDataFactory dataFactory = manager.getOWLDataFactory();
// Remove the duplicated axioms
manager.removeAxioms(ontology, axiomsToMerge);
// Create the axioms with new set of annotations
Set<OWLAxiom> newAxioms = new HashSet<>();
for (Map.Entry<OWLAxiom, Set<OWLAnnotation>> mergedAxiom : mergedAxioms.entrySet()) {
OWLAxiom axiom = mergedAxiom.getKey();
if (axiom.isAnnotationAxiom()) {
OWLAxiom newAxiom = axiom.getAnnotatedAxiom(mergedAxiom.getValue());
newAxioms.add(newAxiom);
}
}
manager.addAxioms(ontology, newAxioms);
}
/**
* Repairs invalid references
*
* <p>Currently only able to repair references to deprecated classes.
*
* <p>Assumes OBO vocabulary
*
* @param iohelper IOHelper to work with the ontology
* @param ontology the OWLOntology to repair
* @param violations set of references violations
*/
public static void repairInvalidReferences(
IOHelper iohelper, OWLOntology ontology, Set<InvalidReferenceViolation> violations) {
repairInvalidReferences(iohelper, ontology, violations, Collections.emptySet());
}
/**
* Repairs invalid references
*
* <p>Currently only able to repair references to deprecated classes.
*
* <p>Assumes OBO vocabulary
*
* @param iohelper IOHelper to work with the ontology
* @param ontology the OWLOntology to repair
* @param violations set of references violations
* @param migrateAnnotations set of annotation properties for which to migrate values
*/
public static void repairInvalidReferences(
IOHelper iohelper,
OWLOntology ontology,
Set<InvalidReferenceViolation> violations,
Set<OWLAnnotationProperty> migrateAnnotations) {
logger.info("Invalid references: " + violations.size());
OWLOntologyManager manager = ontology.getOWLOntologyManager();
OWLEntityRenamer renamer = new OWLEntityRenamer(manager, ontology.getImportsClosure());
Map<OWLEntity, IRI> renameMap = new HashMap<>();
Set<OWLAxiom> axiomsToPreserve = new HashSet<>();
for (InvalidReferenceViolation v : violations) {
if (v.getCategory().equals(Category.DEPRECATED)) {
OWLEntity obsObj = v.getReferencedObject();
logger.info("Finding replacements for: " + v);
IRI replacedBy = null;
for (OWLOntology o : ontology.getImportsClosure()) {
for (OWLAnnotationAssertionAxiom aaa : o.getAnnotationAssertionAxioms(obsObj.getIRI())) {
// TODO: use a vocabulary class
if (aaa.getProperty()
.getIRI()
.equals(IRI.create("http://purl.obolibrary.org/obo/IAO_0100001"))) {
OWLAnnotationValue val = aaa.getValue();
IRI valIRI = val.asIRI().orNull();
if (valIRI != null) {
logger.info("Using URI replacement: " + valIRI);
replacedBy = valIRI;
} else {
OWLLiteral valLit = val.asLiteral().orNull();
if (valLit != null) {
logger.info("Using CURIE replacement: " + valLit);
replacedBy = iohelper.createIRI(valLit.getLiteral());
}
}
}
}
}
if (replacedBy != null) {
renameMap.put(obsObj, replacedBy);
}
}
}
for (OWLEntity obsObj : renameMap.keySet()) {
IRI replacedBy = renameMap.get(obsObj);
if (obsObj instanceof OWLClass) {
axiomsToPreserve.addAll(ontology.getAxioms((OWLClass) obsObj, Imports.EXCLUDED));
}
if (obsObj instanceof OWLObjectProperty) {
axiomsToPreserve.addAll(ontology.getAxioms((OWLObjectProperty) obsObj, Imports.EXCLUDED));
}
axiomsToPreserve.addAll(ontology.getDeclarationAxioms(obsObj));
axiomsToPreserve.addAll(
ontology
.getAnnotationAssertionAxioms(obsObj.getIRI())
.stream()
.filter(ax -> !migrateAnnotations.contains(ax.getProperty()))
.collect(Collectors.toSet()));
logger.info("Replacing: " + obsObj + " -> " + replacedBy);
}
logger.info("PRESERVE: " + axiomsToPreserve);
manager.removeAxioms(ontology, axiomsToPreserve);
List<OWLOntologyChange> changes = new ArrayList<>(renamer.changeIRI(renameMap));
manager.applyChanges(changes);
manager.addAxioms(ontology, axiomsToPreserve);
}
} |
package ca.uwaterloo.joos.ast.decl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ca.uwaterloo.joos.ast.ASTNode;
import ca.uwaterloo.joos.ast.body.TypeBody;
import ca.uwaterloo.joos.ast.descriptor.ChildDescriptor;
import ca.uwaterloo.joos.ast.descriptor.ChildListDescriptor;
import ca.uwaterloo.joos.ast.type.InterfaceType;
import ca.uwaterloo.joos.ast.type.Modifiers;
import ca.uwaterloo.joos.parser.ParseTree.LeafNode;
import ca.uwaterloo.joos.parser.ParseTree.Node;
import ca.uwaterloo.joos.parser.ParseTree.TreeNode;
import ca.uwaterloo.joos.parser.ParseTreeTraverse;
public abstract class TypeDeclaration extends ASTNode {
protected static final ChildDescriptor MODIFIERS = new ChildDescriptor(Modifiers.class);
protected static final ChildListDescriptor INTERFACES = new ChildListDescriptor(InterfaceType.class);
protected static final ChildDescriptor BODY = new ChildDescriptor(TypeBody.class);
public TypeDeclaration(Node node, ASTNode parent) throws Exception {
super(parent);
assert node instanceof TreeNode : "TypeDeclaration is expecting a TreeNode";
ParseTreeTraverse traverse = new ParseTreeTraverse(this);
traverse.traverse(node);
}
public Modifiers getModifiers() throws ChildTypeUnmatchException {
return (Modifiers) this.getChildByDescriptor(TypeDeclaration.MODIFIERS);
}
public List<ASTNode> getInterfaces() throws ChildTypeUnmatchException {
return this.getChildByDescriptor(TypeDeclaration.INTERFACES);
}
public TypeBody getBody() throws ChildTypeUnmatchException {
return (TypeBody) this.getChildByDescriptor(TypeDeclaration.BODY);
}
@Override
public Set<Node> processTreeNode(TreeNode treeNode) throws Exception {
Set<Node> offers = new HashSet<Node>();
if (treeNode.productionRule.getLefthand().equals("modifiers")) {
addChild(MODIFIERS, new Modifiers(treeNode, this));
} else if (treeNode.productionRule.getLefthand().equals("interfaces")) {
List<ASTNode> interfaces = getInterfaces();
if (interfaces == null) {
interfaces = new ArrayList<ASTNode>();
addChild(INTERFACES, interfaces);
}
InterfaceType interfaceType = new InterfaceType(this);
interfaces.add(interfaceType);
} else if (treeNode.productionRule.getLefthand().equals("classbody")) {
// addChild(BODY, new ClassBody(treeNode, this));
} else {
for (Node n : treeNode.children)
offers.add(n);
}
return offers;
}
@Override
public void processLeafNode(LeafNode leafNode) throws Exception {
if (leafNode.token.getKind().equals("ID")) {
setIdentifier(leafNode.token.getLexeme());
}
}
} |
package com.akjava.bvh.client.threejs;
import java.util.ArrayList;
import java.util.List;
import com.akjava.bvh.client.BVHNode;
import com.akjava.bvh.client.Channels;
import com.akjava.bvh.client.Vec3;
import com.akjava.gwt.lib.client.LogUtils;
import com.akjava.gwt.three.client.core.Matrix4;
import com.akjava.gwt.three.client.core.Vector3;
import com.akjava.gwt.three.client.gwt.GWTThreeUtils;
import com.akjava.gwt.three.client.gwt.animation.AnimationBone;
import com.google.gwt.core.client.JsArray;
public class BVHConverter {
public BVHNode convertBVHNode(JsArray<AnimationBone> bones){
List<BVHNode> bvhs=new ArrayList<BVHNode>();
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
BVHNode node=boneToBVHNode(bone);
bvhs.add(node);
//add parent
if(bone.getParent()!=-1){
bvhs.get(bone.getParent()).add(node);
}
}
//add endsite
for(BVHNode node:bvhs){
if(node.getJoints().size()==0){//empty has end site
Vec3 endSite=node.getOffset().clone();//.multiplyScalar(2);
node.setEndSite(endSite);
}
}
return bvhs.get(0);
}
public double[] matrixsToMotion(List<Matrix4> matrixs,int mode,String order){
List<Double> values=new ArrayList<Double>();
for(int i=0;i<matrixs.size();i++){
Matrix4 mx=matrixs.get(i);
if((i==0 && mode==ROOT_POSITION_ROTATE_ONLY) || mode==POSITION_ROTATE){
Vector3 pos=GWTThreeUtils.toPositionVec(mx);
values.add(pos.getX());
values.add(pos.getY());
values.add(pos.getZ());
}
Vector3 tmprot=GWTThreeUtils.rotationToVector3(mx);
//TODO order convert;
if(!order.equals("XYZ")){
LogUtils.log("Warning:only support-XYZ");
}
Vector3 rotDegree=GWTThreeUtils.radiantToDegree(tmprot);
values.add(rotDegree.getX());
values.add(rotDegree.getY());
values.add(rotDegree.getZ());
}
double[] bt=new double[values.size()];
for(int i=0;i<values.size();i++){
bt[i]=values.get(i).doubleValue();
}
return bt;
}
private BVHNode boneToBVHNode(AnimationBone bone){
BVHNode bvhNode=new BVHNode();
bvhNode.setName(bone.getName());
Vec3 pos=new Vec3(bone.getPos().get(0),bone.getPos().get(1),bone.getPos().get(2));
bvhNode.setOffset(pos);
//problem no angle
//no channels
return bvhNode;
}
public static int ROOT_POSITION_ROTATE_ONLY=0;
public static int ROTATE_ONLY=1;
public static int POSITION_ROTATE=2;
public void setChannels(BVHNode node,int mode,String order){
Channels ch=new Channels();
if(mode==ROOT_POSITION_ROTATE_ONLY || mode==POSITION_ROTATE){
ch.setXposition(true);
ch.setYposition(true);
ch.setZposition(true);
}
if(order.equals("XZY")){
ch.setXrotation(true);
ch.setZrotation(true);
ch.setYrotation(true);
}else if(order.equals("YZX")){
ch.setYrotation(true);
ch.setZrotation(true);
ch.setXrotation(true);
}else if(order.equals("YXZ")){
ch.setYrotation(true);
ch.setXrotation(true);
ch.setZrotation(true);
}else if(order.equals("ZXY")){
ch.setZrotation(true);
ch.setXrotation(true);
ch.setYrotation(true);
}else if(order.equals("ZYX")){
ch.setZrotation(true);
ch.setYrotation(true);
ch.setXrotation(true);
}else{//XYZ
ch.setXrotation(true);
ch.setYrotation(true);
ch.setZrotation(true);
}
node.setChannels(ch);
for(BVHNode child:node.getJoints()){
int m=mode;
if(mode==ROOT_POSITION_ROTATE_ONLY){
m=ROTATE_ONLY;
}
setChannels(child,m,order);
}
}
} |
package com.fieldexpert.fbapi4j;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.fieldexpert.fbapi4j.common.Attachment;
public class DefaultCaseBuilder {
private String project;
private String area;
public DefaultCaseBuilder(String project, String area) {
this.project = project;
this.area = area;
}
public Case build(Throwable t, boolean attachStackTrace) {
StackTraceElement firstCause = getFirstCause(t).getStackTrace()[0];
String className = firstCause.getClassName();
String exceptionName = firstCause.getClass().getName();
String fileName = firstCause.getFileName();
int lineNumber = firstCause.getLineNumber();
String title = exceptionName + " " + className + ":" + fileName + ":" + lineNumber;
StringBuilder description = new StringBuilder();
description.append(exceptionName + " \n");
description.append(className + "\n");
description.append(fileName + ":" + lineNumber + "\n");
description.append("\n");
StringWriter stackTraceWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stackTraceWriter);
t.printStackTrace(pw);
if (!attachStackTrace) {
description.append(stackTraceWriter.toString());
}
Case fbCase = new Case(getProject(), getArea(), title, description.toString());
if (attachStackTrace) {
Attachment attachment = new Attachment(exceptionName + ".txt", "text/plain", stackTraceWriter.toString());
fbCase.attach(attachment);
}
return fbCase;
}
public Case build(Throwable t) {
return build(t, true);
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
private Throwable getFirstCause(Throwable e) {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
}
return t;
}
} |
package com.fsck.k9.activity.setup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.RingtonePreference;
import android.util.Log;
import android.view.KeyEvent;
import com.fsck.k9.Account;
import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.ChooseIdentity;
import com.fsck.k9.activity.ColorPickerDialog;
import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.activity.ManageIdentities;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.crypto.Apg;
import com.fsck.k9.mail.Store;
import com.fsck.k9.service.MailService;
public class AccountSettings extends K9PreferenceActivity
{
private static final String EXTRA_ACCOUNT = "account";
private static final int SELECT_AUTO_EXPAND_FOLDER = 1;
private static final int ACTIVITY_MANAGE_IDENTITIES = 2;
private static final String PREFERENCE_TOP_CATERGORY = "account_settings";
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_COMPOSITION = "composition";
private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_HIDE_BUTTONS = "hide_buttons_enum";
private static final String PREFERENCE_HIDE_MOVE_BUTTONS = "hide_move_buttons_enum";
private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum";
private static final String PREFERENCE_ENABLE_MOVE_BUTTONS = "enable_move_buttons";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self";
private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern";
private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_NOTIFICATION_LED = "account_led";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode";
private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode";
private static final String PREFERENCE_PUSH_MODE = "folder_push_mode";
private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect";
private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders";
private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period";
private static final String PREFERENCE_TARGET_MODE = "folder_target_mode";
private static final String PREFERENCE_DELETE_POLICY = "delete_policy";
private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy";
private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder";
private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders";
private static final String PREFERENCE_CHIP_COLOR = "chip_color";
private static final String PREFERENCE_LED_COLOR = "led_color";
private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread";
private static final String PREFERENCE_MESSAGE_AGE = "account_message_age";
private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size";
private static final String PREFERENCE_SAVE_ALL_HEADERS = "account_save_all_headers";
private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix";
private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote";
private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions";
private static final String PREFERENCE_CRYPTO_APP = "crypto_app";
private static final String PREFERENCE_CRYPTO_AUTO_SIGNATURE = "crypto_auto_signature";
private Account mAccount;
private boolean mIsPushCapable = false;
private boolean mIsExpungeCapable = false;
private EditTextPreference mAccountDescription;
private ListPreference mCheckFrequency;
private ListPreference mDisplayCount;
private ListPreference mMessageAge;
private ListPreference mMessageSize;
private CheckBoxPreference mAccountDefault;
private CheckBoxPreference mAccountNotify;
private CheckBoxPreference mAccountNotifySelf;
private ListPreference mAccountHideButtons;
private ListPreference mAccountHideMoveButtons;
private ListPreference mAccountShowPictures;
private CheckBoxPreference mAccountEnableMoveButtons;
private CheckBoxPreference mAccountNotifySync;
private CheckBoxPreference mAccountVibrate;
private CheckBoxPreference mAccountLed;
private ListPreference mAccountVibratePattern;
private ListPreference mAccountVibrateTimes;
private RingtonePreference mAccountRingtone;
private ListPreference mDisplayMode;
private ListPreference mSyncMode;
private ListPreference mPushMode;
private ListPreference mTargetMode;
private ListPreference mDeletePolicy;
private ListPreference mExpungePolicy;
private ListPreference mSearchableFolders;
private Preference mAutoExpandFolder;
private Preference mChipColor;
private Preference mLedColor;
private boolean mIncomingChanged = false;
private CheckBoxPreference mNotificationOpensUnread;
private EditTextPreference mAccountQuotePrefix;
private CheckBoxPreference mReplyAfterQuote;
private CheckBoxPreference mSyncRemoteDeletions;
private CheckBoxPreference mSaveAllHeaders;
private CheckBoxPreference mPushPollOnConnect;
private ListPreference mIdleRefreshPeriod;
private ListPreference mMaxPushFolders;
private ListPreference mCryptoApp;
private CheckBoxPreference mCryptoAutoSignature;
public static void actionSettings(Context context, Account account)
{
Intent i = new Intent(context, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
Preference category = findPreference(PREFERENCE_TOP_CATERGORY);
category.setTitle(getString(R.string.account_settings_title_fmt));
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
mAutoExpandFolder = (Preference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
mAutoExpandFolder.setSummary(translateFolder(mAccount.getAutoExpandFolderName()));
mAutoExpandFolder.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseAutoExpandFolder();
return false;
}
});
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
private void handleCryptoAppDependencies()
{
if ("".equals(mCryptoApp.getValue()))
{
mCryptoAutoSignature.setEnabled(false);
}
else
{
mCryptoAutoSignature.setEnabled(true);
}
}
@Override
public void onResume()
{
super.onResume();
}
private void saveSettings()
{
if (mAccountDefault.isChecked())
{
Preferences.getPreferences(this).setDefaultAccount(mAccount);
}
mAccount.setDescription(mAccountDescription.getText());
mAccount.setNotifyNewMail(mAccountNotify.isChecked());
mAccount.setNotifySelfNewMail(mAccountNotifySelf.isChecked());
mAccount.setShowOngoing(mAccountNotifySync.isChecked());
mAccount.setDisplayCount(Integer.parseInt(mDisplayCount.getValue()));
mAccount.setMaximumPolledMessageAge(Integer.parseInt(mMessageAge.getValue()));
mAccount.setMaximumAutoDownloadMessageSize(Integer.parseInt(mMessageSize.getValue()));
mAccount.getNotificationSetting().setVibrate(mAccountVibrate.isChecked());
mAccount.getNotificationSetting().setVibratePattern(Integer.parseInt(mAccountVibratePattern.getValue()));
mAccount.getNotificationSetting().setVibrateTimes(Integer.parseInt(mAccountVibrateTimes.getValue()));
mAccount.getNotificationSetting().setLed(mAccountLed.isChecked());
mAccount.setGoToUnreadMessageSearch(mNotificationOpensUnread.isChecked());
mAccount.setFolderTargetMode(Account.FolderMode.valueOf(mTargetMode.getValue()));
mAccount.setDeletePolicy(Integer.parseInt(mDeletePolicy.getValue()));
mAccount.setExpungePolicy(mExpungePolicy.getValue());
mAccount.setSyncRemoteDeletions(mSyncRemoteDeletions.isChecked());
mAccount.setSaveAllHeaders(mSaveAllHeaders.isChecked());
mAccount.setSearchableFolders(Account.Searchable.valueOf(mSearchableFolders.getValue()));
mAccount.setQuotePrefix(mAccountQuotePrefix.getText());
mAccount.setReplyAfterQuote(mReplyAfterQuote.isChecked());
mAccount.setCryptoApp(mCryptoApp.getValue());
mAccount.setCryptoAutoSignature(mCryptoAutoSignature.isChecked());
if (mIsPushCapable)
{
mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked());
mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue()));
mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue()));
}
boolean needsRefresh = mAccount.setAutomaticCheckIntervalMinutes(Integer.parseInt(mCheckFrequency.getValue()));
needsRefresh |= mAccount.setFolderSyncMode(Account.FolderMode.valueOf(mSyncMode.getValue()));
boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue()));
boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue()));
if (mAccount.getFolderPushMode() != FolderMode.NONE)
{
needsPushRestart |= displayModeChanged;
needsPushRestart |= mIncomingChanged;
}
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null);
if (newRingtone != null)
{
mAccount.getNotificationSetting().setRing(true);
mAccount.getNotificationSetting().setRingtone(newRingtone);
}
else
{
if (mAccount.getNotificationSetting().shouldRing())
{
mAccount.getNotificationSetting().setRingtone(null);
}
}
mAccount.setHideMessageViewButtons(Account.HideButtons.valueOf(mAccountHideButtons.getValue()));
mAccount.setHideMessageViewMoveButtons(Account.HideButtons.valueOf(mAccountHideMoveButtons.getValue()));
mAccount.setShowPictures(Account.ShowPictures.valueOf(mAccountShowPictures.getValue()));
mAccount.setEnableMoveButtons(mAccountEnableMoveButtons.isChecked());
mAccount.setAutoExpandFolderName(reverseTranslateFolder(mAutoExpandFolder.getSummary().toString()));
mAccount.save(Preferences.getPreferences(this));
if (needsRefresh && needsPushRestart)
{
MailService.actionReset(this, null);
}
else if (needsRefresh)
{
MailService.actionReschedulePoll(this, null);
}
else if (needsPushRestart)
{
MailService.actionRestartPushers(this, null);
}
// TODO: refresh folder list here
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case SELECT_AUTO_EXPAND_FOLDER:
mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
saveSettings();
}
return super.onKeyDown(keyCode, event);
}
private void onCompositionSettings()
{
AccountSetupComposition.actionEditCompositionSettings(this, mAccount);
}
private void onManageIdentities()
{
Intent intent = new Intent(this, ManageIdentities.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid());
startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES);
}
private void onIncomingSettings()
{
AccountSetupIncoming.actionEditIncomingSettings(this, mAccount);
}
private void onOutgoingSettings()
{
AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount);
}
public void onChooseChipColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.setChipColor(color);
}
},
mAccount.getChipColor()).show();
}
public void onChooseLedColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.getNotificationSetting().setLedColor(color);
}
},
mAccount.getNotificationSetting().getLedColor()).show();
}
public void onChooseAutoExpandFolder()
{
Intent selectIntent = new Intent(this, ChooseFolder.class);
selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mAutoExpandFolder.getSummary());
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes");
startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER);
}
private String translateFolder(String in)
{
if (K9.INBOX.equalsIgnoreCase(in))
{
return getString(R.string.special_mailbox_name_inbox);
}
else
{
return in;
}
}
private String reverseTranslateFolder(String in)
{
if (getString(R.string.special_mailbox_name_inbox).equals(in))
{
return K9.INBOX;
}
else
{
return in;
}
}
private void doVibrateTest(Preference preference)
{
// Do the vibration to show the user what it's like.
Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = MessagingController.getVibratePattern(
Integer.parseInt(mAccountVibratePattern.getValue()),
Integer.parseInt(mAccountVibrateTimes.getValue()));
vibrate.vibrate(pattern, -1);
}
} |
package com.fsck.k9.controller;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
import com.fsck.k9.K9;
import com.fsck.k9.K9.NotificationHideSubject;
import com.fsck.k9.K9.Intents;
import com.fsck.k9.K9.NotificationQuickDelete;
import com.fsck.k9.NotificationSetting;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.Accounts;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.activity.NotificationDeleteConfirmation;
import com.fsck.k9.activity.setup.AccountSetupIncoming;
import com.fsck.k9.activity.setup.AccountSetupOutgoing;
import com.fsck.k9.cache.EmailProviderCache;
import com.fsck.k9.helper.Contacts;
import com.fsck.k9.helper.NotificationBuilder;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.CertificateValidationException;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.mail.store.LocalStore.PendingCommand;
import com.fsck.k9.mail.store.Pop3Store;
import com.fsck.k9.mail.store.UnavailableAccountException;
import com.fsck.k9.mail.store.UnavailableStorageException;
import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.StatsColumns;
import com.fsck.k9.search.ConditionsTreeNode;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.Searchfield;
import com.fsck.k9.search.SqlQueryBuilder;
import com.fsck.k9.service.NotificationActionService;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
public static final long INVALID_MESSAGE_ID = -1;
/**
* Immutable empty {@link String} array
*/
private static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* Immutable empty {@link Message} array
*/
private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0];
/**
* Immutable empty {@link Folder} array
*/
private static final Folder[] EMPTY_FOLDER_ARRAY = new Folder[0];
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW = "com.fsck.k9.MessagingController.moveOrCopyBulkNew";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
public static class UidReverseComparator implements Comparator<Message> {
@Override
public int compare(Message o1, Message o2) {
if (o1 == null || o2 == null || o1.getUid() == null || o2.getUid() == null) {
return 0;
}
int id1, id2;
try {
id1 = Integer.parseInt(o1.getUid());
id2 = Integer.parseInt(o2.getUid());
} catch (NumberFormatException e) {
return 0;
}
//reversed intentionally.
if (id1 < id2)
return 1;
if (id1 > id2)
return -1;
return 0;
}
}
/**
* Maximum number of unsynced messages to store at once
*/
private static final int UNSYNC_CHUNK_SIZE = 5;
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private final ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
/**
* {@link K9}
*/
private Application mApplication;
/**
* A holder class for pending notification data
*
* This class holds all pieces of information for constructing
* a notification with message preview.
*/
private static class NotificationData {
/** Number of unread messages before constructing the notification */
int unreadBeforeNotification;
/**
* List of messages that should be used for the inbox-style overview.
* It's sorted from newest to oldest message.
* Don't modify this list directly, but use {@link addMessage} and
* {@link removeMatchingMessage} instead.
*/
LinkedList<Message> messages;
/**
* List of references for messages that the user is still to be notified of,
* but which don't fit into the inbox style anymore. It's sorted from newest
* to oldest message.
*/
LinkedList<MessageReference> droppedMessages;
/**
* Maximum number of messages to keep for the inbox-style overview.
* As of Jellybean, phone notifications show a maximum of 5 lines, while tablet
* notifications show 7 lines. To make sure no lines are silently dropped,
* we default to 5 lines.
*/
private final static int MAX_MESSAGES = 5;
/**
* Constructs a new data instance.
*
* @param unread Number of unread messages prior to instance construction
*/
public NotificationData(int unread) {
unreadBeforeNotification = unread;
droppedMessages = new LinkedList<MessageReference>();
messages = new LinkedList<Message>();
}
/**
* Adds a new message to the list of pending messages for this notification.
*
* The implementation will take care of keeping a meaningful amount of
* messages in {@link #messages}.
*
* @param m The new message to add.
*/
public void addMessage(Message m) {
while (messages.size() >= MAX_MESSAGES) {
Message dropped = messages.removeLast();
droppedMessages.addFirst(dropped.makeMessageReference());
}
messages.addFirst(m);
}
/**
* Remove a certain message from the message list.
*
* @param context A context.
* @param ref Reference of the message to remove
* @return true if message was found and removed, false otherwise
*/
public boolean removeMatchingMessage(Context context, MessageReference ref) {
for (MessageReference dropped : droppedMessages) {
if (dropped.equals(ref)) {
droppedMessages.remove(dropped);
return true;
}
}
for (Message message : messages) {
if (message.makeMessageReference().equals(ref)) {
if (messages.remove(message) && !droppedMessages.isEmpty()) {
Message restoredMessage = droppedMessages.getFirst().restoreToLocalMessage(context);
if (restoredMessage != null) {
messages.addLast(restoredMessage);
droppedMessages.removeFirst();
}
}
return true;
}
}
return false;
}
/**
* Gets a list of references for all pending messages for the notification.
*
* @return Message reference list
*/
public ArrayList<MessageReference> getAllMessageRefs() {
ArrayList<MessageReference> refs = new ArrayList<MessageReference>();
for (Message m : messages) {
refs.add(m.makeMessageReference());
}
refs.addAll(droppedMessages);
return refs;
}
/**
* Gets the total number of messages the user is to be notified of.
*
* @return Amount of new messages the notification notifies for
*/
public int getNewMessageCount() {
return messages.size() + droppedMessages.size();
}
};
// Key is accountNumber
private ConcurrentHashMap<Integer, NotificationData> notificationData = new ConcurrentHashMap<Integer, NotificationData>();
private static final Flag[] SYNC_FLAGS = new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED };
private void suppressMessages(Account account, List<Message> messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
cache.hideMessages(messages);
}
private void unsuppressMessages(Account account, Message[] messages) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
cache.unhideMessages(messages);
}
private boolean isMessageSuppressed(Account account, Message message) {
LocalMessage localMessage = (LocalMessage) message;
String accountUuid = account.getUuid();
long messageId = localMessage.getId();
long folderId = ((LocalFolder) localMessage.getFolder()).getId();
EmailProviderCache cache = EmailProviderCache.getCache(accountUuid,
mApplication.getApplicationContext());
return cache.isMessageHidden(messageId, folderId);
}
private void setFlagInCache(final Account account, final List<Long> messageIds,
final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForMessages(messageIds, columnName, value);
}
private void removeFlagFromCache(final Account account, final List<Long> messageIds,
final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForMessages(messageIds, columnName);
}
private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag);
String value = Integer.toString((newState) ? 1 : 0);
cache.setValueForThreads(threadRootIds, columnName, value);
}
private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds,
final Flag flag) {
EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(),
mApplication.getApplicationContext());
String columnName = LocalStore.getColumnNameForFlag(flag);
cache.removeValueForThreads(messageIds, columnName);
}
/**
* @param application {@link K9}
*/
private MessagingController(Application application) {
mApplication = application;
mThread = new Thread(this);
mThread.setName("MessagingController");
mThread.start();
if (memorizingListener != null) {
addListener(memorizingListener);
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application {@link K9}
* @return
*/
public synchronized static MessagingController getInstance(Application application) {
if (inst == null) {
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy() {
return mBusy;
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
String commandDescription = null;
try {
final Command command = mCommands.take();
if (command != null) {
commandDescription = command.description;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
try {
command.runnable.run();
} catch (UnavailableAccountException e) {
// retry later
new Thread() {
@Override
public void run() {
try {
sleep(30 * 1000);
mCommands.put(command);
} catch (InterruptedException e) {
Log.e(K9.LOG_TAG, "interrupted while putting a pending command for"
+ " an unavailable account back into the queue."
+ " THIS SHOULD NEVER HAPPEN.");
}
}
} .start();
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") +
" Command '" + command.description + "' completed");
for (MessagingListener l : getListeners(command.listener)) {
l.controllerCommandCompleted(!mCommands.isEmpty());
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) {
int retries = 10;
Exception e = null;
while (retries
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
} catch (InterruptedException ie) {
try {
Thread.sleep(200);
} catch (InterruptedException ne) {
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener) {
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener) {
if (memorizingListener != null && listener != null) {
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener) {
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners() {
return mListeners;
}
public Set<MessagingListener> getListeners(MessagingListener listener) {
if (listener == null) {
return mListeners;
}
Set<MessagingListener> listeners = new HashSet<MessagingListener>(mListeners);
listeners.add(listener);
return listeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
listFoldersSynchronous(account, refreshRemote, listener);
}
});
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method is called in the
* foreground.
* TODO this needs to cache the remote folder list
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersStarted(account);
}
List <? extends Folder > localFolders = null;
if (!account.isAvailable(mApplication)) {
Log.i(K9.LOG_TAG, "not listing folders of unavailable account");
} else {
try {
Store localStore = account.getLocalStore();
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY);
if (refreshRemote || localFolders.isEmpty()) {
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners(listener)) {
l.listFolders(account, folderArray);
}
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, null, e);
return;
} finally {
if (localFolders != null) {
for (Folder localFolder : localFolders) {
closeFolder(localFolder);
}
}
}
}
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFinished(account);
}
}
private void doRefreshRemote(final Account account, final MessagingListener listener) {
put("doRefreshRemote", listener, new Runnable() {
@Override
public void run() {
List <? extends Folder > localFolders = null;
try {
Store store = account.getRemoteStore();
List <? extends Folder > remoteFolders = store.getPersonalNamespaces(false);
LocalStore localStore = account.getLocalStore();
HashSet<String> remoteFolderNames = new HashSet<String>();
List<LocalFolder> foldersToCreate = new LinkedList<LocalFolder>();
localFolders = localStore.getPersonalNamespaces(false);
HashSet<String> localFolderNames = new HashSet<String>();
for (Folder localFolder : localFolders) {
localFolderNames.add(localFolder.getName());
}
for (Folder remoteFolder : remoteFolders) {
if (localFolderNames.contains(remoteFolder.getName()) == false) {
LocalFolder localFolder = localStore.getFolder(remoteFolder.getName());
foldersToCreate.add(localFolder);
}
remoteFolderNames.add(remoteFolder.getName());
}
localStore.createFolders(foldersToCreate, account.getDisplayCount());
localFolders = localStore.getPersonalNamespaces(false);
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders) {
String localFolderName = localFolder.getName();
// FIXME: This is a hack used to clean up when we accidentally created the
// special placeholder folder "-NONE-".
if (K9.FOLDER_NONE.equals(localFolderName)) {
localFolder.delete(false);
}
if (!account.isSpecialFolder(localFolderName) &&
!remoteFolderNames.contains(localFolderName)) {
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY);
for (MessagingListener l : getListeners(listener)) {
l.listFolders(account, folderArray);
}
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFinished(account);
}
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.listFoldersFailed(account, "");
}
addErrorMessage(account, null, e);
} finally {
if (localFolders != null) {
for (Folder localFolder : localFolders) {
closeFolder(localFolder);
}
}
}
}
});
}
/**
* Find all messages in any local account which match the query 'query'
* @throws MessagingException
*/
public void searchLocalMessages(final LocalSearch search, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
searchLocalMessagesSynchronous(search, listener);
}
});
}
public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) {
final AccountStats stats = new AccountStats();
final HashSet<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids()));
Account[] accounts = Preferences.getPreferences(mApplication.getApplicationContext()).getAccounts();
boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS);
// for every account we want to search do the query in the localstore
for (final Account account : accounts) {
if (!allAccounts && !uuidSet.contains(account.getUuid())) {
continue;
}
// Collecting statistics of the search result
MessageRetrievalListener retrievalListener = new MessageRetrievalListener() {
@Override
public void messageStarted(String message, int number, int ofTotal) {}
@Override
public void messagesFinished(int number) {}
@Override
public void messageFinished(Message message, int number, int ofTotal) {
if (!isMessageSuppressed(message.getFolder().getAccount(), message)) {
List<Message> messages = new ArrayList<Message>();
messages.add(message);
stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0;
stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0;
if (listener != null) {
listener.listLocalMessagesAddMessages(account, null, messages);
}
}
}
};
// alert everyone the search has started
if (listener != null) {
listener.listLocalMessagesStarted(account, null);
}
// build and do the query in the localstore
try {
LocalStore localStore = account.getLocalStore();
localStore.searchForMessages(retrievalListener, search);
} catch (Exception e) {
if (listener != null) {
listener.listLocalMessagesFailed(account, null, e.getMessage());
}
addErrorMessage(account, null, e);
} finally {
if (listener != null) {
listener.listLocalMessagesFinished(account, null);
}
}
}
// publish the total search statistics
if (listener != null) {
listener.searchStats(stats);
}
}
public Future<?> searchRemoteMessages(final String acctUuid, final String folderName, final String query,
final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) {
if (K9.DEBUG) {
String msg = "searchRemoteMessages ("
+ "acct=" + acctUuid
+ ", folderName = " + folderName
+ ", query = " + query
+ ")";
Log.i(K9.LOG_TAG, msg);
}
return threadPool.submit(new Runnable() {
@Override
public void run() {
searchRemoteMessagesSynchronous(acctUuid, folderName, query, requiredFlags, forbiddenFlags, listener);
}
});
}
public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query,
final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) {
final Account acct = Preferences.getPreferences(mApplication.getApplicationContext()).getAccount(acctUuid);
if (listener != null) {
listener.remoteSearchStarted(acct, folderName);
}
List<Message> extraResults = new ArrayList<Message>();
try {
Store remoteStore = acct.getRemoteStore();
LocalStore localStore = acct.getLocalStore();
if (remoteStore == null || localStore == null) {
throw new MessagingException("Could not get store");
}
Folder remoteFolder = remoteStore.getFolder(folderName);
LocalFolder localFolder = localStore.getFolder(folderName);
if (remoteFolder == null || localFolder == null) {
throw new MessagingException("Folder not found");
}
List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags);
if (K9.DEBUG) {
Log.i("Remote Search", "Remote search got " + messages.size() + " results");
}
// There's no need to fetch messages already completely downloaded
List<Message> remoteMessages = localFolder.extractNewMessages(messages);
messages.clear();
if (listener != null) {
listener.remoteSearchServerQueryComplete(acct, folderName, remoteMessages.size());
}
Collections.sort(remoteMessages, new UidReverseComparator());
int resultLimit = acct.getRemoteSearchNumResults();
if (resultLimit > 0 && remoteMessages.size() > resultLimit) {
extraResults = remoteMessages.subList(resultLimit, remoteMessages.size());
remoteMessages = remoteMessages.subList(0, resultLimit);
}
loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener);
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
Log.i(K9.LOG_TAG, "Caught exception on aborted remote search; safe to ignore.", e);
} else {
Log.e(K9.LOG_TAG, "Could not complete remote search", e);
if (listener != null) {
listener.remoteSearchFailed(acct, null, e.getMessage());
}
addErrorMessage(acct, null, e);
}
} finally {
if (listener != null) {
listener.remoteSearchFinished(acct, folderName, 0, extraResults);
}
}
}
public void loadSearchResults(final Account account, final String folderName, final List<Message> messages, final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
if (listener != null) {
listener.enableProgressIndicator(true);
}
try {
Store remoteStore = account.getRemoteStore();
LocalStore localStore = account.getLocalStore();
if (remoteStore == null || localStore == null) {
throw new MessagingException("Could not get store");
}
Folder remoteFolder = remoteStore.getFolder(folderName);
LocalFolder localFolder = localStore.getFolder(folderName);
if (remoteFolder == null || localFolder == null) {
throw new MessagingException("Folder not found");
}
loadSearchResultsSynchronous(messages, localFolder, remoteFolder, listener);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Exception in loadSearchResults: " + e);
addErrorMessage(account, null, e);
} finally {
if (listener != null) {
listener.enableProgressIndicator(false);
}
}
}
});
}
public void loadSearchResultsSynchronous(List<Message> messages, LocalFolder localFolder, Folder remoteFolder, MessagingListener listener) throws MessagingException {
final FetchProfile header = new FetchProfile();
header.add(FetchProfile.Item.FLAGS);
header.add(FetchProfile.Item.ENVELOPE);
final FetchProfile structure = new FetchProfile();
structure.add(FetchProfile.Item.STRUCTURE);
int i = 0;
for (Message message : messages) {
i++;
LocalMessage localMsg = localFolder.getMessage(message.getUid());
if (localMsg == null) {
remoteFolder.fetch(new Message [] {message}, header, null);
//fun fact: ImapFolder.fetch can't handle getting STRUCTURE at same time as headers
remoteFolder.fetch(new Message [] {message}, structure, null);
localFolder.appendMessages(new Message [] {message});
localMsg = localFolder.getMessage(message.getUid());
}
if (listener != null) {
listener.remoteSearchAddMessage(remoteFolder.getAccount(), remoteFolder.getName(), localMsg, i, messages.size());
}
}
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener) {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
if (localFolder.getVisibleLimit() > 0) {
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
}
synchronizeMailbox(account, folder, listener, null);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Collection<Account> accounts) {
for (Account account : accounts) {
account.resetVisibleLimits();
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
* @param providedRemoteFolder TODO
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) {
putBackground("synchronizeMailbox", listener, new Runnable() {
@Override
public void run() {
synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
* @param providedRemoteFolder TODO
*/
private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) {
Folder remoteFolder = null;
LocalFolder tLocalFolder = null;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxStarted(account, folder);
}
/*
* We don't ever sync the Outbox or errors folder
*/
if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
return;
}
Exception commandException = null;
try {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription());
try {
processPendingCommandsSynchronous(account);
} catch (Exception e) {
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(Folder.OPEN_MODE_RW);
localFolder.updateLastUid();
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (providedRemoteFolder != null) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder);
remoteFolder = providedRemoteFolder;
} else {
Store remoteStore = account.getRemoteStore();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
remoteFolder = remoteStore.getFolder(folder);
if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) {
return;
}
/*
* Synchronization process:
*
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
remoteFolder.open(Folder.OPEN_MODE_RW);
if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
if (visibleLimit < 0) {
visibleLimit = K9.DEFAULT_VISIBLE_LIMIT;
}
Message[] remoteMessageArray = EMPTY_MESSAGE_ARRAY;
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount);
final Date earliestDate = account.getEarliestPollDate();
if (remoteMessageCount > 0) {
/* Message numbers start at 1. */
int remoteStart;
if (visibleLimit > 0) {
remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
} else {
remoteStart = 1;
}
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
final AtomicInteger headerProgress = new AtomicInteger(0);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersStarted(account, folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null);
int messageCount = remoteMessageArray.length;
for (Message thisMess : remoteMessageArray) {
headerProgress.incrementAndGet();
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount);
}
Message localMessage = localUidMap.get(thisMess.getUid());
if (localMessage == null || !localMessage.olderThan(earliestDate)) {
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
remoteMessageArray = null;
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size());
}
} else if (remoteMessageCount < 0) {
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store or are too old
*/
if (account.syncRemoteDeletions()) {
ArrayList<Message> destroyMessages = new ArrayList<Message>();
for (Message localMessage : localMessages) {
if (remoteUidMap.get(localMessage.getUid()) == null) {
destroyMessages.add(localMessage);
}
}
localFolder.destroyMessages(destroyMessages.toArray(EMPTY_MESSAGE_ARRAY));
for (Message destroyMessage : destroyMessages) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxRemovedMessage(account, folder, destroyMessage);
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, unreadMessageCount);
}
/* Notify listeners that we're finally done. */
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder +
" @ " + new Date() + " with " + newMessages + " new messages");
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null) {
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null) {
try {
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
notifyUserIfCertificateProblem(mApplication, e, account, true);
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date());
} finally {
if (providedRemoteFolder == null) {
closeFolder(remoteFolder);
}
closeFolder(tLocalFolder);
}
}
private void closeFolder(Folder f) {
if (f != null) {
f.close();
}
}
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException {
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners(listener)) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return false;
}
}
}
return true;
}
/**
* Fetches the messages described by inputMessages from the remote store and writes them to
* local storage.
*
* @param account
* The account the remote store belongs to.
* @param remoteFolder
* The remote folder to download messages from.
* @param localFolder
* The {@link LocalFolder} instance corresponding to the remote folder.
* @param inputMessages
* A list of messages objects that store the UIDs of which messages to download.
* @param flagSyncOnly
* Only flags will be fetched from the remote store if this is {@code true}.
*
* @return The number of downloaded messages that are not flagged as {@link Flag#SEEN}.
*
* @throws MessagingException
*/
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages,
boolean flagSyncOnly) throws MessagingException {
final Date earliestDate = account.getEarliestPollDate();
Date downloadStarted = new Date(); // now
if (earliestDate != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
int unreadBeforeStart = 0;
try {
AccountStats stats = account.getStats(mApplication);
unreadBeforeStart = stats.unreadMessageCount;
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages) {
evaluateMessageForDownload(message, folder, localFolder, remoteFolder, account, unsyncedMessages, syncFlagMessages , flagSyncOnly);
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (!unsyncedMessages.isEmpty()) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.sort(unsyncedMessages, new UidReverseComparator());
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if ((visibleLimit > 0) && (listSize > visibleLimit)) {
unsyncedMessages = unsyncedMessages.subList(0, visibleLimit);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp);
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages) {
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null) {
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, unreadBeforeStart, newMessages, todo, fp);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, unreadBeforeStart, newMessages, todo, fp);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener() {
@Override
public void messageRemoved(Message message) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
// If the oldest message seen on this sync is newer than
// the oldest message seen on the previous sync, then
// we want to move our high-water mark forward
// this is all here just for pop which only syncs inbox
// this would be a little wrong for IMAP (we'd want a folder-level pref, not an account level pref.)
// fortunately, we just don't care.
Long oldestMessageTime = localFolder.getOldestMessageDate();
if (oldestMessageTime != null) {
Date oldestExtantMessage = new Date(oldestMessageTime);
if (oldestExtantMessage.before(downloadStarted) &&
oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) {
account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime());
account.save(Preferences.getPreferences(mApplication.getApplicationContext()));
}
}
return newMessages.get();
}
private void evaluateMessageForDownload(final Message message, final String folder,
final LocalFolder localFolder,
final Folder remoteFolder,
final Account account,
final List<Message> unsyncedMessages,
final ArrayList<Message> syncFlagMessages,
boolean flagSyncOnly) throws MessagingException {
if (message.isSet(Flag.DELETED)) {
syncFlagMessages.add(message);
return;
}
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null) {
if (!flagSyncOnly) {
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
} else {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
} else if (!localMessage.isSet(Flag.DELETED)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
} else {
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null) {
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
List<Message> unsyncedMessages,
final ArrayList<Message> smallMessages,
final ArrayList<Message> largeMessages,
final AtomicInteger progress,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
/*
* Messages to be batch written
*/
final List<Message> chunk = new ArrayList<Message>(UNSYNC_CHUNK_SIZE);
remoteFolder.fetch(unsyncedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp,
new MessageRetrievalListener() {
@Override
public void messageFinished(Message message, int number, int ofTotal) {
try {
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null) {
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) {
if (K9.DEBUG) {
if (message.isSet(Flag.DELETED)) {
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was marked deleted on server, skipping");
} else {
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (account.getMaximumAutoDownloadMessageSize() > 0 &&
message.getSize() > account.getMaximumAutoDownloadMessageSize()) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null && message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
// keep message for delayed storing
chunk.add(message);
if (chunk.size() >= UNSYNC_CHUNK_SIZE) {
writeUnsyncedMessages(chunk, localFolder, account, folder);
chunk.clear();
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
@Override
public void messageStarted(String uid, int number, int ofTotal) {}
@Override
public void messagesFinished(int total) {
// FIXME this method is almost never invoked by various Stores! Don't rely on it unless fixed!!
}
});
if (!chunk.isEmpty()) {
writeUnsyncedMessages(chunk, localFolder, account, folder);
chunk.clear();
}
}
/**
* Actual storing of messages
*
* <br>
* FIXME: <strong>This method should really be moved in the above MessageRetrievalListener once {@link MessageRetrievalListener#messagesFinished(int)} is properly invoked by various stores</strong>
*
* @param messages Never <code>null</code>.
* @param localFolder
* @param account
* @param folder
*/
private void writeUnsyncedMessages(final List<Message> messages, final LocalFolder localFolder, final Account account, final String folder) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Batch writing " + Integer.toString(messages.size()) + " messages");
}
try {
// Store the new message locally
localFolder.appendMessages(messages.toArray(new Message[messages.size()]));
for (final Message message : messages) {
final Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (final MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
} catch (final Exception e) {
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) {
if (account.isSearchByDateCapable() && message.olderThan(earliestDate)) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
return false;
}
return true;
}
private void downloadSmallMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> smallMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener() {
@Override
public void messageFinished(final Message message, int number, int ofTotal) {
try {
if (!shouldImportMessage(account, folder, message, progress, earliestDate)) {
progress.incrementAndGet();
return;
}
// Store the updated message locally
final Message localMessage = localFolder.storeSmallMessage(message, new Runnable() {
@Override
public void run() {
progress.incrementAndGet();
}
});
// Increment the number of "new messages" if the newly downloaded message is
// not marked as read.
if (!localMessage.isSet(Flag.SEEN)) {
newMessages.incrementAndGet();
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview.
notifyAccount(mApplication, account, localMessage, unreadBeforeStart);
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
@Override
public void messageStarted(String uid, int number, int ofTotal) {}
@Override
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
private void downloadLargeMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> largeMessages,
final AtomicInteger progress,
final int unreadBeforeStart,
final AtomicInteger newMessages,
final int todo,
FetchProfile fp) throws MessagingException {
final String folder = remoteFolder.getName();
final Date earliestDate = account.getEarliestPollDate();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (!shouldImportMessage(account, folder, message, progress, earliestDate)) {
progress.incrementAndGet();
continue;
}
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* Mark the message as fully downloaded if the message size is smaller than
* the account's autodownload size limit, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*
* If there is no limit on autodownload size, that's the same as the message
* being smaller than the max size
*/
if (account.getMaximumAutoDownloadMessageSize() == 0 || message.getSize() < account.getMaximumAutoDownloadMessageSize()) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
Set<Part> viewables = MimeUtility.collectTextParts(message);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
// TODO do we need to re-fetch this here?
Message localMessage = localFolder.getMessage(message.getUid());
// Increment the number of "new messages" if the newly downloaded message is
// not marked as read.
if (!localMessage.isSet(Flag.SEEN)) {
newMessages.incrementAndGet();
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
// Send a notification of this message
if (shouldNotifyForMessage(account, localFolder, message)) {
// Notify with the localMessage so that we don't have to recalculate the content preview.
notifyAccount(mApplication, account, localMessage, unreadBeforeStart);
}
}//for large messages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder,
final LocalFolder localFolder,
ArrayList<Message> syncFlagMessages,
final AtomicInteger progress,
final int todo
) throws MessagingException {
final String folder = remoteFolder.getName();
if (remoteFolder.supportsFetchingFlags()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages) {
if (!message.isSet(Flag.DELETED)) {
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, null);
for (Message remoteMessage : syncFlagMessages) {
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged) {
boolean shouldBeNotifiedOf = false;
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, localMessage)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
} else {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
if (shouldNotifyForMessage(account, localFolder, localMessage)) {
shouldBeNotifiedOf = true;
}
}
// we're only interested in messages that need removing
if (!shouldBeNotifiedOf) {
NotificationData data = getNotificationData(account, null);
if (data != null) {
synchronized (data) {
MessageReference ref = localMessage.makeMessageReference();
if (data.removeMatchingMessage(mApplication, ref)) {
notifyAccountWithDataLocked(mApplication, account, null, data);
}
}
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException {
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED)) {
return false;
}
if (remoteMessage.isSet(Flag.DELETED)) {
if (localMessage.getFolder().getAccount().syncRemoteDeletions()) {
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
} else {
for (Flag flag : MessagingController.SYNC_FLAGS) {
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t) {
Throwable rootCause = t;
Throwable nextCause = rootCause;
do {
nextCause = rootCause.getCause();
if (nextCause != null) {
rootCause = nextCause;
}
} while (nextCause != null);
if (rootCause instanceof MessagingException) {
return rootCause.getMessage();
} else {
// Remove the namespace on the exception so we have a fighting chance of seeing more of the error in the
// notification.
return (rootCause.getLocalizedMessage() != null)
? (rootCause.getClass().getSimpleName() + ": " + rootCause.getLocalizedMessage())
: rootCause.getClass().getSimpleName();
}
}
private void queuePendingCommand(Account account, PendingCommand command) {
try {
LocalStore localStore = account.getLocalStore();
localStore.addPendingCommand(command);
} catch (Exception e) {
addErrorMessage(account, null, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account) {
putBackground("processPendingCommands", null, new Runnable() {
@Override
public void run() {
try {
processPendingCommandsSynchronous(account);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to process pending command because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, null, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException {
LocalStore localStore = account.getLocalStore();
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0) {
return;
}
for (MessagingListener l : getListeners()) {
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try {
for (PendingCommand command : commands) {
processingCommand = command;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners()) {
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try {
if (PENDING_COMMAND_APPEND.equals(command.command)) {
processPendingAppend(command, account);
} else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) {
processPendingSetFlag(command, account);
} else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) {
processPendingSetFlagOld(command, account);
} else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) {
processPendingMarkAllAsRead(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) {
processPendingMoveOrCopyOld2(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW.equals(command.command)) {
processPendingMoveOrCopy(command, account);
} else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) {
processPendingMoveOrCopyOld(command, account);
} else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) {
processPendingEmptyTrash(command, account);
} else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) {
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
} catch (MessagingException me) {
if (me.isPermanentFailure()) {
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
} else {
throw me;
}
} finally {
progress++;
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
} catch (MessagingException me) {
notifyUserIfCertificateProblem(mApplication, me, account, true);
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
} finally {
for (MessagingListener l : getListeners()) {
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder)) {
return;
}
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
LocalMessage localMessage = localFolder.getMessage(uid);
if (localMessage == null) {
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return;
}
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null) {
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) {
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null) {
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
} else {
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage } , fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
} else {
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0) {
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.destroy();
} else {
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
if (remoteDate != null) {
remoteMessage.setFlag(Flag.DELETED, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) {
remoteFolder.expunge();
}
}
}
}
} finally {
closeFolder(remoteFolder);
closeFolder(localFolder);
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) {
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
int length = 4 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
command.arguments[3] = Boolean.toString(false);
System.arraycopy(uids, 0, command.arguments, 4, uids.length);
queuePendingCommand(account, command);
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[], Map<String, String> uidMap) {
if (uidMap == null || uidMap.isEmpty()) {
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, uids);
} else {
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
int length = 4 + uidMap.keySet().size() + uidMap.values().size();
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
command.arguments[3] = Boolean.toString(true);
System.arraycopy(uidMap.keySet().toArray(), 0, command.arguments, 4, uidMap.keySet().size());
System.arraycopy(uidMap.values().toArray(), 0, command.arguments, 4 + uidMap.keySet().size(), uidMap.values().size());
queuePendingCommand(account, command);
}
}
/**
* Convert pending command to new format and call
* {@link #processPendingMoveOrCopy(PendingCommand, Account)}.
*
* <p>
* TODO: This method is obsolete and is only for transition from K-9 4.0 to K-9 4.2
* Eventually, it should be removed.
* </p>
*
* @param command
* Pending move/copy command in old format.
* @param account
* The account the pending command belongs to.
*
* @throws MessagingException
* In case of an error.
*/
private void processPendingMoveOrCopyOld2(PendingCommand command, Account account)
throws MessagingException {
PendingCommand newCommand = new PendingCommand();
int len = command.arguments.length;
newCommand.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW;
newCommand.arguments = new String[len + 1];
newCommand.arguments[0] = command.arguments[0];
newCommand.arguments[1] = command.arguments[1];
newCommand.arguments[2] = command.arguments[2];
newCommand.arguments[3] = Boolean.toString(false);
System.arraycopy(command.arguments, 3, newCommand.arguments, 4, len - 3);
processPendingMoveOrCopy(newCommand, account);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException {
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
LocalFolder localDestFolder = null;
try {
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
String hasNewUidsS = command.arguments[3];
boolean hasNewUids = false;
if (hasNewUidsS != null) {
hasNewUids = Boolean.parseBoolean(hasNewUidsS);
}
Store remoteStore = account.getRemoteStore();
remoteSrcFolder = remoteStore.getFolder(srcFolder);
Store localStore = account.getLocalStore();
localDestFolder = (LocalFolder) localStore.getFolder(destFolder);
List<Message> messages = new ArrayList<Message>();
/*
* We split up the localUidMap into two parts while sending the command, here we assemble it back.
*/
Map<String, String> localUidMap = new HashMap<String, String>();
if (hasNewUids) {
int offset = (command.arguments.length - 4) / 2;
for (int i = 4; i < 4 + offset; i++) {
localUidMap.put(command.arguments[i], command.arguments[i + offset]);
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteSrcFolder.getMessage(uid));
}
}
} else {
for (int i = 4; i < command.arguments.length; i++) {
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteSrcFolder.getMessage(uid));
}
}
}
boolean isCopy = false;
if (isCopyS != null) {
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists()) {
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(Folder.OPEN_MODE_RW);
if (remoteSrcFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
Map <String, String> remoteUidMap = null;
if (!isCopy && destFolder.equals(account.getTrashFolderName())) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName)) {
destFolderName = null;
}
remoteSrcFolder.delete(messages.toArray(EMPTY_MESSAGE_ARRAY), destFolderName);
} else {
remoteDestFolder = remoteStore.getFolder(destFolder);
if (isCopy) {
remoteUidMap = remoteSrcFolder.copyMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder);
} else {
remoteUidMap = remoteSrcFolder.moveMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder);
}
}
if (!isCopy && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
/*
* This next part is used to bring the local UIDs of the local destination folder
* upto speed with the remote UIDs of remote destionation folder.
*/
if (!localUidMap.isEmpty() && remoteUidMap != null && !remoteUidMap.isEmpty()) {
Set<Map.Entry<String, String>> remoteSrcEntries = remoteUidMap.entrySet();
Iterator<Map.Entry<String, String>> remoteSrcEntriesIterator = remoteSrcEntries.iterator();
while (remoteSrcEntriesIterator.hasNext()) {
Map.Entry<String, String> entry = remoteSrcEntriesIterator.next();
String remoteSrcUid = entry.getKey();
String localDestUid = localUidMap.get(remoteSrcUid);
String newUid = entry.getValue();
Message localDestMessage = localDestFolder.getMessage(localDestUid);
if (localDestMessage != null) {
localDestMessage.setUid(newUid);
localDestFolder.changeUid((LocalMessage)localDestMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, destFolder, localDestUid, newUid);
}
}
}
}
} finally {
closeFolder(remoteSrcFolder);
closeFolder(remoteDestFolder);
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) {
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() {
@Override
public void run() {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
System.arraycopy(uids, 0, command.arguments, 3, uids.length);
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder)) {
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(flag)) {
return;
}
try {
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++) {
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.isEmpty()) {
return;
}
remoteFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] { flag }, newState);
} finally {
closeFolder(remoteFolder);
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder)) {
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Folder remoteFolder = null;
try {
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null) {
return;
}
remoteMessage.setFlag(flag, newState);
} finally {
closeFolder(remoteFolder);
}
}
private void queueExpunge(final Account account, final String folderName) {
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() {
@Override
public void run() {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder)) {
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try {
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder);
} finally {
closeFolder(remoteFolder);
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException {
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null) {
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder)) {
return;
}
Store remoteStore = account.getRemoteStore();
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists()) {
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(Folder.OPEN_MODE_RW);
if (remoteSrcFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null) {
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (!isCopy && destFolder.equals(account.getTrashFolderName())) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(Folder.OPEN_MODE_RW);
if (remoteDestFolder.getMode() != Folder.OPEN_MODE_RW) {
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy) {
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
} else {
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException {
String folder = command.arguments[0];
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages) {
if (!message.isSet(Flag.SEEN)) {
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners()) {
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, 0);
}
if (account.getErrorFolderName().equals(folder)) {
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(Flag.SEEN)) {
return;
}
remoteFolder.open(Folder.OPEN_MODE_RW);
if (remoteFolder.getMode() != Folder.OPEN_MODE_RW) {
return;
}
remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true);
remoteFolder.close();
} catch (UnsupportedOperationException uoe) {
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
} finally {
closeFolder(localFolder);
closeFolder(remoteFolder);
}
}
private void notifyUserIfCertificateProblem(Context context, Exception e,
Account account, boolean incoming) {
if (!(e instanceof CertificateValidationException)) {
return;
}
CertificateValidationException cve = (CertificateValidationException) e;
if (!cve.needsUserAttention()) {
return;
}
final int id = incoming
? K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber()
: K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber();
final Intent i = incoming
? AccountSetupIncoming.intentActionEditIncomingSettings(context, account)
: AccountSetupOutgoing.intentActionEditOutgoingSettings(context, account);
final PendingIntent pi = PendingIntent.getActivity(context,
account.getAccountNumber(), i, PendingIntent.FLAG_UPDATE_CURRENT);
final String title = context.getString(
R.string.notification_certificate_error_title, account.getName());
final NotificationCompat.Builder builder = new NotificationBuilder(context);
builder.setSmallIcon(R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
builder.setTicker(title);
builder.setContentTitle(title);
builder.setContentText(context.getString(R.string.notification_certificate_error_text));
builder.setContentIntent(pi);
configureNotification(builder, null, null,
K9.NOTIFICATION_LED_FAILURE_COLOR,
K9.NOTIFICATION_LED_BLINK_FAST, true);
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(null, id, builder.build());
}
public void clearCertificateErrorNotifications(Context context,
final Account account, boolean incoming, boolean outgoing) {
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (incoming) {
nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber());
}
if (outgoing) {
nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber());
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, String subject, Throwable t) {
if (!loopCatch.compareAndSet(false, true)) {
return;
}
try {
if (t == null) {
return;
}
CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10);
PrintWriter ps = new PrintWriter(baos);
t.printStackTrace(ps);
ps.close();
if (subject == null) {
subject = getRootCauseMessage(t);
}
addErrorMessage(account, subject, baos.toString());
} catch (Throwable it) {
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
} finally {
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body) {
if (!K9.ENABLE_ERROR_FOLDER) {
return;
}
if (!loopCatch.compareAndSet(false, true)) {
return;
}
try {
if (body == null || body.length() < 1) {
return;
}
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000));
} catch (Throwable it) {
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
} finally {
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState) {
setFlagInCache(account, messageIds, flag, newState);
threadPool.execute(new Runnable() {
@Override
public void run() {
setFlagSynchronous(account, messageIds, flag, newState, false);
}
});
}
public void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState) {
setFlagForThreadsInCache(account, threadRootIds, flag, newState);
threadPool.execute(new Runnable() {
@Override
public void run() {
setFlagSynchronous(account, threadRootIds, flag, newState, true);
}
});
}
private void setFlagSynchronous(final Account account, final List<Long> ids,
final Flag flag, final boolean newState, final boolean threadedList) {
LocalStore localStore;
try {
localStore = account.getLocalStore();
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't get LocalStore instance", e);
return;
}
// Update affected messages in the database. This should be as fast as possible so the UI
// can be updated with the new state.
try {
if (threadedList) {
localStore.setFlagForThreads(ids, flag, newState);
removeFlagForThreadsFromCache(account, ids, flag);
} else {
localStore.setFlag(ids, flag, newState);
removeFlagFromCache(account, ids, flag);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't set flags in local database", e);
}
// Read folder name and UID of messages from the database
Map<String, List<String>> folderMap;
try {
folderMap = localStore.getFoldersAndUids(ids, threadedList);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Couldn't get folder name and UID of messages", e);
return;
}
// Loop over all folders
for (Entry<String, List<String>> entry : folderMap.entrySet()) {
String folderName = entry.getKey();
// Notify listeners of changed folder status
LocalFolder localFolder = localStore.getFolder(folderName);
try {
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
} catch (MessagingException e) {
Log.w(K9.LOG_TAG, "Couldn't get unread count for folder: " + folderName, e);
}
// The error folder is always a local folder
// TODO: Skip the remote part for all local-only folders
if (account.getErrorFolderName().equals(folderName)) {
continue;
}
// Send flag change to server
String[] uids = entry.getValue().toArray(EMPTY_STRING_ARRAY);
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
}
/**
* Set or remove a flag for a set of messages in a specific folder.
*
* <p>
* The {@link Message} objects passed in are updated to reflect the new flag state.
* </p>
*
* @param account
* The account the folder containing the messages belongs to.
* @param folderName
* The name of the folder.
* @param messages
* The messages to change the flag for.
* @param flag
* The flag to change.
* @param newState
* {@code true}, if the flag should be set. {@code false} if it should be removed.
*/
public void setFlag(Account account, String folderName, Message[] messages, Flag flag,
boolean newState) {
// TODO: Put this into the background, but right now some callers depend on the message
// objects being modified right after this method returns.
Folder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(Folder.OPEN_MODE_RW);
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && !newState &&
account.getOutboxFolderName().equals(folderName)) {
for (Message message : messages) {
String uid = message.getUid();
if (uid != null) {
sendCount.remove(uid);
}
}
}
// Update the messages in the local store
localFolder.setFlags(messages, new Flag[] {flag}, newState);
int unreadMessageCount = localFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
/*
* Handle the remote side
*/
// The error folder is always a local folder
// TODO: Skip the remote part for all local-only folders
if (account.getErrorFolderName().equals(folderName)) {
return;
}
String[] uids = new String[messages.length];
for (int i = 0, end = uids.length; i < end; i++) {
uids[i] = messages[i].getUid();
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException(me);
} finally {
closeFolder(localFolder);
}
}
/**
* Set or remove a flag for a message referenced by message UID.
*
* @param account
* The account the folder containing the message belongs to.
* @param folderName
* The name of the folder.
* @param uid
* The UID of the message to change the flag for.
* @param flag
* The flag to change.
* @param newState
* {@code true}, if the flag should be set. {@code false} if it should be removed.
*/
public void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState) {
Folder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(Folder.OPEN_MODE_RW);
Message message = localFolder.getMessage(uid);
if (message != null) {
setFlag(account, folderName, new Message[] { message }, flag, newState);
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException(me);
} finally {
closeFolder(localFolder);
}
}
public void clearAllPending(final Account account) {
try {
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = account.getLocalStore();
localStore.removePendingCommands();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, null, me);
}
}
public void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener) {
put("loadMessageForViewRemote", listener, new Runnable() {
@Override
public void run() {
loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, false);
}
});
}
public boolean loadMessageForViewRemoteSynchronous(final Account account, final String folder,
final String uid, final MessagingListener listener, final boolean force,
final boolean loadPartialFromSearch) {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
Message message = localFolder.getMessage(uid);
if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully.");
// ASH move toast
android.widget.Toast.makeText(mApplication,
"Message has local UID so cannot download fully",
android.widget.Toast.LENGTH_LONG).show();
// TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But
// one we can't download completely. Maybe add a new flag; X_PARTIAL_MESSAGE ?
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
}
/* commented out because this was pulled from another unmerged branch:
} else if (localFolder.isLocalOnly() && !force) {
Log.w(K9.LOG_TAG, "Message in local-only folder so cannot download fully.");
// ASH move toast
android.widget.Toast.makeText(mApplication,
"Message in local-only folder so cannot download fully",
android.widget.Toast.LENGTH_LONG).show();
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
}*/
if (message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
} else {
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(Folder.OPEN_MODE_RW);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
if (loadPartialFromSearch) {
fp.add(FetchProfile.Item.BODY);
}
fp.add(FetchProfile.Item.ENVELOPE);
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
if (account.isMarkMessageAsReadOnView()) {
message.setFlag(Flag.SEEN, true);
}
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// now that we have the full message, refresh the headers
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
return true;
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
notifyUserIfCertificateProblem(mApplication, e, account, true);
addErrorMessage(account, null, e);
return false;
} finally {
closeFolder(remoteFolder);
closeFolder(localFolder);
}
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open(Folder.OPEN_MODE_RW);
LocalMessage message = localFolder.getMessage(uid);
if (message == null
|| message.getId() == 0) {
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
// IMAP search results will usually need to be downloaded before viewing.
// TODO: limit by account.getMaximumAutoDownloadMessageSize().
if (!message.isSet(Flag.X_DOWNLOADED_FULL) &&
!message.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
if (loadMessageForViewRemoteSynchronous(account, folder, uid, listener,
false, true)) {
markMessageAsReadOnView(account, message);
}
return;
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] {
message
}, fp, null);
localFolder.close();
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
markMessageAsReadOnView(account, message);
} catch (Exception e) {
for (MessagingListener l : getListeners(listener)) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
}
});
}
/**
* Mark the provided message as read if not disabled by the account setting.
*
* @param account
* The account the message belongs to.
* @param message
* The message to mark as read. This {@link Message} instance will be modify by calling
* {@link Message#setFlag(Flag, boolean)} on it.
*
* @throws MessagingException
*
* @see Account#isMarkMessageAsReadOnView()
*/
private void markMessageAsReadOnView(Account account, Message message)
throws MessagingException {
if (account.isMarkMessageAsReadOnView() && !message.isSet(Flag.SEEN)) {
List<Long> messageIds = Collections.singletonList(message.getId());
setFlag(account, messageIds, Flag.SEEN, true);
((LocalMessage) message).setFlagInternal(Flag.SEEN, true);
}
}
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener) {
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
if (part.getBody() != null) {
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFinished(account, message, part, tag);
}
return;
}
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentStarted(account, message, part, tag, true);
}
put("loadAttachment", listener, new Runnable() {
@Override
public void run() {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
List<Part> attachments = MimeUtility.collectAttachments(message);
for (Part attachment : attachments) {
attachment.setBody(null);
}
Store remoteStore = account.getRemoteStore();
localFolder = localStore.getFolder(message.getFolder().getName());
remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(Folder.OPEN_MODE_RW);
//FIXME: This is an ugly hack that won't be needed once the Message objects have been united.
Message remoteMessage = remoteFolder.getMessage(message.getUid());
remoteMessage.setBody(message.getBody());
remoteFolder.fetchPart(remoteMessage, part, null);
localFolder.updateMessage((LocalMessage)message);
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFinished(account, message, part, tag);
}
} catch (MessagingException me) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Exception loading attachment", me);
for (MessagingListener l : getListeners(listener)) {
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
notifyUserIfCertificateProblem(mApplication, me, account, true);
addErrorMessage(account, null, me);
} finally {
closeFolder(localFolder);
closeFolder(remoteFolder);
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener) {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, listener);
} catch (Exception e) {
/*
for (MessagingListener l : getListeners())
{
// TODO general failed
}
*/
addErrorMessage(account, null, e);
}
}
public void sendPendingMessages(MessagingListener listener) {
final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext());
for (Account account : prefs.getAvailableAccounts()) {
sendPendingMessages(account, listener);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener) {
putBackground("sendPendingMessages", listener, new Runnable() {
@Override
public void run() {
if (!account.isAvailable(mApplication)) {
throw new UnavailableAccountException();
}
if (messagesPendingSend(account)) {
notifyWhileSending(account);
try {
sendPendingMessagesSynchronous(account);
} finally {
notifyWhileSendingDone(account);
}
}
}
});
}
private void cancelNotification(int id) {
NotificationManager notifMgr =
(NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(id);
}
private void notifyWhileSendingDone(Account account) {
if (account.isShowOngoing()) {
cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
/**
* Display an ongoing notification while a message is being sent.
*
* @param account
* The account the message is sent from. Never {@code null}.
*/
private void notifyWhileSending(Account account) {
if (!account.isShowOngoing()) {
return;
}
NotificationManager notifMgr =
(NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationBuilder(mApplication);
builder.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true);
String accountDescription = account.getDescription();
String accountName = (TextUtils.isEmpty(accountDescription)) ?
account.getEmail() : accountDescription;
builder.setTicker(mApplication.getString(R.string.notification_bg_send_ticker,
accountName));
builder.setContentTitle(mApplication.getString(R.string.notification_bg_send_title));
builder.setContentText(account.getDescription());
TaskStackBuilder stack = buildMessageListBackStack(mApplication, account,
account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0));
if (K9.NOTIFICATION_LED_WHILE_SYNCING) {
configureNotification(builder, null, null,
account.getNotificationSetting().getLedColor(),
K9.NOTIFICATION_LED_BLINK_FAST, true);
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
private void notifySendTempFailed(Account account, Exception lastFailure) {
notifySendFailed(account, lastFailure, account.getOutboxFolderName());
}
private void notifySendPermFailed(Account account, Exception lastFailure) {
notifySendFailed(account, lastFailure, account.getDraftsFolderName());
}
/**
* Display a notification when sending a message has failed.
*
* @param account
* The account that was used to sent the message.
* @param lastFailure
* The {@link Exception} instance that indicated sending the message has failed.
* @param openFolder
* The name of the folder to open when the notification is clicked.
*/
private void notifySendFailed(Account account, Exception lastFailure, String openFolder) {
NotificationManager notifMgr =
(NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationBuilder(mApplication);
builder.setSmallIcon(R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
builder.setTicker(mApplication.getString(R.string.send_failure_subject));
builder.setContentTitle(mApplication.getString(R.string.send_failure_subject));
builder.setContentText(getRootCauseMessage(lastFailure));
TaskStackBuilder stack = buildFolderListBackStack(mApplication, account);
builder.setContentIntent(stack.getPendingIntent(0, 0));
configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR,
K9.NOTIFICATION_LED_BLINK_FAST, true);
notifMgr.notify(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
/**
* Display an ongoing notification while checking for new messages on the server.
*
* @param account
* The account that is checked for new messages. Never {@code null}.
* @param folder
* The folder that is being checked for new messages. Never {@code null}.
*/
private void notifyFetchingMail(final Account account, final Folder folder) {
if (!account.isShowOngoing()) {
return;
}
final NotificationManager notifMgr =
(NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationBuilder(mApplication);
builder.setSmallIcon(R.drawable.ic_notify_check_mail);
builder.setWhen(System.currentTimeMillis());
builder.setOngoing(true);
builder.setTicker(mApplication.getString(
R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()));
builder.setContentTitle(mApplication.getString(R.string.notification_bg_sync_title));
builder.setContentText(account.getDescription() +
mApplication.getString(R.string.notification_bg_title_separator) +
folder.getName());
TaskStackBuilder stack = buildMessageListBackStack(mApplication, account,
account.getInboxFolderName());
builder.setContentIntent(stack.getPendingIntent(0, 0));
if (K9.NOTIFICATION_LED_WHILE_SYNCING) {
configureNotification(builder, null, null,
account.getNotificationSetting().getLedColor(),
K9.NOTIFICATION_LED_BLINK_FAST, true);
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(),
builder.build());
}
private void notifyFetchingMailCancel(final Account account) {
if (account.isShowOngoing()) {
cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
public boolean messagesPendingSend(final Account account) {
Folder localFolder = null;
try {
localFolder = account.getLocalStore().getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return false;
}
localFolder.open(Folder.OPEN_MODE_RW);
if (localFolder.getMessageCount() > 0) {
return true;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
} finally {
closeFolder(localFolder);
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
*/
public void sendPendingMessagesSynchronous(final Account account) {
Folder localFolder = null;
Exception lastFailure = null;
try {
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return;
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesStarted(account);
}
localFolder.open(Folder.OPEN_MODE_RW);
Message[] localMessages = localFolder.getMessages(null);
int progress = 0;
int todo = localMessages.length;
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account);
for (Message message : localMessages) {
if (message.isSet(Flag.DELETED)) {
message.destroy();
continue;
}
try {
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null) {
count = oldCount;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) {
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " can't be delivered after " + K9.MAX_SEND_ATTEMPTS + " attempts. Giving up until the user restarts the device");
notifySendTempFailed(account, new MessagingException(message.getSubject()));
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try {
if (message.getHeader(K9.IDENTITY_HEADER) != null) {
Log.v(K9.LOG_TAG, "The user has set the Outbox and Drafts folder to the same thing. " +
"This message appears to be a draft, so K-9 will not send it");
continue;
}
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
if (!account.hasSentFolder()) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account does not have a sent mail folder; deleting sent message");
message.setFlag(Flag.DELETED, true);
} else {
LocalFolder localSentFolder = (LocalFolder) localStore.getFolder(account.getSentFolderName());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(new Message[] { message }, localSentFolder);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] { localSentFolder.getName(), message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
} catch (Exception e) {
// 5.x.x errors from the SMTP server are "PERMFAIL"
// move the message over to drafts rather than leaving it in the outbox
// This is a complete hack, but is worlds better than the previous
// "don't even bother" functionality
if (getRootCauseMessage(e).startsWith("5")) {
localFolder.moveMessages(new Message[] { message }, (LocalFolder) localStore.getFolder(account.getDraftsFolderName()));
}
notifyUserIfCertificateProblem(mApplication, e, account, false);
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e));
}
lastFailure = e;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e));
}
lastFailure = e;
}
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesCompleted(account);
}
if (lastFailure != null) {
if (getRootCauseMessage(lastFailure).startsWith("5")) {
notifySendPermFailed(account, lastFailure);
} else {
notifySendTempFailed(account, lastFailure);
}
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, null, e);
} finally {
if (lastFailure == null) {
cancelNotification(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber());
}
closeFolder(localFolder);
}
}
public void getAccountStats(final Context context, final Account account,
final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
AccountStats stats = account.getStats(context);
listener.accountStatusChanged(account, stats);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Count not get unread count for account " +
account.getDescription(), me);
}
}
});
}
public void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run() {
getSearchAccountStatsSynchronous(searchAccount, listener);
}
});
}
public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener) {
Preferences preferences = Preferences.getPreferences(mApplication);
LocalSearch search = searchAccount.getRelatedSearch();
// Collect accounts that belong to the search
String[] accountUuids = search.getAccountUuids();
Account[] accounts;
if (search.searchAllAccounts()) {
accounts = preferences.getAccounts();
} else {
accounts = new Account[accountUuids.length];
for (int i = 0, len = accountUuids.length; i < len; i++) {
String accountUuid = accountUuids[i];
accounts[i] = preferences.getAccount(accountUuid);
}
}
ContentResolver cr = mApplication.getContentResolver();
int unreadMessageCount = 0;
int flaggedMessageCount = 0;
String[] projection = {
StatsColumns.UNREAD_COUNT,
StatsColumns.FLAGGED_COUNT
};
for (Account account : accounts) {
StringBuilder query = new StringBuilder();
List<String> queryArgs = new ArrayList<String>();
ConditionsTreeNode conditions = search.getConditions();
SqlQueryBuilder.buildWhereClause(account, conditions, query, queryArgs);
String selection = query.toString();
String[] selectionArgs = queryArgs.toArray(EMPTY_STRING_ARRAY);
Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI,
"account/" + account.getUuid() + "/stats");
// Query content provider to get the account stats
Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null);
try {
if (cursor.moveToFirst()) {
unreadMessageCount += cursor.getInt(0);
flaggedMessageCount += cursor.getInt(1);
}
} finally {
cursor.close();
}
}
// Create AccountStats instance...
AccountStats stats = new AccountStats();
stats.unreadMessageCount = unreadMessageCount;
stats.flaggedMessageCount = flaggedMessageCount;
// ...and notify the listener
if (listener != null) {
listener.accountStatusChanged(searchAccount, stats);
}
return stats;
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l) {
Runnable unreadRunnable = new Runnable() {
@Override
public void run() {
int unreadMessageCount = 0;
try {
Folder localFolder = account.getLocalStore().getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public boolean isMoveCapable(Message message) {
return !message.getUid().startsWith(K9.LOCAL_UID_PREFIX);
}
public boolean isCopyCapable(Message message) {
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account) {
try {
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account) {
try {
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public void moveMessages(final Account account, final String srcFolder,
final List<Message> messages, final String destFolder,
final MessagingListener listener) {
suppressMessages(account, messages);
putBackground("moveMessages", null, new Runnable() {
@Override
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false,
listener);
}
});
}
public void moveMessagesInThread(final Account account, final String srcFolder,
final List<Message> messages, final String destFolder) {
suppressMessages(account, messages);
putBackground("moveMessagesInThread", null, new Runnable() {
@Override
public void run() {
try {
List<Message> messagesInThreads = collectMessagesInThreads(account, messages);
moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder,
false, null);
} catch (MessagingException e) {
addErrorMessage(account, "Exception while moving messages", e);
}
}
});
}
public void moveMessage(final Account account, final String srcFolder, final Message message,
final String destFolder, final MessagingListener listener) {
moveMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener);
}
public void copyMessages(final Account account, final String srcFolder,
final List<Message> messages, final String destFolder,
final MessagingListener listener) {
putBackground("copyMessages", null, new Runnable() {
@Override
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true,
listener);
}
});
}
public void copyMessagesInThread(final Account account, final String srcFolder,
final List<Message> messages, final String destFolder) {
putBackground("copyMessagesInThread", null, new Runnable() {
@Override
public void run() {
try {
List<Message> messagesInThreads = collectMessagesInThreads(account, messages);
moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder,
true, null);
} catch (MessagingException e) {
addErrorMessage(account, "Exception while copying messages", e);
}
}
});
}
public void copyMessage(final Account account, final String srcFolder, final Message message,
final String destFolder, final MessagingListener listener) {
copyMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener);
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder,
final List<Message> inMessages, final String destFolder, final boolean isCopy,
MessagingListener listener) {
try {
Map<String, String> uidMap = new HashMap<String, String>();
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) {
return;
}
if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) {
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
boolean unreadCountAffected = false;
List<String> uids = new LinkedList<String>();
for (Message message : inMessages) {
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
uids.add(uid);
}
if (!unreadCountAffected && !message.isSet(Flag.SEEN)) {
unreadCountAffected = true;
}
}
Message[] messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null);
if (messages.length > 0) {
Map<String, Message> origUidMap = new HashMap<String, Message>();
for (Message message : messages) {
origUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(messages, fp, null);
uidMap = localSrcFolder.copyMessages(messages, localDestFolder);
if (unreadCountAffected) {
// If this copy operation changes the unread count in the destination
// folder, notify the listeners.
int unreadMessageCount = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, destFolder, unreadMessageCount);
}
}
} else {
uidMap = localSrcFolder.moveMessages(messages, localDestFolder);
for (Map.Entry<String, Message> entry : origUidMap.entrySet()) {
String origUid = entry.getKey();
Message message = entry.getValue();
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
}
unsuppressMessages(account, messages);
if (unreadCountAffected) {
// If this move operation changes the unread count, notify the listeners
// that the unread count changed in both the source and destination folder.
int unreadMessageCountSrc = localSrcFolder.getUnreadMessageCount();
int unreadMessageCountDest = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, srcFolder, unreadMessageCountSrc);
l.folderStatusChanged(account, destFolder, unreadMessageCountDest);
}
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(EMPTY_STRING_ARRAY), uidMap);
}
processPendingCommands(account);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener) {
putBackground("expunge", null, new Runnable() {
@Override
public void run() {
queueExpunge(account, folder);
}
});
}
public void deleteDraft(final Account account, long id) {
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
String uid = localFolder.getMessageUidById(id);
if (uid != null) {
Message message = localFolder.getMessage(uid);
if (message != null) {
deleteMessages(Collections.singletonList(message), null);
}
}
} catch (MessagingException me) {
addErrorMessage(account, null, me);
} finally {
closeFolder(localFolder);
}
}
public void deleteThreads(final List<Message> messages) {
actOnMessages(messages, new MessageActor() {
@Override
public void act(final Account account, final Folder folder,
final List<Message> accountMessages) {
suppressMessages(account, messages);
putBackground("deleteThreads", null, new Runnable() {
@Override
public void run() {
deleteThreadsSynchronous(account, folder.getName(), accountMessages);
}
});
}
});
}
public void deleteThreadsSynchronous(Account account, String folderName,
List<Message> messages) {
try {
List<Message> messagesToDelete = collectMessagesInThreads(account, messages);
deleteMessagesSynchronous(account, folderName,
messagesToDelete.toArray(EMPTY_MESSAGE_ARRAY), null);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Something went wrong while deleting threads", e);
}
}
public List<Message> collectMessagesInThreads(Account account, List<Message> messages)
throws MessagingException {
LocalStore localStore = account.getLocalStore();
List<Message> messagesInThreads = new ArrayList<Message>();
for (Message message : messages) {
LocalMessage localMessage = (LocalMessage) message;
long rootId = localMessage.getRootId();
long threadId = (rootId == -1) ? localMessage.getThreadId() : rootId;
Message[] messagesInThread = localStore.getMessagesInThread(threadId);
Collections.addAll(messagesInThreads, messagesInThread);
}
return messagesInThreads;
}
public void deleteMessages(final List<Message> messages, final MessagingListener listener) {
actOnMessages(messages, new MessageActor() {
@Override
public void act(final Account account, final Folder folder,
final List<Message> accountMessages) {
suppressMessages(account, messages);
putBackground("deleteMessages", null, new Runnable() {
@Override
public void run() {
deleteMessagesSynchronous(account, folder.getName(),
accountMessages.toArray(EMPTY_MESSAGE_ARRAY), listener);
}
});
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages,
MessagingListener listener) {
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try {
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages) {
for (MessagingListener l : getListeners(listener)) {
l.messageDeleted(account, folder, message);
}
}
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
Map<String, String> uidMap = null;
if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true);
} else {
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (!localTrashFolder.exists()) {
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
uidMap = localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount());
if (localTrashFolder != null) {
l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount());
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
if (folder.equals(account.getOutboxFolderName())) {
for (Message message : messages) {
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
} else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) {
if (folder.equals(account.getTrashFolderName())) {
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
} else {
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap);
}
processPendingCommands(account);
} else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) {
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
} else {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
unsuppressMessages(account, messages);
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Error deleting message from local store.", me);
} finally {
closeFolder(localFolder);
closeFolder(localTrashFolder);
}
}
private String[] getUidsFromMessages(Message[] messages) {
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++) {
uids[i] = messages[i].getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException {
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try {
if (remoteFolder.exists()) {
remoteFolder.open(Folder.OPEN_MODE_RW);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) {
remoteFolder.expunge();
}
// When we empty trash, we need to actually synchronize the folder
// or local deletes will never get cleaned up
synchronizeFolder(account, remoteFolder, true, 0, null);
compact(account, null);
}
} finally {
closeFolder(remoteFolder);
}
}
public void emptyTrash(final Account account, MessagingListener listener) {
putBackground("emptyTrash", listener, new Runnable() {
@Override
public void run() {
LocalFolder localFolder = null;
try {
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(account.getTrashFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
boolean isTrashLocalOnly = isTrashLocalOnly(account);
if (isTrashLocalOnly) {
localFolder.clearAllMessages();
} else {
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
}
for (MessagingListener l : getListeners()) {
l.emptyTrashCompleted(account);
}
if (!isTrashLocalOnly) {
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(EMPTY_STRING_ARRAY);
queuePendingCommand(account, command);
processPendingCommands(account);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, null, e);
} finally {
closeFolder(localFolder);
}
}
});
}
/**
* Find out whether the account type only supports a local Trash folder.
*
* <p>Note: Currently this is only the case for POP3 accounts.</p>
*
* @param account
* The account to check.
*
* @return {@code true} if the account only has a local Trash folder that is not synchronized
* with a folder on the server. {@code false} otherwise.
*
* @throws MessagingException
* In case of an error.
*/
private boolean isTrashLocalOnly(Account account) throws MessagingException {
// TODO: Get rid of the tight coupling once we properly support local folders
return (account.getRemoteStore() instanceof Pop3Store);
}
public void sendAlternate(final Context context, Account account, Message message) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener() {
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
try {
Intent msg = new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null) {
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, message.getSubject());
Address[] from = message.getFrom();
String[] senders = new String[from.length];
for (int i = 0; i < from.length; i++) {
senders[i] = from[i].toString();
}
msg.putExtra(Intents.Share.EXTRA_FROM, senders);
Address[] to = message.getRecipients(RecipientType.TO);
String[] recipientsTo = new String[to.length];
for (int i = 0; i < to.length; i++) {
recipientsTo[i] = to[i].toString();
}
msg.putExtra(Intent.EXTRA_EMAIL, recipientsTo);
Address[] cc = message.getRecipients(RecipientType.CC);
String[] recipientsCc = new String[cc.length];
for (int i = 0; i < cc.length; i++) {
recipientsCc[i] = cc[i].toString();
}
msg.putExtra(Intent.EXTRA_CC, recipientsCc);
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener) {
TracingWakeLock twakeLock = null;
if (useManualWakeLock) {
TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final TracingWakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners()) {
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable() {
@Override
public void run() {
try {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Collection<Account> accounts;
if (account != null) {
accounts = new ArrayList<Account>(1);
accounts.add(account);
} else {
accounts = prefs.getAvailableAccounts();
}
for (final Account account : accounts) {
checkMailForAccount(context, account, ignoreLastCheckedTime, prefs, listener);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, null, e);
}
putBackground("finalize sync", null, new Runnable() {
@Override
public void run() {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null) {
wakeLock.release();
}
for (MessagingListener l : getListeners()) {
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
private void checkMailForAccount(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final Preferences prefs,
final MessagingListener listener) {
if (!account.isAvailable(context)) {
if (K9.DEBUG) {
Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription());
}
return;
}
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (!ignoreLastCheckedTime && accountInterval <= 0) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
return;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
account.setRingNotified(false);
sendPendingMessages(account, listener);
try {
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false)) {
folder.open(Folder.OPEN_MODE_RW);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass)) {
// Never sync a folder that isn't displayed
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
*/
continue;
}
if (modeMismatch(aSyncMode, fSyncClass)) {
// Do not sync folders in the wrong class
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
*/
continue;
}
synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, null, e);
} finally {
putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() {
@Override
public void run() {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription());
account.setRingNotified(false);
try {
AccountStats stats = account.getStats(context);
if (stats == null || stats.unreadMessageCount == 0) {
notifyAccountCancel(context, account);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
}
}
);
}
}
private void synchronizeFolder(
final Account account,
final Folder folder,
final boolean ignoreLastCheckedTime,
final long accountInterval,
final MessagingListener listener) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
if (!ignoreLastCheckedTime && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
putBackground("sync" + folder.getName(), null, new Runnable() {
@Override
public void run() {
LocalFolder tLocalFolder = null;
try {
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OPEN_MODE_RW);
if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
notifyFetchingMail(account, folder);
try {
synchronizeMailboxSynchronous(account, folder.getName(), listener, null);
} finally {
notifyFetchingMailCancel(account);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, null, e);
} finally {
closeFolder(tLocalFolder);
}
}
}
);
}
public void compact(final Account account, final MessagingListener ml) {
putBackground("compact:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to compact account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml) {
putBackground("clear:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e);
}
}
});
}
public void recreate(final Account account, final MessagingListener ml) {
putBackground("recreate:" + account.getDescription(), ml, new Runnable() {
@Override
public void run() {
try {
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.recreate();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
for (MessagingListener l : getListeners(ml)) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
} catch (UnavailableStorageException e) {
Log.i(K9.LOG_TAG, "Failed to recreate an account because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e);
}
}
});
}
private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) {
// If we don't even have an account name, don't show the notification.
// (This happens during initial account setup)
if (account.getName() == null) {
return false;
}
// Do not notify if the user does not have notifications enabled or if the message has
// been read.
if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) {
return false;
}
// If the account is a POP3 account and the message is older than the oldest message we've
// previously seen, then don't notify about it.
if (account.getStoreUri().startsWith("pop3") &&
message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) {
return false;
}
// No notification for new messages in Trash, Drafts, Spam or Sent folder.
// But do notify if it's the INBOX (see issue 1817).
Folder folder = message.getFolder();
if (folder != null) {
String folderName = folder.getName();
if (!account.getInboxFolderName().equals(folderName) &&
(account.getTrashFolderName().equals(folderName)
|| account.getDraftsFolderName().equals(folderName)
|| account.getSpamFolderName().equals(folderName)
|| account.getSentFolderName().equals(folderName))) {
return false;
}
}
if (message.getUid() != null && localFolder.getLastUid() != null) {
try {
Integer messageUid = Integer.parseInt(message.getUid());
if (messageUid <= localFolder.getLastUid()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " +
localFolder.getLastUid() + ". Skipping notification.");
return false;
}
} catch (NumberFormatException e) {
// Nothing to be done here.
}
}
// Don't notify if the sender address matches one of our identities and the user chose not
// to be notified for such messages.
if (account.isAnIdentity(message.getFrom()) && !account.isNotifySelfNewMail()) {
return false;
}
return true;
}
/**
* Get the pending notification data for an account.
* See {@link NotificationData}.
*
* @param account The account to retrieve the pending data for
* @param previousUnreadMessageCount The number of currently pending messages, which will be used
* if there's no pending data yet. If passed as null, a new instance
* won't be created if currently not existent.
* @return A pending data instance, or null if one doesn't exist and
* previousUnreadMessageCount was passed as null.
*/
private NotificationData getNotificationData(Account account, Integer previousUnreadMessageCount) {
NotificationData data;
synchronized (notificationData) {
data = notificationData.get(account.getAccountNumber());
if (data == null && previousUnreadMessageCount != null) {
data = new NotificationData(previousUnreadMessageCount);
notificationData.put(account.getAccountNumber(), data);
}
}
return data;
}
private CharSequence getMessageSender(Context context, Account account, Message message) {
try {
boolean isSelf = false;
final Contacts contacts = K9.showContactName() ? Contacts.getInstance(context) : null;
final Address[] fromAddrs = message.getFrom();
if (fromAddrs != null) {
isSelf = account.isAnIdentity(fromAddrs);
if (!isSelf && fromAddrs.length > 0) {
return fromAddrs[0].toFriendly(contacts).toString();
}
}
if (isSelf) {
// show To: if the message was sent from me
Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
if (rcpts != null && rcpts.length > 0) {
return context.getString(R.string.message_to_fmt,
rcpts[0].toFriendly(contacts).toString());
}
return context.getString(R.string.general_no_sender);
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to get sender information for notification.", e);
}
return null;
}
private CharSequence getMessageSubject(Context context, Message message) {
String subject = message.getSubject();
if (!TextUtils.isEmpty(subject)) {
return subject;
}
return context.getString(R.string.general_no_subject);
}
private static TextAppearanceSpan sEmphasizedSpan;
private TextAppearanceSpan getEmphasizedSpan(Context context) {
if (sEmphasizedSpan == null) {
sEmphasizedSpan = new TextAppearanceSpan(context,
R.style.TextAppearance_StatusBar_EventContent_Emphasized);
}
return sEmphasizedSpan;
}
private CharSequence getMessagePreview(Context context, Message message) {
CharSequence subject = getMessageSubject(context, message);
String snippet = message.getPreview();
if (TextUtils.isEmpty(subject)) {
return snippet;
} else if (TextUtils.isEmpty(snippet)) {
return subject;
}
SpannableStringBuilder preview = new SpannableStringBuilder();
preview.append(subject);
preview.append('\n');
preview.append(snippet);
preview.setSpan(getEmphasizedSpan(context), 0, subject.length(), 0);
return preview;
}
private CharSequence buildMessageSummary(Context context, CharSequence sender, CharSequence subject) {
if (sender == null) {
return subject;
}
SpannableStringBuilder summary = new SpannableStringBuilder();
summary.append(sender);
summary.append(" ");
summary.append(subject);
summary.setSpan(getEmphasizedSpan(context), 0, sender.length(), 0);
return summary;
}
private static final boolean platformShowsNumberInNotification() {
// Honeycomb and newer don't show the number as overlay on the notification icon.
// However, the number will appear in the detailed notification view.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static final boolean platformSupportsExtendedNotifications() {
// supported in Jellybean
// TODO: use constant once target SDK is set to >= 16
return Build.VERSION.SDK_INT >= 16;
}
private Message findNewestMessageForNotificationLocked(Context context,
Account account, NotificationData data) {
if (!data.messages.isEmpty()) {
return data.messages.getFirst();
}
if (!data.droppedMessages.isEmpty()) {
return data.droppedMessages.getFirst().restoreToLocalMessage(context);
}
return null;
}
/**
* Creates a notification of a newly received message.
*/
private void notifyAccount(Context context, Account account,
Message message, int previousUnreadMessageCount) {
final NotificationData data = getNotificationData(account, previousUnreadMessageCount);
synchronized (data) {
notifyAccountWithDataLocked(context, account, message, data);
}
}
private void notifyAccountWithDataLocked(Context context, Account account,
Message message, NotificationData data) {
boolean updateSilently = false;
if (message == null) {
/* this can happen if a message we previously notified for is read or deleted remotely */
message = findNewestMessageForNotificationLocked(context, account, data);
updateSilently = true;
if (message == null) {
// seemingly both the message list as well as the overflow list is empty;
// it probably is a good idea to cancel the notification in that case
notifyAccountCancel(context, account);
return;
}
} else {
data.addMessage(message);
}
final KeyguardManager keyguardService = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
final CharSequence sender = getMessageSender(context, account, message);
final CharSequence subject = getMessageSubject(context, message);
CharSequence summary = buildMessageSummary(context, sender, subject);
boolean privacyModeEnabled =
(K9.getNotificationHideSubject() == NotificationHideSubject.ALWAYS) ||
(K9.getNotificationHideSubject() == NotificationHideSubject.WHEN_LOCKED &&
keyguardService.inKeyguardRestrictedInputMode());
if (privacyModeEnabled || summary.length() == 0) {
summary = context.getString(R.string.notification_new_title);
}
NotificationManager notifMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationBuilder(context);
builder.setSmallIcon(R.drawable.ic_notify_new_mail);
builder.setWhen(System.currentTimeMillis());
if (!updateSilently) {
builder.setTicker(summary);
}
final int newMessages = data.getNewMessageCount();
final int unreadCount = data.unreadBeforeNotification + newMessages;
if (account.isNotificationShowsUnreadCount() || platformShowsNumberInNotification()) {
builder.setNumber(unreadCount);
}
String accountDescr = (account.getDescription() != null) ?
account.getDescription() : account.getEmail();
final ArrayList<MessageReference> allRefs = data.getAllMessageRefs();
if (platformSupportsExtendedNotifications() && !privacyModeEnabled) {
if (newMessages > 1) {
// multiple messages pending, show inbox style
NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder);
for (Message m : data.messages) {
style.addLine(buildMessageSummary(context,
getMessageSender(context, account, m),
getMessageSubject(context, m)));
}
if (!data.droppedMessages.isEmpty()) {
style.setSummaryText(context.getString(R.string.notification_additional_messages,
data.droppedMessages.size(), accountDescr));
}
String title = context.getString(R.string.notification_new_messages_title, newMessages);
style.setBigContentTitle(title);
builder.setContentTitle(title);
builder.setSubText(accountDescr);
builder.setStyle(style);
} else {
// single message pending, show big text
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(builder);
CharSequence preview = getMessagePreview(context, message);
if (preview != null) {
style.bigText(preview);
}
builder.setContentText(subject);
builder.setSubText(accountDescr);
builder.setContentTitle(sender);
builder.setStyle(style);
builder.addAction(R.drawable.ic_action_single_message_options_dark,
context.getString(R.string.notification_action_reply),
NotificationActionService.getReplyIntent(context, account, message.makeMessageReference()));
}
builder.addAction(R.drawable.ic_action_mark_as_read_dark,
context.getString(R.string.notification_action_mark_as_read),
NotificationActionService.getReadAllMessagesIntent(context, account, allRefs));
NotificationQuickDelete deleteOption = K9.getNotificationQuickDeleteBehaviour();
boolean showDeleteAction = deleteOption == NotificationQuickDelete.ALWAYS ||
(deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG && newMessages == 1);
if (showDeleteAction) {
// we need to pass the action directly to the activity, otherwise the
// status bar won't be pulled up and we won't see the confirmation (if used)
builder.addAction(R.drawable.ic_action_delete_dark,
context.getString(R.string.notification_action_delete),
NotificationDeleteConfirmation.getIntent(context, account, allRefs));
}
} else {
String accountNotice = context.getString(R.string.notification_new_one_account_fmt,
unreadCount, accountDescr);
builder.setContentTitle(accountNotice);
builder.setContentText(summary);
}
for (Message m : data.messages) {
if (m.isSet(Flag.FLAGGED)) {
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
break;
}
}
TaskStackBuilder stack;
boolean treatAsSingleMessageNotification;
if (platformSupportsExtendedNotifications()) {
// in the new-style notifications, we focus on the new messages, not the unread ones
treatAsSingleMessageNotification = newMessages == 1;
} else {
// in the old-style notifications, we focus on unread messages, as we don't have a
// good way to express the new message count
treatAsSingleMessageNotification = unreadCount == 1;
}
if (treatAsSingleMessageNotification) {
stack = buildMessageViewBackStack(context, message.makeMessageReference());
} else if (account.goToUnreadMessageSearch()) {
stack = buildUnreadBackStack(context, account);
} else {
String initialFolder = message.getFolder().getName();
/* only go to folder if all messages are in the same folder, else go to folder list */
for (MessageReference ref : allRefs) {
if (!TextUtils.equals(initialFolder, ref.folderName)) {
initialFolder = null;
break;
}
}
stack = buildMessageListBackStack(context, account, initialFolder);
}
builder.setContentIntent(stack.getPendingIntent(
account.getAccountNumber(),
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT));
builder.setDeleteIntent(NotificationActionService.getAcknowledgeIntent(context, account));
// Only ring or vibrate if we have not done so already on this account and fetch
boolean ringAndVibrate = false;
if (!updateSilently && !account.isRingNotified()) {
account.setRingNotified(true);
ringAndVibrate = true;
}
NotificationSetting n = account.getNotificationSetting();
configureNotification(
builder,
(n.shouldRing()) ? n.getRingtone() : null,
(n.shouldVibrate()) ? n.getVibration() : null,
(n.isLed()) ? Integer.valueOf(n.getLedColor()) : null,
K9.NOTIFICATION_LED_BLINK_SLOW,
ringAndVibrate);
notifMgr.notify(account.getAccountNumber(), builder.build());
}
private TaskStackBuilder buildAccountsBackStack(Context context) {
TaskStackBuilder stack = TaskStackBuilder.create(context);
if (!skipAccountsInBackStack(context)) {
stack.addNextIntent(new Intent(context, Accounts.class).putExtra(Accounts.EXTRA_STARTUP, false));
}
return stack;
}
private TaskStackBuilder buildFolderListBackStack(Context context, Account account) {
TaskStackBuilder stack = buildAccountsBackStack(context);
stack.addNextIntent(FolderList.actionHandleAccountIntent(context, account, false));
return stack;
}
private TaskStackBuilder buildUnreadBackStack(Context context, final Account account) {
TaskStackBuilder stack = buildAccountsBackStack(context);
LocalSearch search = Accounts.createUnreadSearch(context, account);
stack.addNextIntent(MessageList.intentDisplaySearch(context, search, true, false, false));
return stack;
}
private TaskStackBuilder buildMessageListBackStack(Context context, Account account, String folder) {
TaskStackBuilder stack = skipFolderListInBackStack(context, account, folder)
? buildAccountsBackStack(context)
: buildFolderListBackStack(context, account);
if (folder != null) {
LocalSearch search = new LocalSearch(folder);
search.addAllowedFolder(folder);
search.addAccountUuid(account.getUuid());
stack.addNextIntent(MessageList.intentDisplaySearch(context, search, false, true, true));
}
return stack;
}
private TaskStackBuilder buildMessageViewBackStack(Context context, MessageReference message) {
Account account = Preferences.getPreferences(context).getAccount(message.accountUuid);
TaskStackBuilder stack = buildMessageListBackStack(context, account, message.folderName);
stack.addNextIntent(MessageList.actionDisplayMessageIntent(context, message));
return stack;
}
private boolean skipFolderListInBackStack(Context context, Account account, String folder) {
return folder != null && folder.equals(account.getAutoExpandFolderName());
}
private boolean skipAccountsInBackStack(Context context) {
return Preferences.getPreferences(context).getAccounts().length == 1;
}
/**
* Configure the notification sound and LED
*
* @param builder
* {@link NotificationCompat.Builder} instance used to configure the notification.
* Never {@code null}.
* @param ringtone
* String name of ringtone. {@code null}, if no ringtone should be played.
* @param vibrationPattern
* {@code long[]} vibration pattern. {@code null}, if no vibration should be played.
* @param ledColor
* Color to flash LED. {@code null}, if no LED flash should happen.
* @param ledSpeed
* Either {@link K9#NOTIFICATION_LED_BLINK_SLOW} or
* {@link K9#NOTIFICATION_LED_BLINK_FAST}.
* @param ringAndVibrate
* {@code true}, if ringtone/vibration are allowed. {@code false}, otherwise.
*/
private void configureNotification(NotificationCompat.Builder builder, String ringtone,
long[] vibrationPattern, Integer ledColor, int ledSpeed, boolean ringAndVibrate) {
// if it's quiet time, then we shouldn't be ringing, buzzing or flashing
if (K9.isQuietTime()) {
return;
}
if (ringAndVibrate) {
if (ringtone != null && !TextUtils.isEmpty(ringtone)) {
builder.setSound(Uri.parse(ringtone));
}
if (vibrationPattern != null) {
builder.setVibrate(vibrationPattern);
}
}
if (ledColor != null) {
int ledOnMS;
int ledOffMS;
if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) {
ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
} else {
ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
builder.setLights(ledColor, ledOnMS, ledOffMS);
}
}
/** Cancel a notification of new email messages */
public void notifyAccountCancel(Context context, Account account) {
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(account.getAccountNumber());
notifMgr.cancel(-1000 - account.getAccountNumber());
notificationData.remove(account.getAccountNumber());
}
/**
* Save a draft message.
* @param account Account we are saving for.
* @param message Message to save.
* @return Message representing the entry in the local store.
*/
public Message saveDraft(final Account account, final Message message, long existingDraftId) {
Message localMessage = null;
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(Folder.OPEN_MODE_RW);
if (existingDraftId != INVALID_MESSAGE_ID) {
String uid = localFolder.getMessageUidById(existingDraftId);
message.setUid(uid);
}
// Save the message to the store.
localFolder.appendMessages(new Message[] {
message
});
// Fetch the message back from the store. This is the Message that's returned to the caller.
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] {
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, null, e);
}
return localMessage;
}
public long getId(Message message) {
long id;
if (message instanceof LocalMessage) {
id = ((LocalMessage) message).getId();
} else {
Log.w(K9.LOG_TAG, "MessagingController.getId() called without a LocalMessage");
id = INVALID_MESSAGE_ID;
}
return id;
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) {
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)) {
return true;
} else {
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
static class Command implements Comparable<Command> {
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
@Override
public int compareTo(Command other) {
if (other.isForeground && !isForeground) {
return 1;
} else if (!other.isForeground && isForeground) {
return -1;
} else {
return (sequence - other.sequence);
}
}
}
public MessagingListener getCheckMailListener() {
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener) {
if (this.checkMailListener != null) {
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null) {
addListener(this.checkMailListener);
}
}
public Collection<Pusher> getPushers() {
return pushers.values();
}
public boolean setupPushing(final Account account) {
try {
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null) {
previousPusher.stop();
}
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false)) {
if (folder.getName().equals(account.getErrorFolderName())
|| folder.getName().equals(account.getOutboxFolderName())) {
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which should never be pushed");
*/
continue;
}
folder.open(Folder.OPEN_MODE_RW);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass)) {
// Never push a folder that isn't displayed
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
*/
continue;
}
if (modeMismatch(aPushMode, fPushClass)) {
// Do not push folders in the wrong class
/*
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
*/
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (!names.isEmpty()) {
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try {
Store store = account.getRemoteStore();
if (!store.isPushCapable()) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
if (pusher != null) {
Pusher oldPusher = pushers.putIfAbsent(account, pusher);
if (oldPusher == null) {
pusher.start(names);
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
} else {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing() {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext()) {
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable() {
@Override
public void run() {
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(remoteFolder.getName());
localFolder.open(Folder.OPEN_MODE_RW);
account.setRingNotified(false);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = localFolder.getUnreadMessageCount();
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0) {
notifyAccountCancel(mApplication, account);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
} catch (Exception e) {
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try {
// Oddly enough, using a local variable gets rid of a
// potential null pointer access warning with Eclipse.
LocalFolder folder = localFolder;
folder.setStatus(errorMessage);
} catch (Exception se) {
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, null, e);
} finally {
closeFolder(localFolder);
latch.countDown();
}
}
});
try {
latch.await();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
public void systemStatusChanged() {
for (MessagingListener l : getListeners()) {
l.systemStatusChanged();
}
}
enum MemorizingState { STARTED, FINISHED, FAILED }
static class Memory {
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName) {
account = nAccount;
folderName = nFolderName;
}
String getKey() {
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName) {
return taccount.getDescription() + ":" + tfolderName;
}
static class MemorizingListener extends MessagingListener {
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName) {
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null) {
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
@Override
public synchronized void synchronizeMailboxStarted(Account account, String folder) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
@Override
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other) {
if (other != null) {
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values()) {
if (memory.syncingState != null) {
switch (memory.syncingState) {
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null) {
switch (memory.sendingState) {
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null) {
switch (memory.pushingState) {
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
case FAILED:
break;
}
}
if (memory.processingState != null) {
switch (memory.processingState) {
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null) {
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null) {
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null) {
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null) {
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
} else {
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0) {
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active) {
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
@Override
public synchronized void sendPendingMessagesStarted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void sendPendingMessagesCompleted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
@Override
public synchronized void sendPendingMessagesFailed(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
@Override
public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) {
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
@Override
public synchronized void pendingCommandsProcessing(Account account) {
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void pendingCommandsFinished(Account account) {
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
@Override
public synchronized void pendingCommandStarted(Account account, String commandTitle) {
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
@Override
public synchronized void pendingCommandCompleted(Account account, String commandTitle) {
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
private void actOnMessages(List<Message> messages, MessageActor actor) {
Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>();
for (Message message : messages) {
if ( message == null) {
continue;
}
Folder folder = message.getFolder();
Account account = folder.getAccount();
Map<Folder, List<Message>> folderMap = accountMap.get(account);
if (folderMap == null) {
folderMap = new HashMap<Folder, List<Message>>();
accountMap.put(account, folderMap);
}
List<Message> messageList = folderMap.get(folder);
if (messageList == null) {
messageList = new LinkedList<Message>();
folderMap.put(folder, messageList);
}
messageList.add(message);
}
for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) {
Account account = entry.getKey();
//account.refresh(Preferences.getPreferences(K9.app));
Map<Folder, List<Message>> folderMap = entry.getValue();
for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) {
Folder folder = folderEntry.getKey();
List<Message> messageList = folderEntry.getValue();
actor.act(account, folder, messageList);
}
}
}
interface MessageActor {
public void act(final Account account, final Folder folder, final List<Message> messages);
}
} |
package cn.christian.msdl;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created in IntelliJ IDEA.
* MSDL
* cn.christian.msdl
*
* @author Christian_Chen
* @github freestyletime@foxmail.com
* @mail mailchristianchen@gmail.com
* @time 14-9-16 1:51
* @describtion A flag that user can use this in his own method.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DownLoadCallback {
//void fun(DownLoadUserTask task);
} |
package com.occidere.kookmincarteparser;
import android.content.Intent;
import android.graphics.Color;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView tv;
static String print;
private static final String address = "http://kmucoop.kookmin.ac.kr/restaurant/restaurant.php?w=";
private static String breakfast="", lunch="", dinner="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "Made by occidere", Toast.LENGTH_SHORT).show();
getSupportActionBar().setDisplayShowHomeEnabled(true);
// onCreate
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
setContentView(R.layout.activity_main);
print="";
tv = (TextView)findViewById(R.id.mainText);
try{
String today = findToday();
print+="## "+today+" ##\n\n";
parseBubsik();
parseHaksik();
parseFaculty();
parseChunghyang();
printAll();
tv.setText(print);
tv.setTextColor(Color.BLACK);
}
catch(Exception e){
tv.setText(e.getLocalizedMessage());
}
}
private static String findToday(){
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR), month = cal.get(Calendar.MONTH)+1, date = cal.get(Calendar.DATE);
return year+" "+month+" "+date+"";
}
// Elements
private static Elements jsoupConnect(String address) throws Exception {
String tag = "td[bgcolor=#eaffd9]";
Document doc = Jsoup.connect(address).timeout(5000).get();
return doc.select(tag);
}
private static void parseBubsik() throws Exception {
String bubsik = "[]", tmp;
Elements menu = jsoupConnect(address+1);
for (Element res : menu) {
tmp = removeBracket(res.text());
if(tmp.contains("**"))lunch+=bubsik+tmp.substring(tmp.indexOf("**")+4)+"\n";
else if(tmp.contains("**")) dinner+=bubsik+tmp.substring(tmp.indexOf("**")+4)+"\n";
else if(tmp.contains("**")){
lunch+=bubsik+tmp.substring(tmp.indexOf("**")+5)+"\n";
dinner+=bubsik+tmp.substring(tmp.indexOf("**")+5)+"\n";
}
else breakfast+=bubsik+" "+tmp+"\n";
}
breakfast+="\n"; lunch+="\n"; dinner+="\n";
}
private static void parseHaksik() throws Exception {
String haksik = "[]", tmp;
Elements menu = jsoupConnect(address+2);
int i=0;
for (Element res : menu) {
tmp = removeBracket(res.text());
if(i==0) breakfast+=(haksik+" "+tmp+"\n");
else if(i<6) lunch+=(haksik+" "+tmp+"\n");
else dinner+=(haksik+" "+tmp+"\n");
i++;
if(i>8) break;
}
breakfast+="\n"; lunch+="\n"; dinner+="\n";
}
private static void parseFaculty() throws Exception{
String faculty = "[]", tmp;
Elements menu = jsoupConnect(address+3);
int i=0;
for(Element res : menu){
tmp = removeBracket(res.text());tmp = tmp.substring(tmp.indexOf(']')+1).trim();
if(i>2) dinner+=(faculty+" "+tmp+"\n");
else lunch+=(faculty+" "+tmp+"\n");
i++;
}
lunch+="\n"; dinner+="\n";
}
private static void parseChunghyang() throws Exception{
String chunghyang = "[]", tmp;
Elements menu = jsoupConnect(address+4);
for(Element res : menu){
tmp = removeBracket(res.text());
lunch+=(chunghyang+" "+tmp+"\n");
}
lunch+="\n";
}
private static void printAll(){
print+="
print+=breakfast;
print+="
print+=lunch;
print+="
print+=dinner;
}
private static String removeBracket(String menu){
char tmp[] = menu.toCharArray();
int i, j=0, size = menu.length();
StringBuilder res = new StringBuilder();
char stack[] = new char[size];
for(i=0;i<size;i++){
if(tmp[i]=='('){
while(true) {
if(tmp[i]==')') break;
else i++;
}
}
else if(tmp[i]=='[') {
while(true) {
if(tmp[i]==']') break;
else i++;
}
}
else stack[j++] = tmp[i];
}
for(i=0;i<j;i++) res.append(stack[i]);
return res.toString().trim();
}
public void onClick(View view){
Intent msg = new Intent(Intent.ACTION_SEND);
msg.addCategory(Intent.CATEGORY_DEFAULT);
msg.putExtra(Intent.EXTRA_TEXT, print);
msg.setType("text/plain");
startActivity(Intent.createChooser(msg, ""));
}
@Override
protected void onDestroy() {
super.onDestroy();
breakfast=""; lunch=""; dinner="";
print="";
}
} |
package com.malhartech.lib.io;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.validation.constraints.NotNull;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.annotation.ShipContainingJars;
/**
* Base class for any ActiveMQ input or output adapter operator. <p><br>
* Operators should not be derived from this,
* rather from AbstractActiveMQInputOperator or AbstractActiveMQSinglePortInputOperator or AbstractActiveMQOutputOperator
* or AbstractActiveMQSinglePortOutputOperator. This creates connection with active MQ broker.<br>
*
* <br>
* Ports:<br>
* None<br>
* <br>
* Properties:<br>
* <b>usr</b>: userid for connecting to active MQ message bus<br>
* <b>password</b>: password for connecting to active MQ message bus<br>
* <b>url</b>: URL for connecting to active MQ message bus<br>
* <b>ackMode</b>: message acknowledgment mode<br>
* <b>clientId</b>: client id<br>
* <b>subject</b>: name of destination<br>
* <b>durable</b>: flag to indicate durable consumer<br>
* <b>topic</b>: flag to indicate if the destination is a topic or queue<br>
* <b>transacted</b>: flag whether the messages should be transacted or not<br>
* <br>
* Compile time checks:<br>
* usr should not be null<br>
* password should not be null<br>
* url should not be null<br>
* <br>
* Run time checks:<br>
* None<br>
* <br>
* Benchmarks:<br>
* NA<br>
* <br>
* @author Locknath Shil <locknath@malhar-inc.com>
*
*/
@ShipContainingJars(classes = {javax.jms.Message.class, org.apache.activemq.ActiveMQConnectionFactory.class, javax.management.j2ee.statistics.Stats.class})
public class ActiveMQBase
{
private static final Logger logger = LoggerFactory.getLogger(ActiveMQBase.class);
private transient Connection connection;
private transient Session session;
private transient Destination destination;
@NotNull
private String user = "";
@NotNull
private String password = "";
@NotNull
private String url;
private String ackMode = "CLIENT_ACKNOWLEDGE";
private String clientId = "TestClient";
private String subject = "TEST.FOO";
private int batch = 10;
private int messageSize = 255;
private boolean durable = false;
private boolean topic = false;
private boolean transacted = false;
private boolean verbose = false;
public Connection getConnection()
{
return connection;
}
public Session getSession()
{
return session;
}
public Destination getDestination()
{
return destination;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getAckMode()
{
return ackMode;
}
public void setAckMode(String ackMode)
{
this.ackMode = ackMode;
}
public String getClientId()
{
return clientId;
}
public void setClientId(String clientId)
{
this.clientId = clientId;
}
public String getSubject()
{
return subject;
}
public void setSubject(String subject)
{
this.subject = subject;
}
public int getBatch()
{
return batch;
}
public void setBatch(int batch)
{
this.batch = batch;
}
public int getMessageSize()
{
return messageSize;
}
public void setMessageSize(int messageSize)
{
this.messageSize = messageSize;
}
public boolean isDurable()
{
return durable;
}
public void setDurable(boolean durable)
{
this.durable = durable;
}
public boolean isTopic()
{
return topic;
}
public void setTopic(boolean topic)
{
this.topic = topic;
}
public boolean isTransacted()
{
return transacted;
}
public void setTransacted(boolean transacted)
{
this.transacted = transacted;
}
public boolean isVerbose()
{
return verbose;
}
public void setVerbose(boolean verbose)
{
this.verbose = verbose;
}
/**
* Get session acknowledge.
* Converts acknowledge string into JMS Session variable.
*/
public int getSessionAckMode(String ackMode)
{
if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
return Session.CLIENT_ACKNOWLEDGE;
}
else if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
return Session.AUTO_ACKNOWLEDGE;
}
else if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
return Session.DUPS_OK_ACKNOWLEDGE;
}
else if ("SESSION_TRANSACTED".equals(ackMode)) {
return Session.SESSION_TRANSACTED;
}
else {
return Session.CLIENT_ACKNOWLEDGE; // default
}
}
/**
* Connection specific setup for ActiveMQ.
*
* @throws JMSException
*/
public void createConnection() throws JMSException
{
// Create connection
ActiveMQConnectionFactory connectionFactory;
connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection();
if (durable && clientId != null) {
connection.setClientID(clientId);
}
connection.start();
// Create session
session = connection.createSession(transacted, getSessionAckMode(ackMode));
// Create destination
destination = topic
? session.createTopic(subject)
: session.createQueue(subject);
}
/**
* cleanup connection resources.
*/
public void cleanup()
{
try {
session.close();
connection.close();
session = null;
connection = null;
}
catch (JMSException ex) {
logger.debug(ex.getLocalizedMessage());
}
}
} |
package mustache.clojure.glue;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.DefaultMustacheVisitor;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.TemplateContext;
import com.github.mustachejava.codes.NotIterableCode;
/**
*
* @author bill
*/
public class ClojureMustacheVisitor extends DefaultMustacheVisitor {
public ClojureMustacheVisitor(DefaultMustacheFactory df) {
super(df);
}
@Override
public void iterable(TemplateContext templateContext, String variable, Mustache mustache) {
list.add(new ClojureIterableCode(templateContext, df, mustache, variable));
}
@Override
public void notIterable(TemplateContext templateContext, String variable, Mustache mustache) {
list.add(new ClojureNotIterableCode(templateContext, df, mustache, variable));
}
} |
package com.squareup.seismic;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.util.ArrayList;
import java.util.List;
/**
* Detects phone shaking. If more than 75% of the samples taken in the past 0.5s are
* accelerating, the device is a) shaking, or b) free falling 1.84m (h =
* 1/2*g*t^2*3/4).
*
* @author Bob Lee (bob@squareup.com)
* @author Eric Burke (eric@squareup.com)
*/
public class ShakeDetector implements SensorEventListener {
public static final int SENSITIVITY_LIGHT = 11;
public static final int SENSITIVITY_MEDIUM = 13;
public static final int SENSITIVITY_HARD = 15;
private static final int DEFAULT_ACCELERATION_THRESHOLD = SENSITIVITY_MEDIUM;
/**
* When the magnitude of total acceleration exceeds this
* value, the phone is accelerating.
*/
private int accelerationThreshold = DEFAULT_ACCELERATION_THRESHOLD;
/** Listens for shakes. */
public interface Listener {
/** Called on the main thread when the device is shaken. */
void hearShake();
}
private final SampleQueue queue = new SampleQueue();
private final Listener listener;
private SensorManager sensorManager;
private Sensor accelerometer;
public ShakeDetector(Listener listener) {
this.listener = listener;
}
/**
* Starts listening for shakes on devices with appropriate hardware.
*
* @return true if the device supports shake detection.
*/
public boolean start(SensorManager sensorManager) {
// Already started?
if (accelerometer != null) {
return true;
}
accelerometer = sensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER);
// If this phone has an accelerometer, listen to it.
if (accelerometer != null) {
this.sensorManager = sensorManager;
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
}
return accelerometer != null;
}
/**
* Stops listening. Safe to call when already stopped. Ignored on devices
* without appropriate hardware.
*/
public void stop() {
if (accelerometer != null) {
sensorManager.unregisterListener(this, accelerometer);
sensorManager = null;
accelerometer = null;
}
}
@Override public void onSensorChanged(SensorEvent event) {
boolean accelerating = isAccelerating(event);
long timestamp = event.timestamp;
queue.add(timestamp, accelerating);
if (queue.isShaking()) {
queue.clear();
listener.hearShake();
}
}
/** Returns true if the device is currently accelerating. */
private boolean isAccelerating(SensorEvent event) {
float ax = event.values[0];
float ay = event.values[1];
float az = event.values[2];
// Instead of comparing magnitude to ACCELERATION_THRESHOLD,
// compare their squares. This is equivalent and doesn't need the
// actual magnitude, which would be computed using (expesive) Math.sqrt().
final double magnitudeSquared = ax * ax + ay * ay + az * az;
return magnitudeSquared > accelerationThreshold * accelerationThreshold;
}
/** Sets the acceleration threshold sensitivity. */
public void setSensitivity(int accelerationThreshold) {
this.accelerationThreshold = accelerationThreshold;
}
/** Queue of samples. Keeps a running average. */
static class SampleQueue {
/** Window size in ns. Used to compute the average. */
private static final long MAX_WINDOW_SIZE = 500000000; // 0.5s
private static final long MIN_WINDOW_SIZE = MAX_WINDOW_SIZE >> 1; // 0.25s
/**
* Ensure the queue size never falls below this size, even if the device
* fails to deliver this many events during the time window. The LG Ally
* is one such device.
*/
private static final int MIN_QUEUE_SIZE = 4;
private final SamplePool pool = new SamplePool();
private Sample oldest;
private Sample newest;
private int sampleCount;
private int acceleratingCount;
/**
* Adds a sample.
*
* @param timestamp in nanoseconds of sample
* @param accelerating true if > {@link #accelerationThreshold}.
*/
void add(long timestamp, boolean accelerating) {
// Purge samples that proceed window.
purge(timestamp - MAX_WINDOW_SIZE);
// Add the sample to the queue.
Sample added = pool.acquire();
added.timestamp = timestamp;
added.accelerating = accelerating;
added.next = null;
if (newest != null) {
newest.next = added;
}
newest = added;
if (oldest == null) {
oldest = added;
}
// Update running average.
sampleCount++;
if (accelerating) {
acceleratingCount++;
}
}
/** Removes all samples from this queue. */
void clear() {
while (oldest != null) {
Sample removed = oldest;
oldest = removed.next;
pool.release(removed);
}
newest = null;
sampleCount = 0;
acceleratingCount = 0;
}
/** Purges samples with timestamps older than cutoff. */
void purge(long cutoff) {
while (sampleCount >= MIN_QUEUE_SIZE
&& oldest != null && cutoff - oldest.timestamp > 0) {
// Remove sample.
Sample removed = oldest;
if (removed.accelerating) {
acceleratingCount
}
sampleCount
oldest = removed.next;
if (oldest == null) {
newest = null;
}
pool.release(removed);
}
}
/** Copies the samples into a list, with the oldest entry at index 0. */
List<Sample> asList() {
List<Sample> list = new ArrayList<Sample>();
Sample s = oldest;
while (s != null) {
list.add(s);
s = s.next;
}
return list;
}
/**
* Returns true if we have enough samples and more than 3/4 of those samples
* are accelerating.
*/
boolean isShaking() {
return newest != null
&& oldest != null
&& newest.timestamp - oldest.timestamp >= MIN_WINDOW_SIZE
&& acceleratingCount >= (sampleCount >> 1) + (sampleCount >> 2);
}
}
/** An accelerometer sample. */
static class Sample {
/** Time sample was taken. */
long timestamp;
/** If acceleration > {@link #accelerationThreshold}. */
boolean accelerating;
/** Next sample in the queue or pool. */
Sample next;
}
/** Pools samples. Avoids garbage collection. */
static class SamplePool {
private Sample head;
/** Acquires a sample from the pool. */
Sample acquire() {
Sample acquired = head;
if (acquired == null) {
acquired = new Sample();
} else {
// Remove instance from pool.
head = acquired.next;
}
return acquired;
}
/** Returns a sample to the pool. */
void release(Sample sample) {
sample.next = head;
head = sample;
}
}
@Override public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
} |
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.diagnostic.Logger;
import org.jdom.Element;
/**
* This singleton maintains the instances of all the key groups. All the key/action mappings get created the first
* this singleton is accessed.
*/
public class CommandGroups
{
/**
* Gets the singleton instance
* @return The singleton instance
*/
public static CommandGroups getInstance()
{
if (instance == null)
{
instance = new CommandGroups();
}
return instance;
}
/**
* Creates all the groups
*/
private CommandGroups()
{
motion = new MotionGroup();
change = new ChangeGroup();
copy = new CopyGroup();
mark = new MarkGroup();
register = new RegisterGroup();
file = new FileGroup();
search = new SearchGroup();
}
/**
* Returns the motion group
* @return The motion group
*/
public MotionGroup getMotion()
{
return motion;
}
/**
* Returns the change group
* @return The change group
*/
public ChangeGroup getChange()
{
return change;
}
/**
* Returns the copy group
* @return The copy group
*/
public CopyGroup getCopy()
{
return copy;
}
/**
* Returns the mark group
* @return The mark group
*/
public MarkGroup getMark()
{
return mark;
}
/**
* Returns the register group
* @return The register group
*/
public RegisterGroup getRegister()
{
return register;
}
/**
* Returns the file group
* @return The file group
*/
public FileGroup getFile()
{
return file;
}
/**
* Returns the search group
* @return The search group
*/
public SearchGroup getSearch()
{
return search;
}
/**
* Tells each group to save its data.
* @param element The plugin's root element
*/
public void saveData(Element element)
{
motion.saveData(element);
change.saveData(element);
copy.saveData(element);
mark.saveData(element);
register.saveData(element);
file.saveData(element);
search.saveData(element);
}
/**
* Tells each group to read its data.
* @param element The plugin's root element
*/
public void readData(Element element)
{
logger.debug("readData");
motion.readData(element);
change.readData(element);
copy.readData(element);
mark.readData(element);
register.readData(element);
file.readData(element);
search.readData(element);
}
private static CommandGroups instance;
private MotionGroup motion;
private ChangeGroup change;
private CopyGroup copy;
private MarkGroup mark;
private RegisterGroup register;
private FileGroup file;
private SearchGroup search;
private static Logger logger = Logger.getInstance(CommandGroups.class.getName());
} |
package io.fotoapparat.hardware.v1;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.support.annotation.NonNull;
import android.view.SurfaceHolder;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.fotoapparat.hardware.CameraDevice;
import io.fotoapparat.hardware.CameraException;
import io.fotoapparat.hardware.Capabilities;
import io.fotoapparat.hardware.Parameters;
import io.fotoapparat.hardware.orientation.OrientationUtils;
import io.fotoapparat.log.Logger;
import io.fotoapparat.parameter.LensPosition;
import io.fotoapparat.photo.Photo;
/**
* Camera hardware driver for v1 {@link Camera} API.
*/
@SuppressWarnings("deprecation")
public class Camera1 implements CameraDevice {
private final CapabilitiesFactory capabilitiesFactory;
private final ParametersConverter parametersConverter;
private final Logger logger;
private Camera camera;
private int cameraId;
private Throwable lastStacktrace;
public Camera1(Logger logger) {
this.capabilitiesFactory = new CapabilitiesFactory();
this.parametersConverter = new ParametersConverter();
this.logger = logger;
}
@Override
public void open(LensPosition lensPosition) {
recordMethod();
try {
cameraId = cameraIdForLensPosition(lensPosition);
camera = Camera.open(cameraId);
} catch (RuntimeException e) {
throw new CameraException(e);
}
// TODO apply parameters
camera.setErrorCallback(new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
if (lastStacktrace != null) {
lastStacktrace.printStackTrace();
}
throw new IllegalStateException("Camera error code: " + error);
}
});
}
private int cameraIdForLensPosition(LensPosition lensPosition) {
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = getCameraInfo(i);
if (info.facing == facingForLensPosition(lensPosition)) {
return i;
}
}
return 0;
}
private int facingForLensPosition(LensPosition lensPosition) {
switch (lensPosition) {
case FRONT:
return Camera.CameraInfo.CAMERA_FACING_FRONT;
case BACK:
return Camera.CameraInfo.CAMERA_FACING_BACK;
default:
throw new IllegalArgumentException("Camera is not supported: " + lensPosition);
}
}
@Override
public void close() {
recordMethod();
if (camera != null) {
camera.release();
}
}
@Override
public void startPreview() {
recordMethod();
camera.startPreview();
}
@Override
public void stopPreview() {
recordMethod();
camera.stopPreview();
}
@Override
public void setDisplaySurface(Object displaySurface) {
recordMethod();
try {
trySetDisplaySurface(displaySurface);
} catch (IOException e) {
throw new CameraException(e);
}
}
@Override
public void setDisplayOrientation(int degrees) {
recordMethod();
degrees = OrientationUtils.toClosestRightAngle(degrees);
Camera.CameraInfo info = getCameraInfo(cameraId);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
degrees = (info.orientation + degrees) % 360;
degrees = (360 - degrees) % 360;
} else {
degrees = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(degrees);
}
@Override
public void updateParameters(Parameters parameters) {
recordMethod();
Camera.Parameters cameraParameters = parametersConverter.convert(
parameters,
camera.getParameters()
);
camera.setParameters(cameraParameters);
}
@Override
public Capabilities getCapabilities() {
recordMethod();
return capabilitiesFactory.fromParameters(
camera.getParameters()
);
}
private void trySetDisplaySurface(Object displaySurface) throws IOException {
if (displaySurface instanceof SurfaceTexture) {
camera.setPreviewTexture(((SurfaceTexture) displaySurface));
} else if (displaySurface instanceof SurfaceHolder) {
camera.setPreviewDisplay(((SurfaceHolder) displaySurface));
} else {
throw new IllegalArgumentException("Unsupported display surface: " + displaySurface);
}
}
@Override
public Photo takePicture() {
recordMethod();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Photo> photoReference = new AtomicReference<>();
camera.takePicture(
null,
null,
null,
new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
photoReference.set(
new Photo(
data,
0 // TODO check current screen orientation
)
);
latch.countDown();
}
}
);
try {
latch.await();
} catch (InterruptedException e) {
// Do nothing
}
return photoReference.get();
}
@NonNull
private Camera.CameraInfo getCameraInfo(int id) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
return info;
}
private void recordMethod() {
lastStacktrace = new Exception();
logger.log(
lastStacktrace.getStackTrace()[1].getMethodName()
);
}
} |
package org.broadinstitute.sting.utils;
import edu.mit.broad.picard.util.Interval;
import edu.mit.broad.picard.directed.IntervalList;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMSequenceDictionary;
import net.sf.samtools.SAMSequenceRecord;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GenomeLoc implements Comparable<GenomeLoc>, Cloneable {
private static Logger logger = Logger.getLogger(GenomeLoc.class);
private int contigIndex;
private long start;
private long stop;
// Ugly global variable defining the optional ordering of contig elements
//public static Map<String, Integer> refContigOrdering = null;
private static SAMSequenceDictionary contigInfo = null;
public static boolean hasKnownContigOrdering() {
return contigInfo != null;
}
public static SAMSequenceRecord getContigInfo( final String contig ) {
return contigInfo.getSequence(contig);
}
/**
* Returns the contig index of a specified string version of the contig
* @param contig the contig string
* @return the contig index, -1 if not found
*/
public static int getContigIndex( final String contig ) {
if (contigInfo.getSequenceIndex(contig) == -1)
Utils.scareUser(String.format("Contig %s given as location, but this contig isn't present in the Fasta sequence dictionary", contig));
return contigInfo.getSequenceIndex(contig);
}
public static boolean setupRefContigOrdering(final ReferenceSequenceFile refFile) {
return setupRefContigOrdering(refFile.getSequenceDictionary());
}
public static boolean setupRefContigOrdering(final SAMSequenceDictionary seqDict) {
if (seqDict == null) { // we couldn't load the reference dictionary
logger.info("Failed to load reference dictionary, falling back to lexicographic order for contigs");
Utils.scareUser("Failed to load reference dictionary");
return false;
} else if ( contigInfo == null ){
contigInfo = seqDict;
logger.debug(String.format("Prepared reference sequence contig dictionary"));
for (SAMSequenceRecord contig : seqDict.getSequences() ) {
logger.debug(String.format(" %s (%d bp)", contig.getSequenceName(), contig.getSequenceLength()));
}
}
return true;
}
// constructors
public GenomeLoc( int contigIndex, final long start, final long stop ) {
if(contigInfo == null) { throw new StingException("Contig info has not been setup in the GenomeLoc context yet."); }
if (!isSequenceIndexValid(contigIndex)) {
throw new StingException("Contig info has not been setup in the GenomeLoc context yet.");
}
if (start < 0) { throw new StingException("Bad start position " + start);}
if (stop < -1) { throw new StingException("Bad stop position " + stop); } // a negative -1 indicates it's not a meaningful end position
this.contigIndex = contigIndex;
this.start = start;
this.stop = stop == -1 ? start : stop;
}
public GenomeLoc(final SAMRecord read) {
this(read.getReferenceIndex(), read.getAlignmentStart(), read.getAlignmentEnd());
}
public GenomeLoc( final String contig, final long start, final long stop ) {
this(contigInfo.getSequenceIndex(contig), start, stop);
}
public GenomeLoc( final String contig, final long pos ) {
this(contig, pos, pos);
}
public GenomeLoc( final int contig, final long pos ) {
this(contig, pos, pos );
}
public GenomeLoc( final GenomeLoc toCopy ) {
this( toCopy.contigIndex, toCopy.getStart(), toCopy.getStop() );
}
// Parsing string representations
private static long parsePosition( final String pos ) {
String x = pos.replaceAll(",", "");
return Long.parseLong(x);
}
/**
* Use this static constructor when the input data is under limited control (i.e. parsing user data).
* @param contig Contig to parse.
* @param start Starting point.
* @param stop Stop point.
* @return The genome location, or a MalformedGenomeLocException if unparseable.
*/
public static GenomeLoc parseGenomeLoc( final String contig, long start, long stop ) {
if( !isContigValid(contig) )
throw new MalformedGenomeLocException("Contig " + contig + " does not match any contig in the GATK sequence dictionary derived from the reference.");
return new GenomeLoc(contig,start,stop);
}
public static GenomeLoc parseGenomeLoc( final String str ) {
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
//System.out.printf("Parsing location '%s'%n", str);
final Pattern regex1 = Pattern.compile("([\\w&&[^:]]+)$"); // matches case 1
final Pattern regex2 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)$"); // matches case 2
final Pattern regex3 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)-([\\d,]+)$"); // matches case 3
final Pattern regex4 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)\\+"); // matches case 4
String contig = null;
long start = 1;
long stop = Integer.MAX_VALUE;
boolean bad = false;
Matcher match1 = regex1.matcher(str);
Matcher match2 = regex2.matcher(str);
Matcher match3 = regex3.matcher(str);
Matcher match4 = regex4.matcher(str);
try {
if ( match1.matches() ) {
contig = match1.group(1);
}
else if ( match2.matches() ) {
contig = match2.group(1);
start = parsePosition(match2.group(2));
stop = start;
}
else if ( match4.matches() ) {
contig = match4.group(1);
start = parsePosition(match4.group(2));
}
else if ( match3.matches() ) {
contig = match3.group(1);
start = parsePosition(match3.group(2));
stop = parsePosition(match3.group(3));
if ( start > stop )
bad = true;
}
else {
bad = true;
}
} catch ( Exception e ) {
bad = true;
}
if ( bad ) {
throw new StingException("Invalid Genome Location string: " + str);
}
if ( stop == Integer.MAX_VALUE && hasKnownContigOrdering() ) {
// lookup the actually stop position!
stop = getContigInfo(contig).getSequenceLength();
}
if( !isContigValid(contig) )
throw new MalformedGenomeLocException("Contig " + contig + " does not match any contig in the GATK sequence dictionary derived from the reference.");
GenomeLoc loc = parseGenomeLoc(contig,start,stop);
// System.out.printf(" => Parsed location '%s' into %s%n", str, loc);
return loc;
}
/**
* Useful utility function that parses a location string into a coordinate-order sorted
* array of GenomeLoc objects
*
* @param str String representation of genome locs. Null string corresponds to no filter.
* @return Array of GenomeLoc objects corresponding to the locations in the string, sorted by coordinate order
*/
public static List<GenomeLoc> parseGenomeLocs(final String str) {
// Null string means no filter.
if( str == null ) return null;
// Of the form: loc1;loc2;...
// Where each locN can be:
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
try {
List<GenomeLoc> locs = new ArrayList<GenomeLoc>();
for( String loc: str.split(";") )
locs.add( parseGenomeLoc(loc.trim()) );
Collections.sort(locs);
//logger.info(String.format("Going to process %d locations", locs.length));
locs = mergeOverlappingLocations(locs);
logger.debug("Locations are:" + Utils.join(", ", locs));
return locs;
} catch (Exception e) {
e.printStackTrace();
Utils.scareUser(String.format("Invalid locations string: %s, format is loc1;loc2; where each locN can be 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'", str));
return null;
}
}
public static List<GenomeLoc> mergeOverlappingLocations(final List<GenomeLoc> raw) {
logger.debug(" Raw locations are:\n" + Utils.join("\n", raw));
if ( raw.size() <= 1 )
return raw;
else {
ArrayList<GenomeLoc> merged = new ArrayList<GenomeLoc>();
Iterator<GenomeLoc> it = raw.iterator();
GenomeLoc prev = it.next();
while ( it.hasNext() ) {
GenomeLoc curr = it.next();
if ( prev.contiguousP(curr) ) {
prev = prev.merge(curr);
} else {
merged.add(prev);
prev = curr;
}
}
merged.add(prev);
return merged;
}
}
/**
* Move this Genome loc to the next contig, with a start
* and stop of 1.
* @return true if we are not out of contigs, otherwise false if we're
* at the end of the genome (no more contigs to jump to).
*/
public boolean toNextContig() {
if ((contigIndex + 1) < GenomeLoc.contigInfo.size()) {
this.contigIndex++;
this.start = 1;
this.stop = 1;
return true;
}
return false;
}
/**
* Returns true iff we have a specified series of locations to process AND we are past the last
* location in the list. It means that, in a serial processing of the genome, that we are done.
*
* @param curr Current genome Location
* @return true if we are past the last location to process
*/
public static boolean pastFinalLocation(GenomeLoc curr, List<GenomeLoc> locs) {
return (locs.size() > 0 && curr.isPast(locs.get(locs.size() - 1)));
}
/**
* A key function that returns true if the proposed GenomeLoc curr is within the list of
* locations we are processing in this TraversalEngine
*
* @param curr
* @return true if we should process GenomeLoc curr, otherwise false
*/
public static boolean inLocations(GenomeLoc curr, ArrayList<GenomeLoc> locs) {
if ( locs.size() == 0 ) {
return true;
} else {
for ( GenomeLoc loc : locs ) {
//System.out.printf(" Overlap %s vs. %s => %b%n", loc, curr, loc.overlapsP(curr));
if (loc.overlapsP(curr))
return true;
}
return false;
}
}
public static void removePastLocs(GenomeLoc curr, List<GenomeLoc> locs) {
while ( !locs.isEmpty() && curr.isPast(locs.get(0)) ) {
//System.out.println("At: " + curr + ", removing: " + locs.get(0));
locs.remove(0);
}
}
public static boolean overlapswithSortedLocsP(GenomeLoc curr, List<GenomeLoc> locs, boolean returnTrueIfEmpty) {
if ( locs.isEmpty() )
return returnTrueIfEmpty;
// skip loci before intervals begin
if ( hasKnownContigOrdering() && curr.contigIndex < locs.get(0).contigIndex )
return false;
for ( GenomeLoc loc : locs ) {
//System.out.printf(" Overlap %s vs. %s => %b%n", loc, curr, loc.overlapsP(curr));
if ( loc.overlapsP(curr) )
return true;
if ( curr.compareTo(loc) < 0 )
return false;
}
return false;
}
// Accessors and setters
public final String getContig() {
//this.contigIndex != -1;
if (!(contigInfo != null && contigInfo.getSequences() != null)) {
throw new StingException("The contig information or it's sequences are null");
}
if ((this.contigIndex < 0) || (this.contigIndex >= contigInfo.getSequences().size())) {
throw new StingException("The contig index is not bounded by the zero and seqeunce count, contig index: " + contigIndex);
}
if (contigInfo.getSequence(this.contigIndex) == null ||
contigInfo.getSequence(this.contigIndex).getSequenceName() == null) {
throw new StingException("The associated sequence index for contig " + contigIndex + " is null");
}
return contigInfo.getSequence(this.contigIndex).getSequenceName();
//if (contigInfo != null && contigInfo.getSequence(this.contigIndex) != null) {
// return contigInfo.getSequence(this.contigIndex).getSequenceName();
//return null;
}
public final int getContigIndex() { return this.contigIndex; }
public final long getStart() { return this.start; }
public final long getStop() { return this.stop; }
public final String toString() {
if ( throughEndOfContigP() && atBeginningOfContigP() )
return getContig();
else if ( throughEndOfContigP() || getStart() == getStop() )
return String.format("%s:%d", getContig(), getStart());
else
return String.format("%s:%d-%d", getContig(), getStart(), getStop());
}
public final boolean isUnmapped() { return this.contigIndex == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX; }
public final boolean throughEndOfContigP() { return this.stop == Integer.MAX_VALUE; }
public final boolean atBeginningOfContigP() { return this.start == 1; }
public void setContig(String contig) {
this.contigIndex = contigInfo.getSequenceIndex(contig);
}
public void setStart(long start) {
this.start = start;
}
public void setStop(long stop) {
this.stop = stop;
}
public final boolean isSingleBP() { return stop == start; }
public final boolean disjointP(GenomeLoc that) {
if ( this.contigIndex != that.contigIndex ) return true; // different chromosomes
if ( this.start > that.stop ) return true; // this guy is past that
if ( that.start > this.stop ) return true; // that guy is past our start
return false;
}
public final boolean discontinuousP(GenomeLoc that) {
if ( this.contigIndex != that.contigIndex ) return true; // different chromosomes
if ( (this.start - 1) > that.stop ) return true; // this guy is past that
if ( (that.start - 1) > this.stop ) return true; // that guy is past our start
return false;
}
public final boolean overlapsP(GenomeLoc that) {
return ! disjointP( that );
}
public final boolean contiguousP(GenomeLoc that) {
return ! discontinuousP( that );
}
public GenomeLoc merge( GenomeLoc that ) throws StingException {
if (!(this.contiguousP(that))) {
throw new StingException("The two genome loc's need to be contigous");
}
return new GenomeLoc(getContig(),
Math.min(getStart(), that.getStart()),
Math.max( getStop(), that.getStop()) );
}
public final boolean containsP(GenomeLoc that) {
if ( ! onSameContig(that) ) return false;
return getStart() <= that.getStart() && getStop() >= that.getStop();
}
public final boolean onSameContig(GenomeLoc that) {
return (this.contigIndex == that.contigIndex);
}
public final int minus( final GenomeLoc that ) {
if ( this.contigIndex == that.contigIndex )
return (int) (this.getStart() - that.getStart());
else
return Integer.MAX_VALUE;
}
public final int distance( final GenomeLoc that ) {
return Math.abs(minus(that));
}
public final boolean isBetween( final GenomeLoc left, final GenomeLoc right ) {
return this.compareTo(left) > -1 && this.compareTo(right) < 1;
}
public final boolean isBefore( GenomeLoc that ) {
int comparison = this.compareContigs(that);
return ( comparison == -1 || ( comparison == 0 && this.getStop() < that.getStart() ));
}
public final boolean isPast( GenomeLoc that ) {
int comparison = this.compareContigs(that);
return ( comparison == 1 || ( comparison == 0 && this.getStart() > that.getStop() ));
}
public final void incPos() {
incPos(1);
}
public final void incPos(long by) {
this.start += by;
this.stop += by;
}
public final GenomeLoc nextLoc() {
GenomeLoc n = new GenomeLoc(this);
n.incPos();
return n;
}
/**
* Check to see whether two genomeLocs are equal.
* Note that this implementation ignores the contigInfo object.
* @param other Other contig to compare.
*/
@Override
public boolean equals(Object other) {
if(other == null)
return false;
if(other instanceof GenomeLoc) {
GenomeLoc otherGenomeLoc = (GenomeLoc)other;
return this.contigIndex == otherGenomeLoc.contigIndex &&
this.start == otherGenomeLoc.start &&
this.stop == otherGenomeLoc.stop;
}
return false;
}
@Override
public int hashCode() {
return (int)( start << 16 + stop << 4 + contigIndex );
}
/**
* Return a new GenomeLoc at this same position.
* @return A GenomeLoc with the same contents as the current loc.
*/
@Override
public GenomeLoc clone() {
return new GenomeLoc(this);
}
// Comparison operations
// TODO: get rid of this method because it's sloooooooooooooow
@Deprecated
public static int compareContigs( final String thisContig, final String thatContig )
{
if ( thisContig == thatContig )
{
// Optimization. If the pointers are equal, then the contigs are equal.
return 0;
}
if ( hasKnownContigOrdering() )
{
int thisIndex = getContigIndex(thisContig);
int thatIndex = getContigIndex(thatContig);
if ( thisIndex == -1 )
{
if ( thatIndex == -1 )
{
// Use regular sorted order
return thisContig.compareTo(thatContig);
}
else
{
// this is always bigger if that is in the key set
return 1;
}
}
else if ( thatIndex == -1 )
{
return -1;
}
else
{
if ( thisIndex < thatIndex ) return -1;
if ( thisIndex > thatIndex ) return 1;
return 0;
}
}
else
{
return thisContig.compareTo(thatContig);
}
}
public final int compareContigs( GenomeLoc that ) {
if (this.contigIndex == that.contigIndex)
return 0;
else if (this.contigIndex > that.contigIndex)
return 1;
return -1;
}
public int compareTo( GenomeLoc that ) {
if ( this == that ) return 0;
final int cmpContig = compareContigs(that);
if ( cmpContig != 0 ) return cmpContig;
if ( this.getStart() < that.getStart() ) return -1;
if ( this.getStart() > that.getStart() ) return 1;
// TODO: and error is being thrown because we are treating reads with the same start positions
// but different stop as out of order
//if ( this.getStop() < that.getStop() ) return -1;
//if ( this.getStop() > that.getStop() ) return 1;
return 0;
}
/**
* Read a file of genome locations to process.
* regions specified by the location string. The string is of the form:
* Of the form: loc1;loc2;...
* Where each locN can be:
* 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
*
* @param file_name
*/
public static List<GenomeLoc> IntervalFileToList(final String file_name) {
// first try to read it as an interval file since that's well structured
// we'll fail quickly if it's not a valid file. Then try to parse it as
// a location string file
List<GenomeLoc> ret = null;
try {
IntervalList il = IntervalList.fromFile(new File(file_name));
// iterate through the list of merged intervals and add then as GenomeLocs
ret = new ArrayList<GenomeLoc>();
for(Interval interval : il.getUniqueIntervals()) {
ret.add(new GenomeLoc(interval.getSequence(), interval.getStart(), interval.getEnd()));
}
return ret;
} catch (Exception e) {
try {
xReadLines reader = new xReadLines(new File(file_name));
List<String> lines = reader.readLines();
reader.close();
String locStr = Utils.join(";", lines);
logger.debug("locStr: " + locStr);
ret = parseGenomeLocs(locStr);
return ret;
} catch (Exception e2) {
logger.error("Attempt to parse interval file in GATK format failed: "+e2.getMessage());
e2.printStackTrace();
throw new StingException("Unable to parse out interval file in either format", e);
}
}
}
/**
* Determines whether the given contig is valid with respect to the sequence dictionary
* already installed in the GenomeLoc.
* @return True if the contig is valid. False otherwise.
*/
private static boolean isContigValid( String contig ) {
int contigIndex = contigInfo.getSequenceIndex(contig);
return isSequenceIndexValid(contigIndex);
}
/**
* Determines whether the given sequence index is valid with respect to the sequence dictionary.
* @param sequenceIndex sequence index
* @return True if the sequence index is valid, false otherwise.
*/
private static boolean isSequenceIndexValid( int sequenceIndex ) {
return sequenceIndex >= 0 && sequenceIndex < contigInfo.size();
}
} |
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class CmsNewResourceUpload extends CmsWorkplaceDefault implements I_CmsWpConstants,I_CmsConstants {
/** Vector containing all names of the radiobuttons */
private Vector m_names = null;
/** Vector containing all links attached to the radiobuttons */
private Vector m_values = null;
/**
* Overwrites the getContent method of the CmsWorkplaceDefault.<br>
* Gets the content of the new resource upload page template and processed the data input.
* @param cms The CmsObject.
* @param templateFile The upload template file
* @param elementName not used
* @param parameters Parameters of the request and the template.
* @param templateSelector Selector of the template tag to be displayed.
* @return Bytearry containing the processed data of the template.
* @exception Throws CmsException if something goes wrong.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException {
// the template to be displayed
String template = null;
I_CmsSession session = cms.getRequestContext().getSession(true);
// clear session values on first load
String initial = (String)parameters.get(C_PARA_INITIAL);
if(initial != null) {
// remove all session values
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_FILECONTENT);
session.removeValue(C_PARA_NEWTYPE);
session.removeValue("lasturl");
}
String lastUrl = getLastUrl(cms, parameters);
// get the parameters from the request and session
String step = (String)parameters.get("STEP");
String currentFolder = (String)parameters.get(C_PARA_FILELIST);
if(currentFolder != null) {
session.putValue(C_PARA_FILELIST, currentFolder);
}
currentFolder = (String)session.getValue(C_PARA_FILELIST);
if(currentFolder == null) {
currentFolder = cms.rootFolder().getAbsolutePath();
}
String title = (String)parameters.get(C_PARA_TITLE);
String newname = (String)parameters.get(C_PARA_NAME);
// get filename and file content if available
String filename = null;
byte[] filecontent = new byte[0];
// get the filename
Enumeration files = cms.getRequestContext().getRequest().getFileNames();
while(files.hasMoreElements()) {
filename = (String)files.nextElement();
}
if(filename != null) {
session.putValue(C_PARA_FILE, filename);
}
filename = (String)session.getValue(C_PARA_FILE);
// get the filecontent
if(filename != null) {
filecontent = cms.getRequestContext().getRequest().getFile(filename);
}
if(filecontent != null) {
session.putValue(C_PARA_FILECONTENT, filecontent);
}
filecontent = (byte[])session.getValue(C_PARA_FILECONTENT);
//get the filetype
String newtype = (String)parameters.get(C_PARA_NEWTYPE);
if(newtype != null) {
session.putValue(C_PARA_NEWTYPE, newtype);
}
newtype = (String)session.getValue(C_PARA_NEWTYPE);
// get the document to display
CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
xmlTemplateDocument.setData("lasturl", lastUrl);
// there was a file uploaded, so select its type
if(step != null) {
if(step.equals("1")) {
// display the select filetype screen
if(filename != null) {
// check if the file size is 0
if(filecontent.length == 0) {
template = "error";
xmlTemplateDocument.setData("details", filename);
}
else {
template = "step1";
}
}
}
else {
if(step.equals("2")) {
// get the selected resource and check if it is an image
CmsResourceType type = cms.getResourceType(newtype);
if(newtype.equals(C_TYPE_IMAGE_NAME)) {
// the file type is an image
template = "image";
xmlTemplateDocument.setData("MIME", filename);
xmlTemplateDocument.setData("SIZE", "Not yet available");
xmlTemplateDocument.setData("FILESIZE", new Integer(filecontent.length).toString() + " Bytes");
}
else {
// create the new file.
// todo: error handling if file already exits
cms.createFile(currentFolder, filename, filecontent, type.getResourceName());
cms.lockResource(currentFolder+filename);
// remove the values form the session
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_FILECONTENT);
session.removeValue(C_PARA_NEWTYPE);
// return to the filelist
try {
//cms.getRequestContext().getResponse().sendCmsRedirect( getConfigFile(cms).getWorkplaceActionPath()+C_WP_EXPLORER_FILELIST);
if((lastUrl != null) && (lastUrl != "")) {
cms.getRequestContext().getResponse().sendRedirect(lastUrl);
}
else {
cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST);
}
}
catch(Exception ex) {
throw new CmsException("Redirect fails :" + getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST, CmsException.C_UNKNOWN_EXCEPTION, ex);
}
return null;
}
}
else {
if(step.equals("3")) {
// get the data from the special image upload dialog
// check if a new filename is given
if(newname != null) {
filename = newname;
}
// create the new file.
// todo: error handling if file already exits
CmsResourceType type = cms.getResourceType(newtype);
CmsFile file = cms.createFile(currentFolder, filename, filecontent, type.getResourceName());
// check if a file title was given
if(title != null) {
cms.lockResource(file.getAbsolutePath());
cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_TITLE, title);
}
// remove the values form the session
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_FILECONTENT);
session.removeValue(C_PARA_NEWTYPE);
session.removeValue("lasturl");
// return to the filelist
try {
if((lastUrl != null) && (lastUrl != "")) {
cms.getRequestContext().getResponse().sendRedirect(lastUrl);
}
else {
cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST);
}
}
catch(Exception ex) {
throw new CmsException("Redirect fails :" + getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST, CmsException.C_UNKNOWN_EXCEPTION, ex);
}
return null;
}
}
}
}
if(filename != null) {
xmlTemplateDocument.setData("FILENAME", filename);
}
// process the selected template
return startProcessing(cms, xmlTemplateDocument, "", parameters, template);
}
/**
* Gets the resources displayed in the Radiobutton group on the chtype dialog.
* @param cms The CmsObject.
* @param lang The langauge definitions.
* @param names The names of the new rescources.
* @param values The links that are connected with each resource.
* @param parameters Hashtable of parameters (not used yet).
* @param descriptions Description that will be displayed for the new resource.
* @returns The vectors names and values are filled with the information found in the workplace.ini.
* @return the number of the preselected item, -1 if none preselected
* @exception Throws CmsException if something goes wrong.
*/
public int getResources(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Vector descriptions, Hashtable parameters) throws CmsException {
I_CmsSession session = cms.getRequestContext().getSession(true);
String filename = (String)session.getValue(C_PARA_FILE);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
suffix = suffix.toLowerCase(); // file extension of filename
// read the known file extensions from the database
Hashtable extensions = cms.readFileExtensions();
String resType = new String();
if(extensions != null) {
resType = (String)extensions.get(suffix);
}
if(resType == null) {
resType = "";
}
int ret = 0;
// Check if the list of available resources is not yet loaded from the workplace.ini
if(m_names == null || m_values == null) {
m_names = new Vector();
m_values = new Vector();
CmsXmlWpConfigFile configFile = new CmsXmlWpConfigFile(cms);
configFile.getWorkplaceIniData(m_names, m_values, "RESOURCETYPES", "RESOURCE");
}
// Check if the temportary name and value vectors are not initialized, create
// them if nescessary.
if(names == null) {
names = new Vector();
}
if(values == null) {
values = new Vector();
}
if(descriptions == null) {
descriptions = new Vector();
}
// OK. Now m_names and m_values contain all available
// resource information.
// Loop through the vectors and fill the result vectors.
int numViews = m_names.size();
for(int i = 0;i < numViews;i++) {
String loopValue = (String)m_values.elementAt(i);
String loopName = (String)m_names.elementAt(i);
values.addElement(loopValue);
names.addElement("file_" + loopName);
String descr;
if(lang != null) {
descr = lang.getLanguageValue("fileicon." + loopName);
}
else {
descr = loopName;
}
descriptions.addElement(descr);
if(resType.equals(loopName)) {
// known file extension
ret = i;
}
}
return ret;
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
} |
package org.ligboy.selectphoto;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.File;
import java.io.IOException;
/**
* @author Ligboy.Liu ligboy@gmail.com.
*/
final class ContextUtil {
/**
* Android data cache
*
* @param context Context
* @param prefix .3.
* @param suffix .
* @param subDirectory nullcache
* @return
*/
@Nullable
public static File createTempFile(@NonNull final Context context, @NonNull String prefix,
@Nullable String suffix, @Nullable String subDirectory) {
File tempFile = null;
File cacheDerectory = null;
File outputDir = null;
File externalCacheDir = context.getExternalCacheDir();
//WRITE_EXTERNAL_STORAGE
if (externalCacheDir != null && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
|| context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
&& externalCacheDir.canWrite()) {
cacheDerectory = externalCacheDir;
} else {
cacheDerectory = context.getCacheDir();
}
if (!TextUtils.isEmpty(subDirectory)) {
outputDir = new File(cacheDerectory, subDirectory);
} else {
outputDir = cacheDerectory;
}
if (outputDir != null
&& (outputDir.exists()
|| outputDir.mkdirs())) {
try {
tempFile = File.createTempFile(prefix, suffix, outputDir);
} catch (IOException ignored) {
}
}
return tempFile;
}
/**
* Android data cache
*
* @param context Context
* @param prefix .3.
* @param suffix .
* @return
*/
@Nullable
public static File createTempFile(@NonNull final Context context, @NonNull String prefix,
@Nullable String suffix) {
return createTempFile(context, prefix, suffix, null);
}
} |
package org.openqa.selenium;
import java.util.List;
import static org.openqa.selenium.Ignore.Driver.IPHONE;
import static org.openqa.selenium.Ignore.Driver.SELENESE;
@Ignore({IPHONE, SELENESE})
public class ElementEqualityTest extends AbstractDriverTestCase {
public void testElementEqualityShouldWork() {
driver.get(pages.simpleTestPage);
WebElement body = driver.findElement(By.tagName("body"));
WebElement xbody = driver.findElement(By.xpath("//body"));
assertEquals(body, xbody);
}
public void testElementInequalityShouldWork() {
driver.get(pages.simpleTestPage);
List<WebElement> ps = driver.findElements(By.tagName("p"));
assertFalse(ps.get(0).equals(ps.get(1)));
}
public void testFindElementHashCodeShouldMatchEquality() {
driver.get(pages.simpleTestPage);
WebElement body = driver.findElement(By.tagName("body"));
WebElement xbody = driver.findElement(By.xpath("//body"));
assertEquals(body.hashCode(), xbody.hashCode());
}
public void testFindElementsHashCodeShouldMatchEquality() {
driver.get(pages.simpleTestPage);
List<WebElement> body = driver.findElements(By.tagName("body"));
List<WebElement> xbody = driver.findElements(By.xpath("//body"));
assertEquals(body.get(0).hashCode(), xbody.get(0).hashCode());
}
} |
package com.wrapp.android.webimage;
import android.graphics.Bitmap;
import java.util.*;
public abstract class TaskQueueThread extends Thread {
private static final long SHUTDOWN_TIMEOUT_IN_MS = 100;
private final Queue<ImageRequest> pendingRequests;
private boolean isRunning;
protected abstract Bitmap processRequest(ImageRequest request);
public TaskQueueThread(final String taskName) {
super(taskName);
pendingRequests = new LinkedList<ImageRequest>();
}
@Override
public void run() {
LogWrapper.logMessage("Starting up task " + getName());
ImageRequest request;
isRunning = true;
while(isRunning) {
synchronized(pendingRequests) {
while(pendingRequests.isEmpty() && isRunning) {
try {
pendingRequests.wait();
}
catch(InterruptedException e) {
isRunning = false;
break;
}
}
request = getNextRequest(pendingRequests);
}
if(request != null && request.listener != null) {
try {
Bitmap bitmap = processRequest(request);
if(pruneDuplicateRequests(request, pendingRequests)) {
if(bitmap != null) {
request.listener.onBitmapLoaded(new RequestResponse(bitmap, request.imageUrl));
}
else {
request.listener.onBitmapLoadCancelled();
}
}
else {
request.listener.onBitmapLoadCancelled();
}
}
catch(Exception e) {
request.listener.onBitmapLoadError(e.getMessage());
}
}
}
LogWrapper.logMessage("Shutting down task " + getName());
}
@Override
public void interrupt() {
super.interrupt();
isRunning = false;
}
public void addTask(ImageRequest request) {
synchronized(pendingRequests) {
pendingRequests.add(request);
pendingRequests.notifyAll();
}
}
private ImageRequest getNextRequest(Queue<ImageRequest> requestQueue) {
// Pop the first element from the pending request queue
ImageRequest request = requestQueue.poll();
// Go through the list of pending requests, pruning duplicate requests and using the latest URL
// requested by a particular listener. It is quite common that a listener will request multiple
// URL's, especially when a ListView is scrolling quickly.
Iterator requestIterator = requestQueue.iterator();
while(requestIterator.hasNext()) {
ImageRequest checkRequest = (ImageRequest)requestIterator.next();
if(request.listener.equals(checkRequest.listener)) {
if(request.imageUrl.equals(checkRequest.imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters.
request.listener.onBitmapLoadCancelled();
requestIterator.remove();
}
else {
// If this request in the queue was made by the same listener but is for a new URL,
// then use that request instead and remove it from the queue.
request.listener.onBitmapLoadCancelled();
request = checkRequest;
requestIterator.remove();
}
}
}
return request;
}
private boolean pruneDuplicateRequests(ImageRequest finishedRequest, Queue<ImageRequest> requestQueue) {
for(ImageRequest checkRequest : requestQueue) {
if(finishedRequest.listener.equals(checkRequest.listener) &&
!finishedRequest.imageUrl.equals(checkRequest.imageUrl)) {
return false;
}
}
return true;
}
public void cancelAllRequests() {
synchronized(pendingRequests) {
for(ImageRequest request : pendingRequests) {
request.listener.onBitmapLoadCancelled();
request.listener = null;
}
pendingRequests.clear();
}
}
public void shutdown() {
try {
interrupt();
join(SHUTDOWN_TIMEOUT_IN_MS);
}
catch(InterruptedException e) {
LogWrapper.logException(e);
}
}
} |
package be.fedict.dcat.scrapers;
import be.fedict.dcat.helpers.Storage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.dom4j.Node;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.vocabulary.DCAT;
/**
* Scraper for the Data Store Brussels portal
*
* @author Bart Hanssens
*/
public class GeonetBrussels extends GeonetGmd {
private final static String LANDING = "http://datastore.brussels/geonetwork/srv/eng/catalog.search#/metadata/";
/*
@Override
protected String mapLanguage(String lang) {
switch(lang) {
case "nl": return "DUT";
case "fr": return "FRE";
case "en": return "ENG";
}
return "";
}
*/
@Override
protected void generateDataset(IRI dataset, String id, Storage store, Node node)
throws MalformedURLException {
super.generateDataset(dataset, id, store, node);
store.add(dataset, DCAT.LANDING_PAGE, store.getURI(LANDING + id));
}
public GeonetBrussels(File caching, File storage, URL base) {
super(caching, storage, base);
setName("brussels");
}
} |
package org.helioviewer.jhv.camera;
import java.awt.Point;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.math.GL3DMat4d;
import org.helioviewer.base.math.GL3DQuatd;
import org.helioviewer.base.math.GL3DVec2d;
import org.helioviewer.base.math.GL3DVec3d;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import com.jogamp.opengl.GL2;
public abstract class GL3DCamera {
public static final double MAX_DISTANCE = -Constants.SunMeanDistanceToEarth * 1.8;
public static final double MIN_DISTANCE = -Constants.SunRadius * 1.2;
public static final double INITFOV = (48. / 60.) * Math.PI / 180.;
public static final double MIN_FOV = INITFOV * 0.02;
public static final double MAX_FOV = INITFOV * 10;
private final double clipNear = Constants.SunRadius * 3;
private final double clipFar = Constants.SunRadius * 10000.;
private double fov = INITFOV;
private double aspect = 0.0;
private double previousAspect = -1.0;
private GL3DMat4d cameraTransformation;
protected GL3DQuatd rotation;
protected GL3DVec3d translation;
protected GL3DQuatd currentDragRotation;
protected GL3DQuatd localRotation;
private long timeDelay;
protected long time;
private boolean trackingMode;
public GL3DMat4d orthoMatrixInverse = GL3DMat4d.identity();
private double cameraWidth = 1.;
private double previousCameraWidth = -1;
private double cameraWidthTimesAspect;
private double FOVangleToDraw;
protected static final double DEFAULT_CAMERA_DISTANCE = Constants.SunMeanDistanceToEarth / Constants.SunRadiusInMeter;
private final GL3DTrackballRotationInteraction rotationInteraction;
private final GL3DPanInteraction panInteraction;
private final GL3DZoomBoxInteraction zoomBoxInteraction;
protected GL3DInteraction currentInteraction;
public GL3DCamera() {
this.cameraTransformation = GL3DMat4d.identity();
this.rotation = new GL3DQuatd();
this.currentDragRotation = new GL3DQuatd();
this.localRotation = new GL3DQuatd();
this.translation = new GL3DVec3d();
this.resetFOV();
this.rotationInteraction = new GL3DTrackballRotationInteraction(this);
this.panInteraction = new GL3DPanInteraction(this);
this.zoomBoxInteraction = new GL3DZoomBoxInteraction(this);
this.currentInteraction = this.rotationInteraction;
}
public void reset() {
this.resetFOV();
this.translation = new GL3DVec3d(0, 0, this.translation.z);
this.currentDragRotation.clear();
this.currentInteraction.reset(this);
}
private void resetFOV() {
this.fov = INITFOV;
}
/**
* This method is called when the camera changes and should copy the
* required settings of the preceding camera objects.
*
* @param precedingCamera
*/
public void activate(GL3DCamera precedingCamera) {
if (precedingCamera != null) {
this.rotation = precedingCamera.getRotation().copy();
this.translation = precedingCamera.translation.copy();
this.FOVangleToDraw = precedingCamera.getFOVAngleToDraw();
this.updateCameraTransformation();
if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getRotateInteraction())) {
this.setCurrentInteraction(this.getRotateInteraction());
} else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getPanInteraction())) {
this.setCurrentInteraction(this.getPanInteraction());
} else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getZoomInteraction())) {
this.setCurrentInteraction(this.getZoomInteraction());
}
} else {
Log.debug("GL3DCamera: No Preceding Camera, resetting Camera");
this.reset();
}
}
public double getFOVAngleToDraw() {
return this.FOVangleToDraw;
}
protected void setZTranslation(double z) {
double truncatedz = Math.min(MIN_DISTANCE, Math.max(MAX_DISTANCE, z));
this.translation.z = truncatedz;
}
public void setPanning(double x, double y) {
this.translation.x = x;
this.translation.y = y;
}
public GL3DVec3d getTranslation() {
return this.translation;
}
public GL3DMat4d getCameraTransformation() {
return this.cameraTransformation;
}
public double getZTranslation() {
return this.translation.z;
}
public GL3DQuatd getLocalRotation() {
return this.localRotation;
}
public GL3DQuatd getRotation() {
return this.rotation;
}
public void resetCurrentDragRotation() {
this.currentDragRotation.clear();
}
public void setLocalRotation(GL3DQuatd localRotation) {
this.localRotation = localRotation;
this.rotation.clear();
this.updateCameraTransformation();
}
public void rotateCurrentDragRotation(GL3DQuatd currentDragRotation) {
this.currentDragRotation.rotate(currentDragRotation);
this.rotation.clear();
this.updateCameraTransformation();
}
public void applyPerspective(GL2 gl) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
this.aspect = Displayer.getViewportWidth() / (double) Displayer.getViewportHeight();
cameraWidth = -translation.z * Math.tan(fov / 2.);
if (cameraWidth == 0.)
cameraWidth = 1.;
cameraWidthTimesAspect = cameraWidth * aspect;
gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
if (cameraWidth == previousCameraWidth && aspect == previousAspect) {
return;
}
ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth);
previousCameraWidth = cameraWidth;
previousAspect = aspect;
//orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
orthoMatrixInverse = GL3DMat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
}
public void resumePerspective(GL2 gl) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glMatrixMode(GL2.GL_MODELVIEW);
}
public GL3DVec3d getVectorFromSphereOrPlane(GL3DVec2d normalizedScreenpos, GL3DQuatd cameraDifferenceRotation) {
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
GL3DVec3d hitPoint;
GL3DVec3d rotatedHitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2));
rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint);
if (rotatedHitPoint.z > 0.) {
return rotatedHitPoint;
}
}
GL3DVec3d altnormal = cameraDifferenceRotation.rotateVector(GL3DVec3d.ZAxis);
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
hitPoint = new GL3DVec3d(up1x, up1y, zvalue);
rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint);
return rotatedHitPoint;
}
public GL3DVec3d getVectorFromSphere(Point viewportCoordinates) {
GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5));
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
GL3DVec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1.) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2));
hitPoint = this.localRotation.rotateInverseVector(this.currentDragRotation.rotateInverseVector(hitPoint));
return hitPoint;
}
return null;
}
public GL3DVec3d getVectorFromSphereAlt(Point viewportCoordinates) {
GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5));
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
GL3DVec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1.) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2));
hitPoint = this.currentDragRotation.rotateInverseVector(hitPoint);
return hitPoint;
}
return null;
}
public GL3DVec3d getVectorFromSphereTrackball(Point viewportCoordinates) {
GL3DVec2d normalizedScreenpos = new GL3DVec2d(2. * (viewportCoordinates.getX() / Displayer.getViewportWidth() - 0.5), -2. * (viewportCoordinates.getY() / Displayer.getViewportHeight() - 0.5));
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
GL3DVec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= Constants.SunRadius2 / 2.) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(Constants.SunRadius2 - radius2));
} else {
hitPoint = new GL3DVec3d(up1x, up1y, Constants.SunRadius2 / (2. * Math.sqrt(radius2)));
}
GL3DMat4d roti = this.getCurrentDragRotation().toMatrix().inverse();
hitPoint = roti.multiply(hitPoint);
return hitPoint;
}
/**
* Updates the camera transformation by applying the rotation and
* translation information.
*/
public void updateCameraTransformation() {
this.rotation = this.currentDragRotation.copy();
this.rotation.rotate(this.localRotation);
cameraTransformation = this.rotation.toMatrix().translate(this.translation);
}
public GL3DMat4d getRotationMatrix() {
return this.getRotation().toMatrix();
}
public void applyCamera(GL2 gl) {
gl.glMultMatrixd(cameraTransformation.m, 0);
}
public void drawCamera(GL2 gl) {
getCurrentInteraction().drawInteractionFeedback(gl, this);
}
public double getCameraFOV() {
return this.fov;
}
public double setCameraFOV(double fov) {
if (fov < MIN_FOV) {
this.fov = MIN_FOV;
} else if (fov > MAX_FOV) {
this.fov = MAX_FOV;
} else {
this.fov = fov;
}
return this.fov;
}
public final double getClipNear() {
return clipNear;
}
public final double getClipFar() {
return clipFar;
}
public double getAspect() {
return aspect;
}
@Override
public String toString() {
return getName();
}
public void setTimeDelay(long timeDelay) {
this.timeDelay = timeDelay;
}
public long getTimeDelay() {
return this.timeDelay;
}
public GL3DQuatd getCurrentDragRotation() {
return this.currentDragRotation;
}
public void setTrackingMode(boolean trackingMode) {
this.trackingMode = trackingMode;
}
public boolean getTrackingMode() {
return this.trackingMode;
}
public void deactivate() {
}
public void setDefaultFOV() {
this.fov = INITFOV;
}
public double getCameraWidth() {
return cameraWidth;
}
public void zoom(int wr) {
this.setCameraFOV(this.fov + 0.0005 * wr);
Displayer.render();
}
public void setFOVangleDegrees(double fovAngle) {
this.FOVangleToDraw = fovAngle * Math.PI / 180.0;
}
public GL3DInteraction getPanInteraction() {
return this.panInteraction;
}
public GL3DInteraction getRotateInteraction() {
return this.rotationInteraction;
}
public GL3DInteraction getCurrentInteraction() {
return this.currentInteraction;
}
public void setCurrentInteraction(GL3DInteraction currentInteraction) {
this.currentInteraction = currentInteraction;
}
public GL3DInteraction getZoomInteraction() {
return this.zoomBoxInteraction;
}
public String getName() {
return "Solar Rotation Tracking Camera";
}
public abstract GL3DCameraOptionPanel getOptionPanel();
} |
package me.mattlogan.library;
import android.animation.Animator;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.util.EmptyStackException;
import java.util.Stack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
@RunWith(MockitoJUnitRunner.class)
public class ViewStackTest {
@Mock ViewStackDelegate delegate;
@Mock ViewGroup container;
ViewStack viewStack;
@Before
public void setup() {
initMocks(this);
viewStack = ViewStack.create(container, delegate);
}
@Test
public void createWithNullContainer() {
try {
ViewStack.create(null, delegate);
fail();
} catch (NullPointerException e) {
assertEquals("container == null", e.getMessage());
}
}
@Test
public void createWithNullDelegate() {
try {
ViewStack.create(container, null);
fail();
} catch (NullPointerException e) {
assertEquals("delegate == null", e.getMessage());
}
}
@Test
public void saveToBundleWithNullBundle() {
try {
viewStack.saveToBundle(null, "tag");
fail();
} catch (NullPointerException e) {
assertEquals("bundle == null", e.getMessage());
}
}
@Test
public void saveToBundleWithNullTag() {
Bundle bundle = mock(Bundle.class);
try {
viewStack.saveToBundle(bundle, null);
fail();
} catch (IllegalArgumentException e) {
assertEquals("tag is empty", e.getMessage());
}
}
@Test
public void saveToBundleWithEmptyTag() {
Bundle bundle = mock(Bundle.class);
try {
viewStack.saveToBundle(bundle, "");
fail();
} catch (IllegalArgumentException e) {
assertEquals("tag is empty", e.getMessage());
}
}
@Test
public void saveToBundle() {
viewStack.push(newMockViewFactory());
Bundle bundle = mock(Bundle.class);
viewStack.saveToBundle(bundle, "tag");
verify(bundle).putSerializable(eq("tag"), isA(Stack.class));
}
@Test
public void rebuildFromBundleWithNullBundle() {
try {
viewStack.rebuildFromBundle(null, "tag");
fail();
} catch (NullPointerException e) {
assertEquals("bundle == null", e.getMessage());
}
}
@Test
public void rebuildFromBundleWithNullTag() {
Bundle bundle = mock(Bundle.class);
try {
viewStack.rebuildFromBundle(bundle, null);
fail();
} catch (IllegalArgumentException e) {
assertEquals("tag is empty", e.getMessage());
}
}
@Test
public void rebuildFromBundleWithEmptyTag() {
Bundle bundle = mock(Bundle.class);
try {
viewStack.rebuildFromBundle(bundle, "");
fail();
} catch (IllegalArgumentException e) {
assertEquals("tag is empty", e.getMessage());
}
}
@Test
public void rebuildFromBundleWithNullStack() {
Bundle bundle = mock(Bundle.class);
try {
viewStack.rebuildFromBundle(bundle, "tag");
fail();
} catch (NullPointerException e) {
assertEquals("Bundle doesn't contain any ViewStack state.", e.getMessage());
}
}
@Test
public void rebuildFromBundle() {
Stack<ViewFactory> stack = new Stack<>();
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
ViewFactory bottom = mock(ViewFactory.class);
View bottomView = mock(View.class);
when(bottom.createView(context, container)).thenReturn(bottomView);
when(bottomView.getViewTreeObserver()).thenReturn(mock(ViewTreeObserver.class));
stack.push(bottom);
ViewFactory top = mock(ViewFactory.class);
View topView = mock(View.class);
when(top.createView(context, container)).thenReturn(topView);
when(topView.getViewTreeObserver()).thenReturn(mock(ViewTreeObserver.class));
stack.push(top);
// First time return 1, second time return 2
when(container.getChildCount()).thenAnswer(new Answer() {
int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count == 0) {
count++;
return 1;
}
return 2;
}
});
when(container.getChildAt(0)).thenReturn(bottomView);
Bundle bundle = mock(Bundle.class);
when(bundle.getSerializable("tag")).thenReturn(stack);
viewStack.rebuildFromBundle(bundle, "tag");
assertEquals(2, viewStack.size());
verify(container).addView(bottomView);
verify(container).addView(topView);
verify(bottomView).setVisibility(View.GONE);
}
@Test
public void pushWithNullViewFactory() {
try {
viewStack.push(null);
fail();
} catch (NullPointerException e) {
assertEquals("viewFactory == null", e.getMessage());
}
}
@Test
public void pushFirstTime() {
// Applies to both bottom and top
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
// Bottom
View view = mock(View.class);
ViewFactory viewFactory = mock(ViewFactory.class);
when(viewFactory.createView(context, container)).thenReturn(view);
when(container.getChildCount()).thenReturn(1);
viewStack.push(viewFactory);
assertEquals(1, viewStack.size());
verify(container).addView(view);
}
@Test
public void pushSecondTime() {
// Applies to both bottom and top
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
// Bottom
View bottomView = mock(View.class);
ViewFactory bottomViewFactory = mock(ViewFactory.class);
when(bottomViewFactory.createView(context, container)).thenReturn(bottomView);
viewStack.push(bottomViewFactory);
// Top
View topView = mock(View.class);
ViewFactory topViewFactory = mock(ViewFactory.class);
when(topViewFactory.createView(context, container)).thenReturn(topView);
when(container.getChildCount()).thenReturn(2);
when(container.getChildAt(0)).thenReturn(bottomView);
viewStack.push(topViewFactory);
assertEquals(2, viewStack.size());
verify(container).addView(bottomView);
verify(container).addView(topView);
verify(bottomView).setVisibility(View.GONE);
}
@Test
public void pushWithAnimationWithNullViewFactory() {
try {
viewStack.pushWithAnimation(null, mock(AnimatorFactory.class));
fail();
} catch (NullPointerException e) {
assertEquals("viewFactory == null", e.getMessage());
}
}
@Test
public void pushWithAnimationWithNullAnimatorFactory() {
try {
viewStack.pushWithAnimation(mock(ViewFactory.class), null);
fail();
} catch (NullPointerException e) {
assertEquals("animatorFactory == null", e.getMessage());
}
}
@Test
public void pushWithAnimationFirstTime() {
// Applies to both bottom and top
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
// Top
View view = mock(View.class);
ViewFactory viewFactory = mock(ViewFactory.class);
ViewTreeObserver observer = mock(ViewTreeObserver.class);
when(viewFactory.createView(context, container)).thenReturn(view);
when(view.getViewTreeObserver()).thenReturn(observer);
AnimatorFactory animatorFactory = mock(AnimatorFactory.class);
Animator animator = mock(Animator.class);
when(animatorFactory.createAnimator(view)).thenReturn(animator);
ViewFactory result = viewStack.pushWithAnimation(viewFactory, animatorFactory);
assertSame(viewFactory, result);
assertEquals(1, viewStack.size());
verify(container).addView(view);
ArgumentCaptor<FirstLayoutListener> firstLayoutListenerArgument =
ArgumentCaptor.forClass(FirstLayoutListener.class);
verify(observer).addOnGlobalLayoutListener(firstLayoutListenerArgument.capture());
firstLayoutListenerArgument.getValue().onFirstLayout(view);
ArgumentCaptor<Animator.AnimatorListener> animatorListenerArgument =
ArgumentCaptor.forClass(Animator.AnimatorListener.class);
verify(animator).addListener(animatorListenerArgument.capture());
verify(animator).start();
when(container.getChildCount()).thenReturn(1);
when(container.getChildAt(0)).thenReturn(view);
animatorListenerArgument.getValue().onAnimationEnd(animator);
verify(container).getChildCount();
verify(view, times(0)).setVisibility(View.GONE);
}
@Test
public void pushWithAnimationSecondTime() {
// Applies to both bottom and top
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
// Bottom
View bottomView = mock(View.class);
ViewFactory bottomViewFactory = mock(ViewFactory.class);
ViewTreeObserver bottomObserver = mock(ViewTreeObserver.class);
when(bottomViewFactory.createView(context, container)).thenReturn(bottomView);
when(bottomView.getViewTreeObserver()).thenReturn(bottomObserver);
viewStack.push(bottomViewFactory);
// Top
View topView = mock(View.class);
ViewFactory topViewFactory = mock(ViewFactory.class);
ViewTreeObserver topObserver = mock(ViewTreeObserver.class);
when(topViewFactory.createView(context, container)).thenReturn(topView);
when(topView.getViewTreeObserver()).thenReturn(topObserver);
AnimatorFactory animatorFactory = mock(AnimatorFactory.class);
Animator animator = mock(Animator.class);
when(animatorFactory.createAnimator(topView)).thenReturn(animator);
ViewFactory result = viewStack.pushWithAnimation(topViewFactory, animatorFactory);
assertSame(topViewFactory, result);
assertEquals(2, viewStack.size());
verify(container).addView(bottomView);
verify(container).addView(topView);
ArgumentCaptor<FirstLayoutListener> firstLayoutListenerArgument =
ArgumentCaptor.forClass(FirstLayoutListener.class);
verify(topObserver).addOnGlobalLayoutListener(firstLayoutListenerArgument.capture());
firstLayoutListenerArgument.getValue().onFirstLayout(topView);
ArgumentCaptor<Animator.AnimatorListener> animatorListenerArgument =
ArgumentCaptor.forClass(Animator.AnimatorListener.class);
verify(animator).addListener(animatorListenerArgument.capture());
verify(animator).start();
when(container.getChildCount()).thenReturn(2);
when(container.getChildAt(0)).thenReturn(bottomView);
animatorListenerArgument.getValue().onAnimationEnd(animator);
verify(bottomView).setVisibility(View.GONE);
}
@Test
public void popWithSizeZero() {
try {
viewStack.pop();
fail();
} catch (EmptyStackException e) {
assertNotNull(e);
}
}
@Test
public void popWithSizeOne() {
viewStack.push(newMockViewFactory());
ViewFactory result = viewStack.pop();
assertNull(result);
verify(delegate).finishStack();
}
@Test
public void popWithSizeMoreThanOne() {
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
ViewFactory bottomViewFactory = mock(ViewFactory.class);
View bottomView = mock(View.class);
when(bottomViewFactory.createView(context, container)).thenReturn(bottomView);
viewStack.push(bottomViewFactory);
ViewFactory topViewFactory = mock(ViewFactory.class);
View topView = mock(View.class);
when(topViewFactory.createView(context, container)).thenReturn(topView);
viewStack.push(topViewFactory);
when(container.getChildCount()).thenReturn(2);
when(container.getChildAt(0)).thenReturn(bottomView);
when(container.getChildAt(1)).thenReturn(topView);
ViewFactory result = viewStack.pop();
assertSame(topViewFactory, result);
verify(bottomView).setVisibility(View.VISIBLE);
verify(container).removeView(topView);
}
@Test
public void popWithAnimation() {
Context context = mock(Context.class);
when(container.getContext()).thenReturn(context);
ViewFactory bottomViewFactory = mock(ViewFactory.class);
View bottomView = mock(View.class);
when(bottomViewFactory.createView(context, container)).thenReturn(bottomView);
viewStack.push(bottomViewFactory);
ViewFactory topViewFactory = mock(ViewFactory.class);
View topView = mock(View.class);
when(topViewFactory.createView(context, container)).thenReturn(topView);
viewStack.push(topViewFactory);
when(container.getChildCount()).thenReturn(2);
when(container.getChildAt(0)).thenReturn(bottomView);
when(container.getChildAt(1)).thenReturn(topView);
AnimatorFactory animatorFactory = mock(AnimatorFactory.class);
Animator animator = mock(Animator.class);
when(animatorFactory.createAnimator(topView)).thenReturn(animator);
ViewFactory result = viewStack.popWithAnimation(animatorFactory);
assertSame(topViewFactory, result);
verify(bottomView).setVisibility(View.VISIBLE);
ArgumentCaptor<Animator.AnimatorListener> animatorListenerArgument =
ArgumentCaptor.forClass(Animator.AnimatorListener.class);
verify(animator).addListener(animatorListenerArgument.capture());
verify(animator).start();
animatorListenerArgument.getValue().onAnimationEnd(animator);
verify(container).removeView(topView);
}
@Test
public void peekWithSizeZero() {
try {
viewStack.peek();
fail();
} catch (EmptyStackException e) {
assertNotNull(e);
}
}
@Test
public void peek() {
viewStack.push(newMockViewFactory());
ViewFactory top = newMockViewFactory();
viewStack.push(top);
ViewFactory result = viewStack.peek();
assertSame(top, result);
}
@Test
public void size() {
viewStack.push(newMockViewFactory());
viewStack.push(newMockViewFactory());
assertEquals(2, viewStack.size());
}
@Test
public void clear() {
viewStack.push(newMockViewFactory());
viewStack.push(newMockViewFactory());
reset(container);
viewStack.clear();
verify(container).removeAllViews();
verifyNoMoreInteractions(container);
}
private ViewFactory newMockViewFactory() {
Context context = mock(Context.class);
View view = mock(View.class);
ViewFactory viewFactory = mock(ViewFactory.class);
ViewTreeObserver observer = mock(ViewTreeObserver.class);
when(container.getContext()).thenReturn(context);
when(viewFactory.createView(context, container)).thenReturn(view);
when(view.getViewTreeObserver()).thenReturn(observer);
return viewFactory;
}
} |
package me.lcw.jil.awt;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import me.lcw.jil.Color;
import me.lcw.jil.BaseImage;
import me.lcw.jil.ImageException;
import me.lcw.jil.JilImage;
import me.lcw.jil.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AWTDrawTests {
public BaseImage img;
public BaseImage img200;
public BaseImage img400;
public BaseImage img400a;
public String endHash;
@Before
public void start() throws ImageException, IOException {
img = AWTImage.fromBaseImage(TestUtils.RGBAImageGenerator());
img200 = AWTImage.create(BaseImage.MODE.RGB, 200, 200);
img400 = AWTImage.create(BaseImage.MODE.RGB, 400, 400);
img400a = AWTImage.create(BaseImage.MODE.RGBA, 400, 400);
}
@After
public void end() {
}
@Test
public void floodFillTest1() throws Exception {
BaseImage img = AWTImage.create(BaseImage.MODE.RGB, 200, 200);
img.fillImageWithColor(Color.WHITE);
img.draw().drawRect(30, 30, 140, 140, Color.RED, 1, true);
img.draw().drawRect(80, 80, 80, 80, Color.GREEN, 1, true);
assertEquals("63a715ea35d3509ade22d5c69f7a95077b04130e6384303f8ccd83c2578584a5", TestUtils.hashByteArray(img.getArray()));
//Doing this on red should not work
img.draw().floodFill(78, 78, Color.BLUE, Color.RED, false);
assertEquals("63a715ea35d3509ade22d5c69f7a95077b04130e6384303f8ccd83c2578584a5", TestUtils.hashByteArray(img.getArray()));
//This changes the outside
img.draw().floodFill(0, 0, Color.BLUE, Color.RED, false);
assertEquals("aa260abcfbe77d4a98d72c638771db8b691670510d508458ce36fabc41200ffa", TestUtils.hashByteArray(img.getArray()));
//Changes the inside
img.draw().floodFill(81, 81, Color.BLUE, Color.RED, false);
assertEquals("1dee5a3950bcd1c313cc8f2b6d5e62c3a5415230236dfb33f0c8140e7b9df2ff", TestUtils.hashByteArray(img.getArray()));
//Change inside back
img.draw().floodFill(81, 81, Color.GREEN, Color.RED, false);
assertEquals("aa260abcfbe77d4a98d72c638771db8b691670510d508458ce36fabc41200ffa", TestUtils.hashByteArray(img.getArray()));
//Change outside back to white
img.draw().floodFill(0, 0, Color.WHITE, null, false);
assertEquals("63a715ea35d3509ade22d5c69f7a95077b04130e6384303f8ccd83c2578584a5", TestUtils.hashByteArray(img.getArray()));
//System.out.println(TestUtils.hashByteArray(img.getArray()));
//img.save("/tmp/test.png");
}
@Test
public void floodFillTest2() throws Exception {
BaseImage img = JilImage.create(BaseImage.MODE.RGBA, 200, 200);
img.fillImageWithColor(new Color(Color.MAX_BYTE, Color.MAX_BYTE, Color.MAX_BYTE, (byte)200));
img.draw().drawRect(30, 30, 140, 140, Color.RED, 1, true);
img.draw().drawRect(80, 80, 80, 80, Color.GREEN, 1, true);
assertEquals("e15dd57053d023c607ba264249b17897c6c918e0205a20edc1e5e245b330811e", TestUtils.hashByteArray(img.getArray()));
//Doing this on red should not work
img.draw().floodFill(78, 78, Color.BLUE, Color.RED, true);
assertEquals("e15dd57053d023c607ba264249b17897c6c918e0205a20edc1e5e245b330811e", TestUtils.hashByteArray(img.getArray()));
//This changes the outside
img.draw().floodFill(0, 0, Color.BLUE, Color.RED, true);
assertEquals("8a0e9327bbe083a1fbaad4f29b8df3aad0c186a11669daca5bb19e453a341a89", TestUtils.hashByteArray(img.getArray()));
//Changes the inside
img.draw().floodFill(81, 81, Color.BLUE, Color.RED, true);
assertEquals("bcac8631c9b7f3cea4053e59ae24c7640f546a0e42f38d200766ec72c742d3d8", TestUtils.hashByteArray(img.getArray()));
//Change inside back
img.draw().floodFill(81, 81, Color.GREEN, Color.RED, true);
assertEquals("8a0e9327bbe083a1fbaad4f29b8df3aad0c186a11669daca5bb19e453a341a89", TestUtils.hashByteArray(img.getArray()));
//Change outside back to white
img.draw().floodFill(0, 0, Color.WHITE, null, true);
assertEquals("e15dd57053d023c607ba264249b17897c6c918e0205a20edc1e5e245b330811e", TestUtils.hashByteArray(img.getArray()));
//System.out.println(TestUtils.hashByteArray(img.getArray()));
//img.save("/tmp/test.png");
}
@Test
public void rectTest() throws ImageException, IOException, NoSuchAlgorithmException {
img.draw().drawRect(10, 10, 100, 10, Color.GREEN, 5, false);
assertEquals("e2d46933ac330334a92995eca64f0db70e7966c7d2f38a7420a0443a38f395ff", TestUtils.hashByteArray(img.getArray()));
}
@Test
public void fillColorTest() throws ImageException, IOException, NoSuchAlgorithmException {
img200.draw().drawRect(10, 10, 10, 10, Color.GREY, 1, true);
img200.draw().drawRect(50, 50, 10, 10, Color.WHITE, 1, false);
img200.draw().fillColor(0, 0, Color.RED);
assertEquals("7b3b3952bf8e4af176dfddd92c2f275c023572e9751629a3de5b7c1a9698a991", TestUtils.hashByteArray(img200.getArray()));
}
@Test
public void circleTest() throws ImageException, IOException, NoSuchAlgorithmException {
Color c;
c = new Color((byte)100,(byte)100,(byte)100);
img400.draw().fillColor(0, 0, c);
//Center Circle no fill
c = new Color((byte)255,(byte)255,(byte)255);
img400.draw().drawCircle(200, 200, 200, c, 1, false);
//Manually fill it
c = new Color((byte)145,(byte)28,(byte)222);
img400.draw().fillColor(200, 200, c);
//Draw at 0,0 and have it fill
c = new Color((byte)145,(byte)28,(byte)22);
img400.draw().drawCircle(0, 0, 200, c, 1, true);
//Draw at 400x400 and no fill 1px wide
c = new Color((byte)245,(byte)228,(byte)22);
img400.draw().drawCircle(400, 400, 200, c, 1, false);
//assertEquals("c8da98f88b48090892577530f04093ac6cb14f46c1ea9ab7d1a61f6ba92eb31a", TestUtils.hashByteArray(img400.getArray()));
}
@Test
public void lineTest() throws ImageException, IOException, NoSuchAlgorithmException {
Color c;
//grey canvas
c = new Color((byte)100,(byte)100,(byte)100);
img400.draw().fillColor(0, 0, c);
//Horizontal line all the way through
c = new Color((byte)200,(byte)12,(byte)100);
img400.draw().drawLine(-100, 200, 500, 200, c, 5, false);
//Vertical line all the way through
c = new Color((byte)142,(byte)114,(byte)176);
img400.draw().drawLine(200, -100, 200, 500, c, 5, false);
//left to right line all the way through
c = new Color((byte)44,(byte)214,(byte)55);
img400.draw().drawLine(-100, -100, 500, 500, c, 5, false);
//right to left line all the way through
c = new Color((byte)144,(byte)114,(byte)55);
img400.draw().drawLine( 500, -100, -100, 500, c, 5, false);
//System.out.println(TestUtils.hashByteArray(img400.getArray()));
assertEquals("afd9aa1ebd1fd64ede7cb78887cff1785fb454c3b4c2cf69f442f49469770160", TestUtils.hashByteArray(img400.getArray()));
}
@Test
public void lineTestWithAlpha() throws ImageException, IOException, NoSuchAlgorithmException {
Color c;
//grey canvas
c = new Color((byte)100,(byte)100,(byte)100);
img400a.draw().fillColor(0, 0, c);
//Horizontal line all the way through
c = new Color((byte)200,(byte)12,(byte)100, (byte)100);
img400a.draw().drawLine(-100, 200, 500, 200, c, 5, true);
//Vertical line all the way through
c = new Color((byte)142,(byte)114,(byte)176, (byte)100);
img400a.draw().drawLine(200, -100, 200, 500, c, 5, true);
//left to right line all the way through
c = new Color((byte)44,(byte)214,(byte)55, (byte)100);
img400a.draw().drawLine(-100, -100, 500, 500, c, 5, true);
//right to left line all the way through
c = new Color((byte)144,(byte)114,(byte)55, (byte)100);
//System.out.println(TestUtils.hashByteArray(img400a.getArray()));
assertEquals("95df8420fb458b5120f6be9e2e7cbda3c7f6d6baa70bd1b304a33ccdde71d5b2", TestUtils.hashByteArray(img400a.getArray()));
}
} |
package org.helioviewer.jhv.camera;
import java.awt.Point;
import java.util.Date;
import org.helioviewer.base.astronomy.Sun;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.math.GL3DMat4d;
import org.helioviewer.base.math.GL3DQuatd;
import org.helioviewer.base.math.GL3DVec2d;
import org.helioviewer.base.math.GL3DVec3d;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.viewmodel.metadata.MetaData;
import com.jogamp.opengl.GL2;
public abstract class GL3DCamera {
public static final double INITFOV = (48. / 60.) * Math.PI / 180.;
public static final double MIN_FOV = INITFOV * 0.02;
public static final double MAX_FOV = INITFOV * 30;
private final double clipNear = Sun.Radius * 3;
private final double clipFar = Sun.Radius * 10000;
private double fov = INITFOV;
private double previousAspect = -1.0;
private GL3DMat4d cameraTransformation;
private GL3DQuatd rotation;
private GL3DVec3d translation;
private final GL3DQuatd currentDragRotation;
protected GL3DQuatd localRotation;
private boolean trackingMode;
private GL3DMat4d orthoMatrixInverse = GL3DMat4d.identity();
private double cameraWidth = 1.;
private double previousCameraWidth = -1;
private double cameraWidthTimesAspect;
private double FOVangleToDraw;
private final GL3DTrackballRotationInteraction rotationInteraction;
private final GL3DPanInteraction panInteraction;
private final GL3DAnnotateInteraction annotateInteraction;
private GL3DInteraction currentInteraction;
public GL3DCamera() {
cameraTransformation = GL3DMat4d.identity();
rotation = new GL3DQuatd();
currentDragRotation = new GL3DQuatd();
localRotation = new GL3DQuatd();
translation = new GL3DVec3d();
fov = INITFOV;
rotationInteraction = new GL3DTrackballRotationInteraction(this);
panInteraction = new GL3DPanInteraction(this);
annotateInteraction = new GL3DAnnotateInteraction(this);
currentInteraction = rotationInteraction;
}
public void reset() {
translation = new GL3DVec3d(0, 0, translation.z);
currentDragRotation.clear();
currentInteraction.reset();
zoomToFit();
}
/**
* This method is called when the camera changes and should copy the
* required settings of the preceding camera objects.
*
* @param precedingCamera
*/
public void activate(GL3DCamera precedingCamera) {
if (precedingCamera != null) {
rotation = precedingCamera.rotation.copy();
translation = precedingCamera.translation.copy();
FOVangleToDraw = precedingCamera.getFOVAngleToDraw();
updateCameraTransformation();
updateCameraWidthAspect(precedingCamera.previousAspect);
GL3DInteraction precedingInteraction = precedingCamera.getCurrentInteraction();
if (precedingInteraction.equals(precedingCamera.getRotateInteraction())) {
setCurrentInteraction(getRotateInteraction());
} else if (precedingInteraction.equals(precedingCamera.getPanInteraction())) {
setCurrentInteraction(getPanInteraction());
} else if (precedingInteraction.equals(precedingCamera.getAnnotateInteraction())) {
setCurrentInteraction(getAnnotateInteraction());
}
} else {
Log.debug("GL3DCamera: No Preceding Camera, resetting Camera");
reset();
}
}
private GL3DQuatd saveRotation;
private GL3DQuatd saveLocalRotation;
private GL3DVec3d saveTranslation;
private GL3DMat4d saveTransformation;
public void push(Date date, MetaData m) {
if (!trackingMode) {
saveRotation = rotation.copy();
saveLocalRotation = localRotation.copy();
saveTranslation = translation.copy();
saveTransformation = cameraTransformation.copy();
updateRotation(date, m);
}
}
public void pop() {
if (!trackingMode) {
rotation = saveRotation;
localRotation = saveLocalRotation;
translation = saveTranslation;
cameraTransformation = saveTransformation;
}
}
public double getFOVAngleToDraw() {
return FOVangleToDraw;
}
public void setPanning(double x, double y) {
translation.x = x;
translation.y = y;
}
protected void setZTranslation(double z) {
translation.z = z;
updateCameraWidthAspect(previousAspect);
}
public double getZTranslation() {
return translation.z;
}
public GL3DVec3d getTranslation() {
return translation;
}
public GL3DQuatd getLocalRotation() {
return localRotation;
}
public void resetCurrentDragRotation() {
currentDragRotation.clear();
}
public void setLocalRotation(GL3DQuatd _localRotation) {
localRotation = _localRotation;
rotation.clear();
updateCameraTransformation();
}
public void rotateCurrentDragRotation(GL3DQuatd _currentDragRotation) {
currentDragRotation.rotate(currentDragRotation);
rotation.clear();
updateCameraTransformation();
}
// quantization bits per half width camera
private static final int quantFactor = 1 << 12;
public void updateCameraWidthAspect(double aspect) {
cameraWidth = -translation.z * Math.tan(fov / 2.);
if (cameraWidth == 0.)
cameraWidth = 1.;
cameraWidth = (long) (cameraWidth * quantFactor) / (double) quantFactor;
if (cameraWidth == previousCameraWidth && aspect == previousAspect) {
return;
}
previousCameraWidth = cameraWidth;
previousAspect = aspect;
cameraWidthTimesAspect = cameraWidth * aspect;
//orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
orthoMatrixInverse = GL3DMat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
if (this == Displayer.getViewport().getCamera()) {
ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth);
}
}
public GL3DMat4d getOrthoMatrixInverse() {
return orthoMatrixInverse.copy();
}
public void applyPerspective(GL2 gl) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
// applyCamera
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadMatrixd(cameraTransformation.m, 0);
}
public GL3DVec3d getVectorFromSphereOrPlane(GL3DVec2d normalizedScreenpos, GL3DQuatd cameraDifferenceRotation) {
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
GL3DVec3d hitPoint;
GL3DVec3d rotatedHitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2));
rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint);
if (rotatedHitPoint.z > 0.) {
return rotatedHitPoint;
}
}
GL3DVec3d altnormal = cameraDifferenceRotation.rotateVector(GL3DVec3d.ZAxis);
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
hitPoint = new GL3DVec3d(up1x, up1y, zvalue);
return cameraDifferenceRotation.rotateInverseVector(hitPoint);
}
private static double computeNormalizedX(Point viewportCoordinates) {
return +2. * ((viewportCoordinates.getX() - Displayer.getViewport().getOffsetX()) / Displayer.getViewport().getWidth() - 0.5);
}
private static double computeNormalizedY(Point viewportCoordinates) {
return -2. * ((viewportCoordinates.getY() - Displayer.getViewport().getOffsetY()) / Displayer.getViewport().getHeight() - 0.5);
}
private double computeUpX(Point viewportCoordinates) {
return computeNormalizedX(viewportCoordinates) * cameraWidthTimesAspect - translation.x;
}
private double computeUpY(Point viewportCoordinates) {
return computeNormalizedY(viewportCoordinates) * cameraWidth - translation.y;
}
public GL3DVec3d getVectorFromSphere(Point viewportCoordinates) {
GL3DVec3d hitPoint = getVectorFromSphereAlt(viewportCoordinates);
if (hitPoint != null) {
return localRotation.rotateInverseVector(hitPoint);
}
return null;
}
public GL3DVec3d getVectorFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
GL3DVec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1.) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2));
return currentDragRotation.rotateInverseVector(hitPoint);
}
return null;
}
public double getRadiusFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
return Math.sqrt(up1x * up1x + up1y * up1y);
}
public GL3DVec3d getVectorFromSphereTrackball(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
GL3DVec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= Sun.Radius2 / 2.) {
hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(Sun.Radius2 - radius2));
} else {
hitPoint = new GL3DVec3d(up1x, up1y, Sun.Radius2 / (2. * Math.sqrt(radius2)));
}
return currentDragRotation.rotateInverseVector(hitPoint);
}
public GL3DQuatd getCameraDifferenceRotationQuatd(GL3DQuatd rot) {
GL3DQuatd cameraDifferenceRotation = rotation.copy();
cameraDifferenceRotation.rotateWithConjugate(rot);
return cameraDifferenceRotation;
}
/**
* Updates the camera transformation by applying the rotation and
* translation information.
*/
public void updateCameraTransformation() {
rotation = currentDragRotation.copy();
rotation.rotate(localRotation);
cameraTransformation = rotation.toMatrix().translate(translation);
}
public double getCameraFOV() {
return fov;
}
public void setCameraFOV(double fov) {
if (fov < MIN_FOV) {
this.fov = MIN_FOV;
} else if (fov > MAX_FOV) {
this.fov = MAX_FOV;
} else {
this.fov = fov;
}
updateCameraWidthAspect(previousAspect);
}
@Override
public String toString() {
return getName();
}
public void setTrackingMode(boolean _trackingMode) {
trackingMode = trackingMode;
}
public boolean getTrackingMode() {
return trackingMode;
}
public void deactivate() {
}
public double getCameraWidth() {
return cameraWidth;
}
public void zoom(int wr) {
setCameraFOV(fov + 0.0005 * wr);
}
public void setFOVangleDegrees(double fovAngle) {
FOVangleToDraw = fovAngle * Math.PI / 180.0;
}
public void setCurrentInteraction(GL3DInteraction _currentInteraction) {
currentInteraction = _currentInteraction;
}
public GL3DInteraction getCurrentInteraction() {
return currentInteraction;
}
public GL3DInteraction getPanInteraction() {
return panInteraction;
}
public GL3DInteraction getRotateInteraction() {
return rotationInteraction;
}
public GL3DInteraction getAnnotateInteraction() {
return annotateInteraction;
}
public abstract String getName();
public abstract GL3DCameraOptionPanel getOptionPanel();
public abstract void timeChanged(Date date);
public abstract void updateRotation(Date date, MetaData m);
public void zoomToFit() {
double size = Layers.getLargestPhysicalSize();
if (size == 0)
setCameraFOV(INITFOV);
else
setCameraFOV(2. * Math.atan(- size / 2. / getZTranslation()));
}
public GL3DMat4d getRotation() {
return rotation.toMatrix();
}
} |
package shadow.typecheck;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import shadow.AST.ASTUtils;
import shadow.AST.ASTWalker.WalkType;
import shadow.parser.javacc.ASTAdditiveExpression;
import shadow.parser.javacc.ASTAllocationExpression;
import shadow.parser.javacc.ASTArgumentList;
import shadow.parser.javacc.ASTArguments;
import shadow.parser.javacc.ASTArrayDimsAndInits;
import shadow.parser.javacc.ASTArrayInitializer;
import shadow.parser.javacc.ASTAssignmentOperator;
import shadow.parser.javacc.ASTAssignmentOperator.AssignmentType;
import shadow.parser.javacc.ASTBitwiseAndExpression;
import shadow.parser.javacc.ASTBitwiseExclusiveOrExpression;
import shadow.parser.javacc.ASTBitwiseOrExpression;
import shadow.parser.javacc.ASTBlock;
import shadow.parser.javacc.ASTBreakStatement;
import shadow.parser.javacc.ASTCastExpression;
import shadow.parser.javacc.ASTClassOrInterfaceDeclaration;
import shadow.parser.javacc.ASTClassOrInterfaceType;
import shadow.parser.javacc.ASTConditionalAndExpression;
import shadow.parser.javacc.ASTConditionalExclusiveOrExpression;
import shadow.parser.javacc.ASTConditionalExpression;
import shadow.parser.javacc.ASTConditionalOrExpression;
import shadow.parser.javacc.ASTConstructorDeclaration;
import shadow.parser.javacc.ASTDestructorDeclaration;
import shadow.parser.javacc.ASTDoStatement;
import shadow.parser.javacc.ASTEqualityExpression;
import shadow.parser.javacc.ASTExpression;
import shadow.parser.javacc.ASTFieldDeclaration;
import shadow.parser.javacc.ASTForInit;
import shadow.parser.javacc.ASTForStatement;
import shadow.parser.javacc.ASTForeachStatement;
import shadow.parser.javacc.ASTFormalParameter;
import shadow.parser.javacc.ASTFormalParameters;
import shadow.parser.javacc.ASTIfStatement;
import shadow.parser.javacc.ASTIsExpression;
import shadow.parser.javacc.ASTLabeledStatement;
import shadow.parser.javacc.ASTLocalVariableDeclaration;
import shadow.parser.javacc.ASTMemberSelector;
import shadow.parser.javacc.ASTMethodDeclaration;
import shadow.parser.javacc.ASTMultiplicativeExpression;
import shadow.parser.javacc.ASTName;
import shadow.parser.javacc.ASTPrimaryExpression;
import shadow.parser.javacc.ASTPrimaryPrefix;
import shadow.parser.javacc.ASTPrimarySuffix;
import shadow.parser.javacc.ASTPrimitiveType;
import shadow.parser.javacc.ASTReferenceType;
import shadow.parser.javacc.ASTRelationalExpression;
import shadow.parser.javacc.ASTResultType;
import shadow.parser.javacc.ASTReturnStatement;
import shadow.parser.javacc.ASTRightRotate;
import shadow.parser.javacc.ASTRightShift;
import shadow.parser.javacc.ASTRotateExpression;
import shadow.parser.javacc.ASTSequence;
import shadow.parser.javacc.ASTShiftExpression;
import shadow.parser.javacc.ASTStatementExpression;
import shadow.parser.javacc.ASTSwitchLabel;
import shadow.parser.javacc.ASTSwitchStatement;
import shadow.parser.javacc.ASTType;
import shadow.parser.javacc.ASTTypeArguments;
import shadow.parser.javacc.ASTUnaryExpression;
import shadow.parser.javacc.ASTUnaryExpressionNotPlusMinus;
import shadow.parser.javacc.ASTVariableInitializer;
import shadow.parser.javacc.ASTWhileStatement;
import shadow.parser.javacc.Node;
import shadow.parser.javacc.ShadowException;
import shadow.parser.javacc.ShadowParser.ModifierSet;
import shadow.parser.javacc.SimpleNode;
import shadow.typecheck.type.ArrayType;
import shadow.typecheck.type.ClassInterfaceBaseType;
import shadow.typecheck.type.ClassType;
import shadow.typecheck.type.InterfaceType;
import shadow.typecheck.type.MethodType;
import shadow.typecheck.type.SequenceType;
import shadow.typecheck.type.Type;
import shadow.typecheck.type.UnboundMethodType;
//no automatic promotion for bitwise operators
public class ClassChecker extends BaseChecker {
protected LinkedList<HashMap<String, Node>> symbolTable; /** List of scopes with a hash of symbols & types for each scope */
protected Node curMethod = null; /** Current method (only a single reference needed since Shadow does not allow methods to be defined inside of methods) */
protected LinkedList<Node> curPrefix = null; /** Stack for current prefix (needed for arbitrarily long chains of expressions) */
protected LinkedList<Node> labels = null; /** Stack of labels for labeled break statements */
public ClassChecker(boolean debug, Map<String, Type> typeTable, List<String> importList ) {
super(debug, typeTable, importList);
symbolTable = new LinkedList<HashMap<String, Node>>();
curPrefix = new LinkedList<Node>();
labels = new LinkedList<Node>();
}
public Object visit(ASTClassOrInterfaceDeclaration node, Boolean secondVisit) throws ShadowException {
if(!secondVisit) {// set the current type
if( currentType == null )
currentType = (ClassInterfaceBaseType)lookupType(node.getImage());
else
currentType = (ClassInterfaceBaseType)lookupType(currentType + "." + node.getImage());
}
else // set back when returning from an inner class
currentType = (ClassInterfaceBaseType)currentType.getOuter();
return WalkType.POST_CHILDREN;
}
private void createScope(Boolean secondVisit) {
// we have a new scope, so we need a new HashMap in the linked list
if(secondVisit)
{
System.out.println("\nSYMBOL TABLE:");
for(String s:symbolTable.getFirst().keySet())
System.out.println(s + ": " + symbolTable.getFirst().get(s).getType());
symbolTable.removeFirst();
}
else
symbolTable.addFirst(new HashMap<String, Node>());
}
public Object visit(ASTSwitchStatement node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type type = node.jjtGetChild(0).getType();
if(!type.isIntegral() && !type.isString())//TODO allow enum types
addError(node,Error.INVL_TYP, "Found type " + type + ", but integral or string type required for switch.");
for(int i=1;i<node.jjtGetNumChildren();++i) {
Node childNode = node.jjtGetChild(i);
if(childNode.getClass() == ASTSwitchLabel.class) {
if(childNode.getType() != null){ //default label should have null type
if(!childNode.getType().isSubtype(type)) {
addError(childNode,Error.TYPE_MIS,"Label type " + childNode.getType() + " does not match switch type " + type + ".");
}
}
}
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTSwitchLabel node, Boolean secondVisit) throws ShadowException {
pushUpType(node, secondVisit);
if( secondVisit && node.jjtGetNumChildren() > 0 && !ModifierSet.isFinal(node.getModifiers()) )
addError(node, Error.INVL_MOD, "Label must have constant value");
return WalkType.POST_CHILDREN;
}
public Object visit(ASTBlock node, Boolean secondVisit) throws ShadowException {
createScope(secondVisit);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTMethodDeclaration node, Boolean secondVisit) throws ShadowException {
return visitMethod( node, secondVisit );
}
public Object visit(ASTFormalParameters node, Boolean secondVisit) throws ShadowException
/* Note: The ASTFormalParameters node can only be found in methods (including constructors)
* However, the ASTFormalParameter node can also be found in a try-catch block
* This is why we add parameters to the symbol table in ASTFormalParameters and not ASTFormalParameter
*/
{
if(!secondVisit)
return WalkType.POST_CHILDREN;
for(int i = 0; i < node.jjtGetNumChildren(); ++i)
{
Node child = node.jjtGetChild(i);
String varName = child.jjtGetChild(1).getImage();
addSymbol( varName, child );
}
return WalkType.POST_CHILDREN;
}
public void addSymbol( String name, Node node )
{
if( findSymbol( name ) != null )
addError(node, Error.MULT_SYM, name);
else if( symbolTable.size() == 0 )
addError(node, Error.INVL_TYP, "No valid scope for variable declaration");
else
symbolTable.getFirst().put(name, node); //uses node for modifiers
}
public Node findSymbol( String name )
{
Node node = null;
for( HashMap<String,Node> map : symbolTable )
if( (node = map.get(name)) != null )
return node;
return node;
}
public Object visitMethod( SimpleNode node, Boolean secondVisit )
{
if(!secondVisit)
curMethod = node;
else
curMethod = null;
createScope(secondVisit);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTFormalParameter node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
return WalkType.POST_CHILDREN;
node.setType( node.jjtGetChild(0).getType() );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTConstructorDeclaration node, Boolean secondVisit) throws ShadowException {
return visitMethod( node, secondVisit );
}
public Object visit(ASTDestructorDeclaration node, Boolean secondVisit) throws ShadowException {
return visitMethod( node, secondVisit );
}
public Object visit(ASTReferenceType node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type type = node.jjtGetChild(0).getType();
List<Integer> dimensions = node.getArrayDimensions();
if( dimensions.size() == 0 )
node.setType(type);
else
node.setType(new ArrayType(type, dimensions));
return WalkType.POST_CHILDREN;
}
public Object visit(ASTLocalVariableDeclaration node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
// get the var's type
Type type = node.jjtGetChild(0).getType();
if(type == null) {
addError(node.jjtGetChild(0), Error.UNDEF_TYP, node.jjtGetChild(0).jjtGetChild(0).getImage());
return WalkType.NO_CHILDREN;
}
// go through and add the vars
for(int i = 1; i < node.jjtGetNumChildren(); ++i)
{
Node curNode = node.jjtGetChild(i);
String varName = curNode.jjtGetChild(0).getImage();
if(curNode.jjtGetNumChildren() == 2) // check to see if we have any kind of init here
{
Type initType = curNode.jjtGetChild(1).getType();
if(!initType.isSubtype(type))
{
addError(curNode.jjtGetChild(1), Error.TYPE_MIS, "Cannot assign " + initType + " to " + type);
type = Type.UNKNOWN; //overwrites old type, for error case
}
}
// add the symbol to the table
addSymbol( varName, node);
}
node.setType(type); //either declaration type or UNKNOWN
return WalkType.POST_CHILDREN;
}
public Object visit(ASTFieldDeclaration node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type type = node.getType(); // this is set in the FieldAndMethodChecker
for(int i=1; i < node.jjtGetNumChildren(); ++i)
{
Node curVarDec = node.jjtGetChild(i);
if(curVarDec.jjtGetNumChildren() == 2)
{
Node curVarInit = curVarDec.jjtGetChild(1);
Type initType = curVarInit.getType();
if(!initType.isSubtype(type))
addError(curVarInit, Error.TYPE_MIS, "Cannot assign " + initType + " to " + type);
}
}
return WalkType.POST_CHILDREN;
}
private boolean checkField( Node node, String fieldName, Type prefixType, boolean isStatic )
{
if( prefixType instanceof ClassInterfaceBaseType )
{
ClassInterfaceBaseType currentClass = (ClassInterfaceBaseType)prefixType;
if( currentClass.containsField( fieldName ) )
{
Node field = currentClass.getField(fieldName);
if( !fieldIsAccessible( field, currentType ))
addError(node, Error.INVL_MOD, "Field " + fieldName + " not accessible from current context");
else if( isStatic && !ModifierSet.isStatic(field.getModifiers()) )
addError(node, Error.INVL_MOD, "Cannot access non-static field " + fieldName + " from static context");
else
{
node.setType( field.getType());
node.setModifiers(field.getModifiers());
node.addModifier(ModifierSet.ASSIGNABLE);
return true;
}
}
else
{
List<MethodSignature> methods = currentClass.getMethods(fieldName);
//unbound method (it gets bound when you supply args
if( methods != null && methods.size() > 0 )
{
node.setType( new UnboundMethodType( fieldName, currentClass ) );
return true;
}
else
addError(node, Error.UNDEC_VAR, "Member " + fieldName + " not found");
}
}
else
addError(node, Error.INVL_TYP, prefixType + " not valid class or interface");
node.setType( Type.UNKNOWN ); //if got here, some error
return false;
}
public Object visit(ASTName node, Boolean secondVisit) throws ShadowException
{
String[] references = node.getImage().split("\\.");
String name = references[0];
Type type = lookupType(name);
int modifiers = 0;
// first we check to see if this name is a type
if(type != null)
{
Type newType = type;
int i;
for( i = 1; (newType = lookupType(name)) != null && i < references.length; i++ )
{
name += "." + references[i];
type = newType;
}
if( newType != null ) //pure type, no members reference in name
{
node.setType(newType);
node.setModifiers(newType.getModifiers());
node.addModifier(ModifierSet.TYPE_NAME);
}
else
{
boolean first = true;
i--; //step back, because last thing we added made the name no longer a type
for( ; i < references.length && checkField( node, references[i], type, first ); i++ ) //moves through subsequent members
{
type = node.getType();
first = false;
}
}
return WalkType.PRE_CHILDREN;
}
// now go through the scopes trying to find the variable
Node declaration = findSymbol( name );
if( declaration != null )
{
node.setType(declaration.getType());
node.setModifiers(declaration.getModifiers());
node.addModifier(ModifierSet.ASSIGNABLE);
return WalkType.PRE_CHILDREN;
}
// now check the parameters of the method
MethodType methodType = null;
if( curMethod != null )
methodType = (MethodType)curMethod.getType();
if(methodType != null && methodType.containsParam(name))
{
node.setType(methodType.getParameterType(name).getType());
node.setModifiers(methodType.getParameterType(name).getModifiers());
node.addModifier(ModifierSet.ASSIGNABLE);
return WalkType.PRE_CHILDREN;
}
// check to see if it's a field or a method
if( currentType instanceof ClassInterfaceBaseType )
{
ClassInterfaceBaseType currentClass = (ClassInterfaceBaseType)currentType;
if(currentClass.containsField(name))
{
node.setType(currentClass.getField(name).getType());
node.setModifiers(currentClass.getField(name).getModifiers());
node.addModifier(ModifierSet.ASSIGNABLE);
if( ModifierSet.isStatic(curMethod.getModifiers()) && !ModifierSet.isStatic(node.getModifiers()) )
addError(node, Error.INVL_MOD, "Cannot access non-static member " + name + " from static method " + curMethod);
return WalkType.PRE_CHILDREN;
}
if( currentClass instanceof ClassType ) //check parents
{
ClassType parent = ((ClassType)currentClass).getExtendType();
while( parent != null )
{
if(parent.containsField(name))
{
Node field = parent.getField(name);
node.setType(field.getType());
node.setModifiers(field.getModifiers());
node.addModifier(ModifierSet.ASSIGNABLE);
if( ModifierSet.isPrivate(field.getModifiers()))
addError(node, Error.INVL_MOD, "Cannot access private variable " + field.getImage());
if( ModifierSet.isStatic(curMethod.getModifiers()) && !ModifierSet.isStatic(node.getModifiers()) )
addError(node, Error.INVL_MOD, "Cannot access non-static member " + name + " from static method " + curMethod);
return WalkType.PRE_CHILDREN;
}
parent = parent.getExtendType();
}
}
List<MethodSignature> methods = currentClass.getMethods(name);
//unbound method (it gets bound when you supply args)
if( methods != null && methods.size() > 0 )
{
node.setType( new UnboundMethodType( name, currentClass ) );
return WalkType.PRE_CHILDREN;
}
}
// by the time we get here, we haven't found this name anywhere
addError(node, Error.UNDEC_VAR, name);
node.setType(Type.UNKNOWN);
ASTUtils.DEBUG(node, "DIDN'T FIND: " + name);
return WalkType.NO_CHILDREN;
}
public Object visit(ASTAssignmentOperator node, Boolean secondVisit) throws ShadowException {
return WalkType.NO_CHILDREN; // I don't think we do anything here
}
public Object visit(ASTRelationalExpression node, Boolean secondVisit) throws ShadowException {
if( !secondVisit )
return WalkType.POST_CHILDREN;
Type result = node.jjtGetChild(0).getType();
for( int i = 1; i < node.jjtGetNumChildren(); i++ )
{
Type current = node.jjtGetChild(i).getType();
if( !result.isNumerical() || !current.isNumerical() )
{
addError(node, Error.INVL_TYP, "Relational operator not defined on types " + result + " and " + current);
node.setType(Type.UNKNOWN);
return WalkType.POST_CHILDREN;
}
result = Type.BOOLEAN; //boolean after one comparison
}
node.setType(result); //propagates type up if only one child
pushUpModifiers(node); //can make ASSIGNABLE (if only one child)
return WalkType.POST_CHILDREN;
}
public Object visit(ASTEqualityExpression node, Boolean secondVisit) throws ShadowException {
if( !secondVisit )
return WalkType.POST_CHILDREN;
Type result = node.jjtGetChild(0).getType();
for( int i = 1; i < node.jjtGetNumChildren(); i++ )
{
Type current = node.jjtGetChild(i).getType();
if( !result.isSubtype(current) && !current.isSubtype(result) )
{
addError(node, Error.INVL_TYP, "Equality operator not defined on types " + result + " and " + current);
node.setType(Type.UNKNOWN);
return WalkType.POST_CHILDREN;
}
result = Type.BOOLEAN; //boolean after one comparison
}
node.setType(result); //propagates type up if only one child
pushUpModifiers(node); //can overwrite ASSIGNABLE (if only one child)
return WalkType.POST_CHILDREN;
}
public void visitShiftRotate( SimpleNode node ) throws ShadowException
{
Type result = node.jjtGetChild(0).getType();
for( int i = 1; i < node.jjtGetNumChildren(); i++ )
{
Node child = node.jjtGetChild(i);
if( !(child instanceof ASTRightShift) && !(child instanceof ASTRightRotate) ) //RightRotate() and RightShift() have their own productions
{
Type current = child.getType();
if( current.isIntegral() && result.isIntegral() )
{
if( result.isSubtype( current )) //upgrades type to broader type (e.g. int goes to long)
result = current;
}
else
{
addError(child, Error.INVL_TYP, "Shift and rotate operations not defined on types " + result + " and " + current);
node.setType(Type.UNKNOWN);
return;
}
}
}
node.setType(result); //propagates type up if only one child
pushUpModifiers(node); //can add ASSIGNABLE (if only one child)
}
public Object visit(ASTShiftExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitShiftRotate( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTRotateExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitShiftRotate( node );
return WalkType.POST_CHILDREN;
}
public void visitArithmetic(SimpleNode node) throws ShadowException
{
Type result = node.jjtGetChild(0).getType();
for( int i = 1; i < node.jjtGetNumChildren(); i++ )
{
Type current = node.jjtGetChild(i).getType();
if( result.isString() || current.isString() )
{
if( node.getImage().charAt(i - 1) != '+' )
{
addError(node.jjtGetChild(0), Error.INVL_TYP, "Cannot apply operator " + node.getImage().charAt(i - 1) + " to String type");
node.setType(Type.UNKNOWN);
return;
}
else
result = Type.STRING;
}
else if( result.isNumerical() && current.isNumerical() )
{
if( result.isSubtype( current )) //upgrades type to broader type (e.g. int goes to double)
result = current;
}
else
{
addError(node.jjtGetChild(i), Error.INVL_TYP, "Cannot apply arithmetic operations to " + result + " and " + current);
node.setType(Type.UNKNOWN);
return;
}
}
node.setType(result); //propagates type up if only one child
pushUpModifiers(node); //can add ASSIGNABLE (if only one child)
}
public Object visit(ASTAdditiveExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitArithmetic( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTMultiplicativeExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitArithmetic( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTUnaryExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t = node.jjtGetChild(0).getType();
String symbol = node.getImage();
if( (symbol.equals("-") || symbol.equals("+")) )
{
if( !t.isNumerical() )
{
addError(node, Error.INVL_TYP, "Found type " + t + ", but numerical type required for arithmetic operations");
node.setType(Type.UNKNOWN);
return WalkType.POST_CHILDREN;
}
}
else
pushUpModifiers( node );
if(symbol.startsWith("-"))
node.setType(Type.makeSigned((ClassType)t));
else
node.setType(t);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTUnaryExpressionNotPlusMinus node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t = node.jjtGetChild(0).getType();
if(node.getImage().startsWith("~") )
{
if( !t.isIntegral() )
{
addError(node, Error.INVL_TYP, "Found type " + t + ", but integral type required for bitwise operations");
t = Type.UNKNOWN;
}
}
else if(node.getImage().startsWith("!") )
{
if( !t.equals(Type.BOOLEAN))
{
addError(node, Error.INVL_TYP, "Found type " + t + ", but boolean type required for logical operations");
t = Type.UNKNOWN;
}
}
else
pushUpModifiers( node ); //can add ASSIGNABLE (if only one child)
node.setType(t);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTConditionalExpression node, Boolean secondVisit) throws ShadowException {
if( !secondVisit )
return WalkType.POST_CHILDREN;
if(node.jjtGetNumChildren() == 1)
pushUpType( node, secondVisit ); //propagate type and modifiers up
else if(node.jjtGetNumChildren() == 3)
{
Type t1 = node.jjtGetChild(0).getType();
Type t2 = node.jjtGetChild(1).getType();
Type t3 = node.jjtGetChild(2).getType();
if( !t1.equals(Type.BOOLEAN) )
{
addError(node.jjtGetChild(0), Error.INVL_TYP, "Found type" + t1 + ", but boolean type required for conditional operations");
node.setType(Type.UNKNOWN);
}
else if( t2.isSubtype(t3) )
node.setType(t3);
else if( t3.isSubtype(t2) )
node.setType(t2);
else
{
addError(node, Error.TYPE_MIS, "Type " + t2 + " must match " + t3 + " in ternary operator");
node.setType(Type.UNKNOWN);
}
}
return WalkType.POST_CHILDREN;
}
public void visitConditional(SimpleNode node ) throws ShadowException {
if( node.jjtGetNumChildren() == 1 )
pushUpType(node, true); //includes modifier push up
else
{
Type result = null;
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
{
result = node.jjtGetChild(i).getType();
if( result != Type.BOOLEAN )
{
addError(node.jjtGetChild(i), Error.INVL_TYP, "Found type " + result + ", but boolean type required for conditional operations");
node.setType(Type.UNKNOWN);
return;
}
}
node.setType(result);
}
}
public Object visit(ASTConditionalOrExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitConditional( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTConditionalExclusiveOrExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitConditional( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTConditionalAndExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitConditional( node );
return WalkType.POST_CHILDREN;
}
public void visitBitwise(SimpleNode node ) throws ShadowException {
if( node.jjtGetNumChildren() == 1 )
pushUpType(node, true); //includes modifier push up
else
{
Type result = node.jjtGetChild(0).getType();
if( !result.isIntegral() )
{
addError(node.jjtGetChild(0), Error.INVL_TYP, "Found type " + result + ", but integral type required for shift and rotate operations");
node.setType(Type.UNKNOWN);
return;
}
for( int i = 1; i < node.jjtGetNumChildren(); i++ )
{
Type current = node.jjtGetChild(i).getType();
if( !current.isIntegral() )
{
addError(node.jjtGetChild(i), Error.INVL_TYP, "Found type " + current + ", but integral type required for shift and rotate operations");
node.setType(Type.UNKNOWN);
return;
}
if( current.isSubtype(result))
result = current;
}
node.setType(result);
}
}
public Object visit(ASTBitwiseOrExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitBitwise( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTBitwiseExclusiveOrExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitBitwise( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTBitwiseAndExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
visitBitwise( node );
return WalkType.POST_CHILDREN;
}
public Object visit(ASTExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
// if we only have 1 child, we just get the type from that child
if(node.jjtGetNumChildren() == 1)
pushUpType(node, secondVisit); //takes care of modifiers
// we have 3 children so it's an assignment
else if(node.jjtGetNumChildren() == 3)
{
// get the two types, we have to go up to the parent to get them
Node child1 = node.jjtGetChild(0);
Type t1 = child1.getType();
if( !ModifierSet.isAssignable( child1.getModifiers() ))
{
addError(child1, Error.TYPE_MIS, "Cannot assign a value to expression: " + child1 );
node.setType(Type.UNKNOWN);
return WalkType.NO_CHILDREN;
}
ASTAssignmentOperator op = (ASTAssignmentOperator)node.jjtGetChild(1);
Node child2 = node.jjtGetChild(2);
Type t2 = child2.getType();
// SHOULD DO SOMETHING WITH THIS!!!
AssignmentType assType = op.getAssignmentType();
// TODO: Add in all the types that we can compare here
if( !t2.isSubtype(t1) )
{
addError(child1, Error.TYPE_MIS, "Found type " + t2 + ", type " + t1 + " required");
node.setType(Type.UNKNOWN);
return WalkType.NO_CHILDREN;
}
node.setType(t1); // set this node's type
node.setModifiers( child2.getModifiers() ); //is this meaningful?
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTAllocationExpression node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
return WalkType.POST_CHILDREN;
//check curPrefix at some point
Node child = node.jjtGetChild(0);
if( child instanceof ASTPrimitiveType ) //array allocation
{
//array dims and inits
List<Integer> dimensions = ((ASTArrayDimsAndInits)(node.jjtGetChild(1))).getArrayDimensions();
node.setType(new ArrayType(child.getType(), dimensions));
}
else if( child instanceof ASTClassOrInterfaceType ) //object allocation
{
int counter = 1;
if( node.jjtGetChild(counter) instanceof ASTTypeArguments )
{
//for now
addError(node.jjtGetChild(counter), Error.INVL_TYP, "Generics are not yet handled");
node.setType(Type.UNKNOWN);
counter++;
}
if( node.jjtGetChild(counter) instanceof ASTArrayDimsAndInits)
{
//array dims and inits
List<Integer> dimensions = ((ASTArrayDimsAndInits)(node.jjtGetChild(counter))).getArrayDimensions();
node.setType(new ArrayType(child.getType(), dimensions));
}
else if( node.jjtGetChild(counter) instanceof ASTArguments )
{
if( child.getType() instanceof InterfaceType )
{
addError(child, Error.INVL_TYP, "Interfaces cannot be instantiated");
node.setType(Type.UNKNOWN);
return WalkType.POST_CHILDREN;
}
ClassInterfaceBaseType type = (ClassInterfaceBaseType)child.getType();
List<Type> typeList = ((ASTArguments)(node.jjtGetChild(counter))).getTypeList();
List<MethodSignature> candidateConstructors = type.getMethods("constructor");
// we don't have implicit constructors, so need to check if the default constructor is OK
if(typeList.size() == 0 && candidateConstructors == null)
{
node.setType(child.getType());
return WalkType.POST_CHILDREN;
}
// we have no constructors, but they are calling with params
else if(typeList.size() > 0 && candidateConstructors == null)
{
addError(child, Error.TYPE_MIS, "No constructor found with signature " + typeList);
node.setType(Type.UNKNOWN);
return WalkType.POST_CHILDREN;
}
else
{
// by the time we get here, we have a constructor list
List<MethodSignature> acceptableConstructors = new LinkedList<MethodSignature>();
for( MethodSignature signature : candidateConstructors )
{
if( signature.matches( typeList ))
{
node.setType(child.getType());
return WalkType.POST_CHILDREN;
}
else if( signature.canAccept(typeList))
acceptableConstructors.add(signature);
}
if( acceptableConstructors.size() == 0 )
{
addError(child, Error.TYPE_MIS, "No constructor found with signature " + typeList);
node.setType(Type.UNKNOWN);
}
else if( acceptableConstructors.size() > 1 )
{
addError(child, Error.TYPE_MIS, "Ambiguous constructor call with signature " + typeList);
node.setType(Type.UNKNOWN);
}
else
node.setType(child.getType());
}
}
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTArgumentList node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
node.addType(node.jjtGetChild(i).getType());
return WalkType.POST_CHILDREN;
}
public Object visit(ASTArguments node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
if( node.jjtGetNumChildren() == 0 )
node.setTypeList(new LinkedList<Type>());
else
node.setTypeList(((ASTArgumentList)(node.jjtGetChild(0))).getTypeList());
return WalkType.POST_CHILDREN;
}
public Object visit(ASTStatementExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Node child = node.jjtGetChild(0);
if( child instanceof ASTSequence )
{
ASTSequence sequence = (ASTSequence)child;
SequenceType t1 = (SequenceType)(child.getType());
Type t2 = node.jjtGetChild(1).getType();
if( !sequence.isAssignable() )
addError(child, Error.TYPE_MIS, "Cannot assign a value to expression: " + child);
else if( t2 instanceof SequenceType ) //from method call
{
SequenceType sequenceType = (SequenceType)t2;
if( !t1.canAccept( sequenceType.getTypes() ) )
addError(child, Error.TYPE_MIS, "Sequence " + sequenceType + " does not match " + sequence);
}
else
addError(child, Error.TYPE_MIS, "Only method return values can be assigned to sequences");
}
else //primary expression
{
if( node.jjtGetNumChildren() == 3 ) //only need to proceed if there is assignment
{
ASTAssignmentOperator op = (ASTAssignmentOperator)node.jjtGetChild(1);
Type t1 = child.getType();
Type t2 = node.jjtGetChild(2).getType();
if( !ModifierSet.isAssignable(child.getModifiers()) )
addError(child, Error.TYPE_MIS, "Cannot assign a value to expression: " + child);
else if( ModifierSet.isFinal(child.getModifiers()) )
addError(child, Error.INVL_TYP, "Cannot assign a value to variable marked final");
else
{
// SHOULD DO SOMETHING WITH THIS!!!
AssignmentType assType = op.getAssignmentType();
if( t2 instanceof MethodType ) //could this be done with a more complex subtype relationship below?
{
MethodType methodType = (MethodType)t2;
List<Type> type = new LinkedList<Type>();
type.add(t1);
if( !methodType.canReturn( type ) )
addError(child, Error.TYPE_MIS, "Method with signature " + methodType + " cannot return " + t1);
}
else if( !t2.isSubtype(t1) )
addError(child, Error.TYPE_MIS, "Found type " + t2 + ", type " + t1 + " required");
}
}
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTIsExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
//RelationalExpression() [ "is" Type() ]
if( node.jjtGetNumChildren() == 1 )
pushUpType(node, secondVisit);
else
{
Type t1 = node.jjtGetChild(0).getType();
Type t2 = node.jjtGetChild(1).getType();
if( t1.isSubtype(t2) || t2.isSubtype(t1) )
node.setType(Type.BOOLEAN);
else
{
addError(node, Error.TYPE_MIS, "Type " + t1 + " uncomparable with type " + t2);
node.setType(Type.UNKNOWN);
}
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTCastExpression node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
if( node.jjtGetNumChildren() == 1 )
pushUpType(node, secondVisit);
else
{
Type t1 = node.jjtGetChild(0).getType(); //type
Type t2 = node.jjtGetChild(1).getType(); //expression
if( t1.isSubtype(t2) || t2.isSubtype(t1) )
node.setType(t1);
else
{
addError(node, Error.TYPE_MIS, "Type " + t2 + " cannot be cast to " + t1);
node.setType(Type.UNKNOWN);
}
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTSequence node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
if( node.jjtGetNumChildren() == 1 ) //maybe, or should it be treated like a sequence with one thing in it?
pushUpType(node, secondVisit);
else
{
SequenceType sequence = new SequenceType();
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
sequence.addType(node.jjtGetChild(i).getType());
node.setType( sequence );
}
return WalkType.POST_CHILDREN;
}
public Object visit(ASTIfStatement node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t = node.jjtGetChild(0).getType();
if( !t.equals( Type.BOOLEAN ) )
addError(node, Error.TYPE_MIS, "conditional of if statement must be boolean, found: " + t);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTWhileStatement node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t = node.jjtGetChild(0).getType();
if( !t.equals( Type.BOOLEAN ) )
addError(node, Error.TYPE_MIS, "conditional of while statement must be boolean, found: " + t);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTDoStatement node, Boolean secondVisit) throws ShadowException {
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t = node.jjtGetChild(1).getType(); //second child, not first like if and while
if( !t.equals( Type.BOOLEAN ) )
addError(node, Error.TYPE_MIS, "conditional of do statement must be boolean, found: " + t);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTForeachStatement node, Boolean secondVisit) throws ShadowException {
createScope(secondVisit); //for variables declared in header, right? Pretty sure that works
if(!secondVisit)
return WalkType.POST_CHILDREN;
Type t1 = node.jjtGetChild(0).getType(); //Type declaration
Type t2 = node.jjtGetChild(1).getType(); //Collection
// TODO: Eventually we'll want the notion of a collection and need to check that here
if( t2.getKind() == Type.Kind.ARRAY )
{
ArrayType array = (ArrayType)t2;
if( !array.getBaseType().isSubtype(t1) )
addError(node, Error.TYPE_MIS, "incompatible foreach variable, found: " + t1 + " expected: " + array.getBaseType());
}
else
addError(node, Error.TYPE_MIS, "foreach loop only works on arrays in this typechecker build, found: " + t2);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTForStatement node, Boolean secondVisit) throws ShadowException {
boolean hasInit = false;
if(node.jjtGetChild(0) instanceof ASTForInit) {
createScope(secondVisit); // only need the scope if we've created new vars
hasInit = true;
}
if(!secondVisit)
return WalkType.POST_CHILDREN;
// the conditional type might come first or second depending upon if there is an init or not
Type conditionalType = null;
if(hasInit)
conditionalType = node.jjtGetChild(1).getType();
else
conditionalType = node.jjtGetChild(0).getType();
ASTUtils.DEBUG("TYPE: " + conditionalType);
if(conditionalType == null || !conditionalType.equals( Type.BOOLEAN ) )
addError(node, Error.TYPE_MIS, "conditional of for statement must be boolean, found: " + conditionalType);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTReturnStatement node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
return WalkType.POST_CHILDREN;
//make sure matches method return types
List<Type> types = new LinkedList<Type>();
String returnTypes = "(";
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
{
returnTypes += node.jjtGetChild(i).getType();
if( i < node.jjtGetNumChildren() - 1 )
returnTypes += ",";
types.add( node.jjtGetChild(i).getType() );
}
returnTypes += ")";
if( !((MethodType)curMethod.getType()).canReturn(types))
addError(node, Error.TYPE_MIS, "Method with signature " + curMethod + " cannot return " + returnTypes);
return WalkType.POST_CHILDREN;
}
public Object visit(ASTPrimaryExpression node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
{
curPrefix.addFirst(null);
return WalkType.POST_CHILDREN;
}
if( node.jjtGetNumChildren() > 1 ) //has suffixes, pull type from last suffix
{
node.setType(node.jjtGetChild(node.jjtGetNumChildren() - 1).getType());
node.setModifiers(node.jjtGetChild(node.jjtGetNumChildren() - 1).getModifiers());
}
else //just prefix
{
node.setType(node.jjtGetChild(0).getType());
pushUpModifiers( node );
}
curPrefix.removeFirst(); //pop prefix type off stack
return WalkType.POST_CHILDREN;
}
public Object visit(ASTPrimaryPrefix node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
return WalkType.POST_CHILDREN;
int children = node.jjtGetNumChildren();
if( children == 0 )
{
if( node.getImage().equals("this") )
{
if( currentType instanceof InterfaceType )
{
addError(node, Error.INVL_TYP, "Reference this invalid for interfaces");
node.setType(Type.UNKNOWN);
}
else
{
node.setType(currentType);
if( curMethod != null && ModifierSet.isStatic(curMethod.getModifiers()) )
addError(node, Error.INVL_MOD, "Cannot access non-static reference this from static method " + curMethod);
}
}
else //super case
{
if( currentType instanceof InterfaceType )
{
addError(node, Error.INVL_TYP, "Reference super invalid for interfaces"); //may need other cases
node.setType(Type.UNKNOWN);
}
else if( currentType instanceof ClassType )
{
ClassType parentType = ((ClassType)currentType).getExtendType();
if( parentType.containsField(node.getImage() ))
{
node.setType(parentType.getField(node.getImage()).getType());
if( curMethod != null && ModifierSet.isStatic(curMethod.getModifiers()) )
addError(node, Error.INVL_MOD, "Cannot access non-static reference super from static method " + curMethod);
}
else
{
List<MethodSignature> methods = parentType.getMethods(node.getImage());
//unbound method (it gets bound when you supply args
if( methods != null && methods.size() > 0 )
node.setType( new UnboundMethodType( node.getImage(), parentType ) );
else
{
addError(node, Error.UNDEC_VAR, "Member " + node.getImage() + " not found");
node.setType(Type.UNKNOWN);
}
}
}
else
{
addError(node, Error.INVL_TYP, "Reference super must be used inside of class, enum, error, or exception"); //will this ever happen?
node.setType(Type.UNKNOWN);
}
}
}
else if( children == 1 )
{
Node child = node.jjtGetChild(0);
if( child instanceof ASTResultType ) //ResultType() "." "class"
{
if( child.getType() instanceof ClassType )
node.setType( Type.CLASS );
else
{
addError(node, Error.INVL_TYP, ".class member only accessible on class, enum, error, or exception types"); //may need other cases
node.setType(Type.UNKNOWN);
}
}
else
{
node.setType( child.getType() ); //literal, conditionalexpression, allocation expression, name
pushUpModifiers( node );
}
}
curPrefix.set(0, node); //so that the suffix can figure out where it's at
/*
Literal()
| "this" { jjtThis.setImage("this"); }
| "super" "." t = <IDENTIFIER> { jjtThis.setImage(t.image); }
| LOOKAHEAD( "(" ConditionalExpression() ")" ) "(" ConditionalExpression() ")"
| AllocationExpression()
| LOOKAHEAD( ResultType() "." "class" ) ResultType() "." "class"
| Name()
*/
return WalkType.POST_CHILDREN;
}
public Object visit(ASTPrimarySuffix node, Boolean secondVisit) throws ShadowException
{
/*
LOOKAHEAD(2) "." "this"
| LOOKAHEAD(2) "." AllocationExpression()
| LOOKAHEAD(3) MemberSelector()
| "[" ConditionalExpression() ("," ConditionalExpression())* "]"
| "." t = <IDENTIFIER> { jjtThis.setImage(t.image); }
| Arguments()
}
*/
Node prefixNode = curPrefix.getFirst();
Type prefixType = prefixNode.getType();
if(!secondVisit)
return WalkType.POST_CHILDREN;
int children = node.jjtGetNumChildren();
if( children == 0 )
{
if( node.getImage().equals("this") )
node.setType(prefixType);
else //field name
checkField( node, node.getImage(), prefixType, ModifierSet.isTypeName(prefixNode.getModifiers()) );
}
else
{
Node child = node.jjtGetChild(0);
if( child instanceof ASTAllocationExpression ) //"." AllocationExpression()
{
ASTAllocationExpression allocation = (ASTAllocationExpression)child;
if( prefixType instanceof ClassInterfaceBaseType )
{
ClassInterfaceBaseType currentClass = (ClassInterfaceBaseType)prefixType;
if( currentClass.containsInnerClass(allocation.getType().getTypeName()) )
{
node.setType(currentClass.getInnerClass(allocation.getType().getTypeName()));
if( !classIsAccessible( allocation.getType(), currentType ))
addError(node, Error.INVL_MOD, "Class " + allocation.getType() + " not accessible from current context");
}
else
{
addError(node, Error.UNDEF_TYP, "Inner class " + allocation.getType().getTypeName() + " not found");
node.setType(Type.UNKNOWN);
}
}
else
{
addError(node, Error.INVL_TYP, prefixType + " not valid class or interface");
node.setType(Type.UNKNOWN);
}
}
else if( child instanceof ASTMemberSelector )
{
addError(node, Error.INVL_TYP, "Generics are not yet handled");
node.setType(Type.UNKNOWN);
}
else if( child instanceof ASTConditionalExpression ) //array index
{
if( prefixType instanceof ArrayType )
{
ArrayType arrayType = (ArrayType)prefixType;
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
{
Type childType = node.jjtGetChild(0).getType();
if( !childType.isIntegral() )
{
addError(node.jjtGetChild(i), Error.INVL_TYP, "Found type " + childType + ", but integral type required for array subscript");
node.setType(Type.UNKNOWN);
}
}
if( node.getType() != Type.UNKNOWN )
{
if( node.jjtGetNumChildren() == arrayType.getDimensions() )
{
node.setType( arrayType.getBaseType() );
node.addModifier(ModifierSet.ASSIGNABLE);
}
else
{
node.setType(Type.UNKNOWN);
addError(node, Error.TYPE_MIS, "Needed " + arrayType.getDimensions() + " indexes into array but found " + node.jjtGetNumChildren());
}
}
}
else
{
node.setType(Type.UNKNOWN);
addError(node, Error.INVL_TYP, "Cannot subscript into non-array type " + prefixType);
}
}
else if( child instanceof ASTArguments ) //method call
{
if( prefixType instanceof UnboundMethodType )
{
UnboundMethodType unboundMethod = (UnboundMethodType)prefixType;
List<Type> typeList = ((ASTArguments)child).getTypeList();
ClassInterfaceBaseType outerClass = (ClassInterfaceBaseType)unboundMethod.getOuter();
List<MethodSignature> methods = outerClass.getMethods(unboundMethod.getTypeName());
List<MethodSignature> acceptableMethods = new LinkedList<MethodSignature>();
boolean perfectMatch = false;
for( MethodSignature signature : methods )
{
if( signature.matches( typeList ))
{
List<Type> returnTypes = signature.getMethodType().getReturnTypes();
if( returnTypes.size() == 1 )
node.setType(returnTypes.get(0));
else
{
SequenceType sequenceType = new SequenceType();
for( Type type : returnTypes )
sequenceType.addType(type);
node.setType( sequenceType );
}
perfectMatch = true;
if( !methodIsAccessible( signature, currentType ))
addError(node, Error.INVL_MOD, "Method " + signature + " not accessible from current context");
else
prefixNode.setType(signature.getMethodType());
}
else if( signature.canAccept(typeList))
acceptableMethods.add(signature);
}
if( !perfectMatch )
{
if( acceptableMethods.size() == 0 )
{
node.setType(Type.UNKNOWN);
addError(child, Error.TYPE_MIS, "No method found with signature " + typeList);
}
else if( acceptableMethods.size() > 1 )
{
node.setType(Type.UNKNOWN);
addError(child, Error.TYPE_MIS, "Ambiguous method call with signature " + typeList);
}
else
{
MethodSignature signature = acceptableMethods.get(0);
List<Type> returnTypes = signature.getMethodType().getReturnTypes();
if( returnTypes.size() == 1 )
node.setType(returnTypes.get(0));
else
{
SequenceType sequenceType = new SequenceType();
for( Type type : returnTypes )
sequenceType.addType(type);
node.setType( sequenceType );
}
if( !methodIsAccessible( signature, currentType ))
addError(node, Error.INVL_MOD, "Method " + signature + " not accessible from current context");
else
prefixNode.setType(signature.getMethodType());
}
}
}
}
}
curPrefix.set(0, node); //so that a future suffix can figure out where it's at
/*
| LOOKAHEAD(2) "." AllocationExpression()
| LOOKAHEAD(3) MemberSelector()
| "[" ConditionalExpression() ("," ConditionalExpression())* "]"
| Arguments()
}
*/
return WalkType.POST_CHILDREN;
}
public static boolean fieldIsAccessible( Node node, Type type )
{
if( ModifierSet.isPublic(node.getModifiers()) || node.getEnclosingType() == type )
return true;
if( type instanceof ClassType )
{
ClassType parent = ((ClassType)type).getExtendType();
while( parent != null )
{
if( node.getEnclosingType() == parent )
{
if( ModifierSet.isPrivate(node.getModifiers()))
return false;
else
return true;
}
parent = parent.getExtendType();
}
}
return false;
}
public static boolean classIsAccessible( Type classType, Type type )
{
if( ModifierSet.isPublic(classType.getModifiers()) || classType.getOuter() == type || classType.getOuter() == null )
return true;
Type outer = type.getOuter();
while( outer != null )
{
if( outer == classType.getOuter() )
return true;
outer = outer.getOuter();
}
if( type instanceof ClassType )
{
ClassType parent = ((ClassType)type).getExtendType();
while( parent != null )
{
if( classType.getOuter() == parent )
{
if( ModifierSet.isPrivate(classType.getModifiers()))
return false;
else
return true;
}
outer = parent.getOuter();
while( outer != null )
{
if( outer == classType.getOuter() )
return true;
outer = outer.getOuter();
}
parent = parent.getExtendType();
}
}
return false;
}
public static boolean methodIsAccessible( MethodSignature signature, Type type )
{
return fieldIsAccessible( signature.getASTNode(), type );
}
/*//Push up is wrong, the children of ResultTypes are many, we can't just push one up
public Object visit(ASTResultTypes node, Boolean secondVisit) throws ShadowException
{ return pushUpType(node, secondVisit);
}
*/
public Object visit(ASTLabeledStatement node, Boolean secondVisit) throws ShadowException
{
if(!secondVisit)
{
String label = node.getImage();
if(findSymbol(label) != null || labels.contains(label))
addError(node, Error.MULT_SYM, label);
else
labels.push(node);
}
else
labels.pop();
return WalkType.POST_CHILDREN;
}
public Object visit(ASTBreakStatement node, Boolean secondVisit) throws ShadowException
{
if( !node.getImage().isEmpty() )
{
for( Node label : labels )
if( label.equals(node.getImage()) )
return WalkType.PRE_CHILDREN;
addError(node, Error.UNDEC_VAR, "No matching label for break statement");
}
return WalkType.PRE_CHILDREN;
}
public Object visit(ASTArrayDimsAndInits node, Boolean secondVisit) throws ShadowException
{
if( secondVisit )
{
Node child = node.jjtGetChild(0);
if( child instanceof ASTArrayInitializer )
{
//finish this!!!
}
else
{
for( int i = 0; i < node.jjtGetNumChildren(); i++ )
{
child = node.jjtGetChild(i);
if( !child.getType().isNumerical() )
{
addError(child, Error.INVL_TYP, "Numerical type must be specified for array dimensions");
break;
}
}
}
}
return WalkType.POST_CHILDREN;
}
// Everything below here are just visitors to push up the type
public Object visit(ASTType node, Boolean secondVisit) throws ShadowException { return pushUpType(node, secondVisit); }
public Object visit(ASTVariableInitializer node, Boolean secondVisit) throws ShadowException {
return pushUpType(node, secondVisit);
}
public Object visit(ASTResultType node, Boolean secondVisit) throws ShadowException { return pushUpType(node, secondVisit); }
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.badrobot.commands;
import com.badrobot.OI;
import edu.wpi.first.wpilibj.Utility;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.tables.ITable;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Isaac
*/
public class DriveStraightForward extends BadCommand
{
public double setSpeed;
public double gyroAngle;
private double scaleFactor;
private long startTime;
private long driveTime;
public int state;
public static final int DRIVING_STRAIGHT = 0,
TURNING_RIGHT = 1,
TURNING_LEFT = 2;
/**
* Runs the command for the default time length.
*/
public DriveStraightForward()
{
requires((Subsystem) driveTrain);
driveTime = 6*1000000;
}
/**
* Runs the command for the set time length in seconds.
*/
public DriveStraightForward(long setTime)
{
long temp = setTime*1000000;
driveTime = temp;
}
public String getConsoleIdentity()
{
return "DriveStraightForward";
}
protected void initialize()
{
setSpeed = .2;
scaleFactor = 1;
driveTrain.getGyro().reset();
startTime = Utility.getFPGATime(); //returns fpga time in MICROseconds.
}
protected void execute()
{
gyroAngle = driveTrain.getGyro().getAngle();
//This if statement will make sure the motors do not go in the reverse direction
//when the angle is over 40 degrees either direction.
if(scaleFactor <= 0)
scaleFactor = 0;
switch (state)
{
//Drives robot straight until the angle is greater than 5 degrees either direction.
case DRIVING_STRAIGHT:
if (gyroAngle > 5)
{
state = TURNING_RIGHT;
}
else if (gyroAngle < -5)
{
state = TURNING_LEFT;
}
else
{
driveTrain.getTrain().tankDrive(setSpeed, setSpeed);
}
break;
//Turns the robot to the right until it is less than 5 degrees off center.
case TURNING_RIGHT:
if (gyroAngle <= 5)
{
state = DRIVING_STRAIGHT;
}
else
{
scaleFactor = 1 - Math.abs(gyroAngle*0.025);
driveTrain.getTrain().tankDrive(setSpeed, setSpeed*scaleFactor);
}
break;
//Turns the robot to the left until it is less than 5 degrees off center.
case TURNING_LEFT:
if (gyroAngle >= 5)
{
state = DRIVING_STRAIGHT;
}
else
{
scaleFactor = 1 - Math.abs(gyroAngle*0.025);
driveTrain.getTrain().tankDrive(setSpeed*scaleFactor, setSpeed);
}
break;
}
}
protected boolean isFinished()
{
if (Utility.getFPGATime() >= startTime + driveTime)
{
return true;
}
else
{
return false;
}
}
protected void end()
{
driveTrain.getTrain().tankDrive(0,0);
}
protected void interrupted()
{
}
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
}
protected void addNetworkTableValues(ITable table) {
}
} |
package org.cyanogenmod.launcher.home.api.cards;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.provider.CmHomeContentProvider;
import org.cyanogenmod.launcher.home.api.provider.CmHomeContract;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* Class representing an image that should be displayed along with a parent
* {@link org.cyanogenmod.launcher.home.api.cards.CardData}. Any number of CardDataImage objects
* can be associated with a CardData, and as many as possible will attempt to be displayed with
* the Card in CM Home.
*
* As with {@link org.cyanogenmod.launcher.home.api.cards.CardData},
* a CardDataImage will be published when
* {@link org.cyanogenmod.launcher.home.api.cards.CardDataImage#publish(Context)} is called.
* CardDataImage objects can similarly be removed from view by calling
* {@link org.cyanogenmod.launcher.home.api.cards.CardDataImage#unpublish(android.content.Context)}.
*/
public class CardDataImage extends PublishableCard {
private final static String TAG = "CardDataImage";
/**
* Store a reference to the Database Contract that represents this object,
* so that the superclass can figure out what columns to write.
*/
private final static CmHomeContract.ICmHomeContract sContract =
new CmHomeContract.CardDataImageContract();
private long mCardDataId;
private CardData mLinkedCardData;
private Uri mImageUri;
private String mInternalId;
private String mImageLabel;
private WeakReference<Bitmap> mImageBitmap;
private int mImageResourceId = 0;
/**
* Create a new CardDataImage by passing in a parent {@link CardData} that this
* CardDataImage will be linked to.
* @param linkedCardData The CardData that will be the parent of this CardDataImage.
*/
public CardDataImage(CardData linkedCardData) {
super(sContract);
mLinkedCardData = linkedCardData;
}
/**
* Construct a new CardDataImage using the given Uri as the image source for this image.
* @param imageUri A Uri that resolves to the image that this CardDataImage will display.
* @param linkedCardData The CardData that will be the parent of this CardImageData.
*/
public CardDataImage(Uri imageUri, CardData linkedCardData) {
super(sContract);
mImageUri = imageUri;
mLinkedCardData = linkedCardData;
}
private CardDataImage(long cardDataId, Uri imageUri) {
super(sContract);
mCardDataId = cardDataId;
mImageUri = imageUri;
}
/**
* Sets the ID field that should be used for a unique string that can identify this Card
* within your application. This field is optional and can be used for internal tracking
* within this application.
* @param internalId The String to be used to uniquely identify this card.
*/
public void setInternalId(String internalId) {
mInternalId = internalId;
}
/**
* Retrieves the currenly set internal ID.
* @see org.cyanogenmod.launcher.home.api.cards.CardDataImage#setInternalId(java.lang.String)
* @return The internal ID String that is currently set for this CardDataImage.
*/
public String getInternalId() {
return mInternalId;
}
/**
* Retrieves the ID for this CardDataImage. This is the primary key of this object within
* this application.
* @return The ID of this CardDataImage within this application.
*/
public long getCardDataId() {
return mCardDataId;
}
/**
* Sets the ID of the {@link org.cyanogenmod.launcher.home.api.cards.CardData} that this
* image is associated with. This required field tells CM Home which Card this image will be
* displayed with.
* @param cardDataId The ID of the Card that this image is a child of, as returned by
* {@link org.cyanogenmod.launcher.home.api.cards.CardData#getId()}.
*/
private void setCardDataId(long cardDataId) {
mCardDataId = cardDataId;
}
/**
* Retrieves the Uri that resolves to the image that this CardDataImage will display.
* @return The Uri that resolves to the image this object represents.
*/
public Uri getImageUri() {
return mImageUri;
}
/**
* Sets the Uri that resolves to the image that this CardDataImage will display.
* @param imageUri A URI to this image (all types, including internet resources, are allowed).
*/
public void setImage(Uri imageUri) {
mImageUri = imageUri;
// Drop all other image sources, only the last one assigned is preserved
mImageBitmap = null;
mImageResourceId = 0;
}
/**
* Sets the image bitmap to the given bitmap.
*
* <p>When {@link org.cyanogenmod.launcher.home.api.cards.CardDataImage#publish(Context)} is
* called on this CardDataImage, this bitmap is saved to a cache within the internal storage for
* this application, to be accessed only by CM Home through a ContentProvider. If the same
* Bitmap is passed for any other image, the same cached image will be used. </p>
*
* @param bitmap The Bitmap to save for this CardDataImage.
*/
public void setImage(Bitmap bitmap) {
if (bitmap == null) return;
mImageBitmap = new WeakReference<Bitmap>(bitmap);
// Drop all other image sources, only the last one assigned is preserved
mImageResourceId = 0;
mImageUri = null;
}
/**
* Sets the image to the image that the given resource ID resolves to.
*
* <p>When {@link org.cyanogenmod.launcher.home.api.cards.CardDataImage#publish(Context)} is
* called on this CardDataImage, this image is saved to a cache within the internal storage for
* this application, to be accessed only by CM Home through a ContentProvider. If the same
* Bitmap is passed for any other image, the same cached image will be used. </p>
*
* @param resource The resource to save for this CardDataImage.
*/
public void setImage(int resource) {
mImageResourceId = resource;
// Drop all other image sources, only the last one assigned is preserved
mImageBitmap = null;
mImageUri = null;
}
/**
* Sets a String that will be used to identify this image.
*
* This may be used for a caption or title for this image.
* @param imageLabel A String that identifies this image.
*/
public void setImageLabel(String imageLabel) {
mImageLabel = imageLabel;
}
/**
* Retrieves the image label for this image.
*
* @see org.cyanogenmod.launcher.home.api.cards.CardDataImage#setImageLabel(java.lang.String)
* @return The currently set Image label String.
*/
public String getImageLabel() {
return mImageLabel;
}
@Override
protected ContentValues getContentValues() {
ContentValues values = new ContentValues();
values.put(CmHomeContract.CardDataImageContract.INTERNAL_ID_COL, getInternalId());
values.put(CmHomeContract.CardDataImageContract.CARD_DATA_ID_COL, getCardDataId());
values.put(CmHomeContract.CardDataImageContract.IMAGE_LABEL_COL, getImageLabel());
if (getImageUri() != null) {
values.put(CmHomeContract.CardDataImageContract.IMAGE_URI_COL, getImageUri().toString());
}
return values;
}
/**
* Retrieves all currently published CardDataImages for this application.
* @param context A Context of the application that published the CardDataImages originally.
* @return A list of all currently live and published CardDataImages for this application only.
*/
public static List<CardDataImage> getAllPublishedCardDataImages(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(CmHomeContract.CardDataImageContract.CONTENT_URI,
CmHomeContract.CardDataImageContract.PROJECTION_ALL,
null,
null,
null);
// Catching all Exceptions, since we can't be sure what the extension will do.
} catch (Exception e) {
Log.e(TAG, "Error querying for CardDatas, ContentProvider threw an exception for uri:" +
" " + CmHomeContract.CardDataImageContract.CONTENT_URI, e);
}
List<CardDataImage> allImages = getAllCardDataImagesFromCursor(cursor,
CmHomeContract.CardDataImageContract.CONTENT_URI.getAuthority());
cursor.close();
return allImages;
}
private static List<CardDataImage> getAllCardDataImagesFromCursor(Cursor cursor,
String authority) {
List<CardDataImage> allImages = new ArrayList<CardDataImage>();
if (cursor != null) {
while (cursor.moveToNext()) {
CardDataImage image = createFromCurrentCursorRow(cursor);
if (image != null) {
image.setAuthority(authority);
allImages.add(image);
}
}
}
return allImages;
}
public static CardDataImage createFromCurrentCursorRow(Cursor cursor, String authority)
throws IllegalArgumentException {
if (cursor == null) {
throw new IllegalArgumentException("'cursor' cannot be null!");
}
CardDataImage cardImage = createFromCurrentCursorRow(cursor);
if (cardImage != null && !TextUtils.isEmpty(authority)) {
cardImage.setAuthority(authority);
}
return cardImage;
}
private static CardDataImage createFromCurrentCursorRow(Cursor cursor) {
// Can't work with a cursor in this state
if (cursor.isClosed() || cursor.isAfterLast()) return null;
int cardDataId = cursor.getInt(
cursor.getColumnIndex(CmHomeContract.CardDataImageContract.CARD_DATA_ID_COL));
String imageUriString = cursor.getString(
cursor.getColumnIndex(CmHomeContract.CardDataImageContract.IMAGE_URI_COL));
int imageId = cursor
.getInt(cursor.getColumnIndex(CmHomeContract.CardDataImageContract._ID));
String internalId = cursor.getString(
cursor.getColumnIndex(CmHomeContract.CardDataImageContract.INTERNAL_ID_COL));
String imageLabel = cursor.getString(
cursor.getColumnIndex(CmHomeContract.CardDataImageContract.IMAGE_LABEL_COL));
if (!TextUtils.isEmpty(imageUriString)) {
CardDataImage image = new CardDataImage(cardDataId, Uri.parse(imageUriString));
image.setId(imageId);
image.setInternalId(internalId);
image.setImageLabel(imageLabel);
return image;
}
return null;
}
/**
* Retrieve a list of all currently published CardDataImages that have the {@link CardData}
* given by cardDataId as a parent.
* @param context The Context of the application that published the CardDataImages originally.
* @param cardDataId The ID of the {@link CardData} that is the parent of the CardDataImages
* being queried for.
* @return A list of CardDataImages that have the given {@link CardData} as a parent.
*/
public static List<CardDataImage> getPublishedCardDataImagesForCardDataId(Context context,
long cardDataId) {
return getPublishedCardDataImagesForCardDataId(context,
CmHomeContract.CardDataImageContract.CONTENT_URI,
cardDataId);
}
/**
* @hide
*
* Retrieve a list of currently published DataCardImages that have the CardData
* given by cardDataId as a parent.
*
* <b>This is intended to be an internal method. Please use one of the helper methods to
* retrieve CardDataImages.</b>
* @param context The Context of the application that published the CardDataImages originally.
* @param contentUri The ContentUri of the images being queried for.
* @param cardDataId The ID of the {@link CardData} that is the parent of the CardDataImages
* being queried for.
* @return A list of CardDataImages that have the given {@link CardData} as a parent.
*/
public static List<CardDataImage> getPublishedCardDataImagesForCardDataId(Context context,
Uri contentUri,
long cardDataId) {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(contentUri,
CmHomeContract.CardDataImageContract.PROJECTION_ALL,
CmHomeContract.CardDataImageContract.CARD_DATA_ID_COL + " = ?",
new String[]{Long.toString(cardDataId)},
null);
// Catching all Exceptions, since we can't be sure what the extension will do.
} catch (Exception e) {
Log.e(TAG, "Error querying for CardDatas, ContentProvider threw an exception for uri:" +
" " + contentUri, e);
}
List<CardDataImage> allImages = getAllCardDataImagesFromCursor(cursor,
contentUri.getAuthority());
cursor.close();
return allImages;
}
protected boolean hasValidContent() {
return mImageResourceId > 0 || mImageUri != null ||
(mImageBitmap != null && mImageBitmap.get() != null);
}
@Override
protected void publishSynchronous(Context context){
// Store the current id of the linked CardData, in case it has
// changed before publish.
if (mLinkedCardData != null) {
mCardDataId = mLinkedCardData.getId();
}
if (mImageResourceId != 0) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), mImageResourceId);
setImage(bitmap);
}
if (mImageBitmap != null && mImageBitmap.get() != null) {
Uri uri = CmHomeContentProvider.storeBitmapInCache(mImageBitmap.get(), context);
if (uri != null) {
setImage(uri);
}
}
super.publishSynchronous(context);
}
} |
package com.fsck.k9.controller;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.SearchSpecification;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Folder.OpenMode;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.mail.store.LocalStore.PendingCommand;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable
{
private static final int MAX_SMALL_MESSAGE_SIZE = Store.FETCH_BODY_SANE_SUGGESTED_SIZE;
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newFixedThreadPool(5);
public enum SORT_TYPE
{
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending)
{
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending)
{
if (ascending)
{
return ascendingToast;
}
else
{
return descendingToast;
}
}
public boolean isDefaultAscending()
{
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
private String createMessageKey(Account account, String folder, Message message)
{
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid)
{
return account.getUuid() + ":" + folder + ":" + uid;
}
private void suppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
String messKey = createMessageKey(account, folder, message);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, String uid)
{
if (account == null || folder == null || uid == null)
{
return;
}
String messKey = createMessageKey(account, folder, uid);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return false;
}
String messKey = createMessageKey(account, folder, message);
if (deletedUids.containsKey(messKey))
{
return true;
}
return false;
}
private MessagingController(Application application)
{
mApplication = application;
mThread = new Thread(this);
mThread.start();
if (memorizingListener != null)
{
addListener(memorizingListener);
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application)
{
if (inst == null)
{
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy()
{
return mBusy;
}
public void run()
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true)
{
String commandDescription = null;
try
{
Command command = mCommands.take();
if (command != null)
{
commandDescription = command.description;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
command.runnable.run();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") +
" Command '" + command.description + "' completed");
for (MessagingListener l : getListeners())
{
l.controllerCommandCompleted(mCommands.size() > 0);
}
if (command.listener != null && !getListeners().contains(command.listener))
{
command.listener.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground)
{
int retries = 10;
Exception e = null;
while (retries
{
try
{
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
}
catch (InterruptedException ie)
{
try
{
Thread.sleep(200);
}
catch (InterruptedException ne)
{
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener)
{
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener)
{
if (memorizingListener != null && listener != null)
{
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener)
{
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners()
{
return mListeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
for (MessagingListener l : getListeners())
{
l.listFoldersStarted(account);
}
if (listener != null)
{
listener.listFoldersStarted(account);
}
List<? extends Folder> localFolders = null;
try
{
Store localStore = account.getLocalStore();
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(new Folder[0]);
if (refreshRemote || localFolders == null || localFolders.size() == 0)
{
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners())
{
l.listFolders(account, folderArray);
}
if (listener != null)
{
listener.listFolders(account, folderArray);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, e.getMessage());
}
if (listener != null)
{
listener.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, null, e);
return;
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
if (listener != null)
{
listener.listFoldersFinished(account);
}
}
});
}
private void doRefreshRemote(final Account account, MessagingListener listener)
{
put("doRefreshRemote", listener, new Runnable()
{
public void run()
{
List<? extends Folder> localFolders = null;
try
{
Store store = account.getRemoteStore();
List<? extends Folder> remoteFolders = store.getPersonalNamespaces(false);
LocalStore localStore = account.getLocalStore();
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.size(); i < count; i++)
{
LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName());
if (!localFolder.exists())
{
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders.get(i).getName());
}
localFolders = localStore.getPersonalNamespaces(false);
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders)
{
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(K9.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName()))
{
continue;
}
if (!remoteFolderNames.contains(localFolder.getName()))
{
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(new Folder[0]);
for (MessagingListener l : getListeners())
{
l.listFolders(account, folderArray);
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, "");
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
}
});
}
/**
* List the messages in the local message store for the given folder asynchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
listLocalMessagesSynchronous(account, folder, listener);
}
});
}
/**
* List the messages in the local message store for the given folder synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesStarted(account, folder);
}
Folder localFolder = null;
MessageRetrievalListener retrievalListener =
new MessageRetrievalListener()
{
List<Message> pendingMessages = new ArrayList<Message>();
int totalDone = 0;
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(account, folder, message) == false)
{
pendingMessages.add(message);
totalDone++;
if (pendingMessages.size() > 10)
{
addPendingMessages();
}
}
else
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesRemoveMessage(account, folder, message);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesRemoveMessage(account, folder, message);
}
}
}
public void messagesFinished(int number)
{
addPendingMessages();
}
private void addPendingMessages()
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
pendingMessages.clear();
}
};
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
localFolder.getMessages(
retrievalListener,
false // Skip deleted messages
);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished");
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFinished(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener)
{
searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages,
searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener);
}
/**
* Find all messages in any local account which match the query 'query'
* @param folderNames TODO
* @param query
* @param listener
* @param searchAccounts TODO
* @param account TODO
* @param account
* @throws MessagingException
*/
public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate,
final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener)
{
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "searchLocalMessages ("
+ "accountUuids=" + Utility.combine(accountUuids, ',')
+ ", folderNames = " + Utility.combine(folderNames, ',')
+ ", messages.size() = " + (messages != null ? messages.length : null)
+ ", query = " + query
+ ", integrate = " + integrate
+ ", requiredFlags = " + Utility.combine(requiredFlags, ',')
+ ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',')
+ ")");
}
threadPool.execute(new Runnable()
{
public void run()
{
final AccountStats stats = new AccountStats();
final Set<String> accountUuidsSet = new HashSet<String>();
if (accountUuids != null)
{
for (String accountUuid : accountUuids)
{
accountUuidsSet.add(accountUuid);
}
}
final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext());
Account[] accounts = prefs.getAccounts();
List<LocalFolder> foldersToSearch = null;
boolean displayableOnly = false;
boolean noSpecialFolders = true;
for (final Account account : accounts)
{
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false)
{
continue;
}
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true)
{
displayableOnly = true;
noSpecialFolders = true;
}
else if (integrate == false && folderNames == null)
{
Account.Searchable searchableFolders = account.getSearchableFolders();
switch (searchableFolders)
{
case NONE:
continue;
case DISPLAYABLE:
displayableOnly = true;
break;
}
}
List<Message> messagesToSearch = null;
if (messages != null)
{
messagesToSearch = new LinkedList<Message>();
for (Message message : messages)
{
if (message.getFolder().getAccount().getUuid().equals(account.getUuid()))
{
messagesToSearch.add(message);
}
}
if (messagesToSearch.isEmpty())
{
continue;
}
}
if (listener != null)
{
listener.listLocalMessagesStarted(account, null);
}
if (integrate || displayableOnly || folderNames != null || noSpecialFolders)
{
List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>();
try
{
LocalStore store = account.getLocalStore();
List<? extends Folder> folders = store.getPersonalNamespaces(false);
Set<String> folderNameSet = null;
if (folderNames != null)
{
folderNameSet = new HashSet<String>();
for (String folderName : folderNames)
{
folderNameSet.add(folderName);
}
}
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
boolean include = true;
folder.refresh(prefs);
String localFolderName = localFolder.getName();
if (integrate)
{
include = localFolder.isIntegrate();
}
else
{
if (folderNameSet != null)
{
if (folderNameSet.contains(localFolderName) == false)
{
include = false;
}
}
// Never exclude the INBOX (see issue 1817)
else if (noSpecialFolders && !localFolderName.equals(K9.INBOX) && (
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName())))
{
include = false;
}
else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass()))
{
include = false;
}
}
if (include)
{
tmpFoldersToSearch.add(localFolder);
}
}
if (tmpFoldersToSearch.size() < 1)
{
continue;
}
foldersToSearch = tmpFoldersToSearch;
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me);
addErrorMessage(account, null, me);
}
}
MessageRetrievalListener retrievalListener = new MessageRetrievalListener()
{
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message) == false)
{
List<Message> messages = new ArrayList<Message>();
messages.add(message);
stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0;
stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0;
if (listener != null)
{
listener.listLocalMessagesAddMessages(account, null, messages);
}
}
}
public void messagesFinished(int number)
{
}
};
try
{
String[] queryFields = {"html_content","subject","sender_list"};
LocalStore localStore = account.getLocalStore();
localStore.searchForMessages(retrievalListener, queryFields
, query, foldersToSearch,
messagesToSearch == null ? null : messagesToSearch.toArray(new Message[0]),
requiredFlags, forbiddenFlags);
}
catch (Exception e)
{
if (listener != null)
{
listener.listLocalMessagesFailed(account, null, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (listener != null)
{
listener.listLocalMessagesFinished(account, null);
}
}
}
if (listener != null)
{
listener.searchStats(stats);
}
}
});
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
synchronizeMailbox(account, folder, listener, null);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts)
{
for (Account account : accounts)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
* @param providedRemoteFolder TODO
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder)
{
putBackground("synchronizeMailbox", listener, new Runnable()
{
public void run()
{
synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
* @param providedRemoteFolder TODO
*/
private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder)
{
Folder remoteFolder = null;
LocalFolder tLocalFolder = null;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxStarted(account, folder);
}
/*
* We don't ever sync the Outbox or errors folder
*/
if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName()))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
return;
}
Exception commandException = null;
try
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " +
account.getDescription());
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages)
{
localUidMap.put(message.getUid(), message);
}
if (providedRemoteFolder != null)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder);
remoteFolder = providedRemoteFolder;
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote store for " + folder);
Store remoteStore = account.getRemoteStore();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName()))
{
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
remoteFolder.open(OpenMode.READ_WRITE);
if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
if (visibleLimit < 1)
{
visibleLimit = K9.DEFAULT_VISIBLE_LIMIT;
}
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
// final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount);
final Date earliestDate = account.getEarliestPollDate();
if (remoteMessageCount > 0)
{
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null);
for (Message thisMess : remoteMessageArray)
{
Message localMessage = localUidMap.get(thisMess.getUid());
if (localMessage == null || localMessage.olderThan(earliestDate) == false)
{
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
remoteMessageArray = null;
}
else if (remoteMessageCount < 0)
{
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store or are too old
*/
if (account.syncRemoteDeletions())
{
for (Message localMessage : localMessages)
{
if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages);
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, unreadMessageCount);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages + " new messages");
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
finally
{
if (providedRemoteFolder == null && remoteFolder != null)
{
remoteFolder.close();
}
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException
{
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount != -1)
{
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
else
{
int unreadCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false)
{
unreadCount++;
}
}
localFolder.setUnreadMessageCount(unreadCount);
}
return localFolder.getUnreadMessageCount();
}
private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException
{
int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount();
if (remoteFlaggedMessageCount != -1)
{
localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount);
}
else
{
int flaggedCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false)
{
flaggedCount++;
}
}
localFolder.setFlaggedMessageCount(flaggedCount);
}
}
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final Date earliestDate = account.getEarliestPollDate();
if (earliestDate != null)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (message.isSet(Flag.DELETED))
{
syncFlagMessages.add(message);
}
else if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
}
else
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
if (message.isSet(Flag.DELETED))
{
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was marked deleted on server, skipping");
}
else
{
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE))
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (isMessageSuppressed(account, folder, message ))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+
"but just downloaded. "+
"The race condition means we wasted some bandwidth. Oh well.");
}
progress.incrementAndGet();
return;
}
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
return;
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
progress.incrementAndGet();
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
continue;
}
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE)
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
Message localMessage = localFolder.getMessage(message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}//for large messsages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages)
{
if (message.isSet(Flag.DELETED) == false)
{
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
else
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException
{
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED))
{
return false;
}
if (remoteMessage.isSet(Flag.DELETED))
{
if (localMessage.getFolder().getAccount().syncRemoteDeletions())
{
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
}
else
{
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED })
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag))
{
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
}
while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.addPendingCommand(command);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account)
{
putBackground("processPendingCommands", null, new Runnable()
{
public void run()
{
try
{
processPendingCommandsSynchronous(account);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, null, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException
{
LocalStore localStore = account.getLocalStore();
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0)
{
return;
}
for (MessagingListener l : getListeners())
{
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands)
{
processingCommand = command;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners())
{
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command))
{
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command))
{
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command))
{
processPendingSetFlagOld(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command))
{
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command))
{
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command))
{
processPendingMoveOrCopyOld(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command))
{
processPendingEmptyTrash(command, account);
}
else if (PENDING_COMMAND_EXPUNGE.equals(command.command))
{
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
finally
{
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
finally
{
for (MessagingListener l : getListeners())
{
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null)
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null)
{
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
localMessage
}
, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else
{
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0)
{
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.X_DESTROYED, true);
}
else
{
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
if (remoteDate != null)
{
remoteMessage.setFlag(Flag.DELETED, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[])
{
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
try
{
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
Store remoteStore = account.getRemoteStore();
remoteSrcFolder = remoteStore.getFolder(srcFolder);
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteSrcFolder.getMessage(uid));
}
}
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName))
{
destFolderName = null;
}
remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName);
}
else
{
remoteDestFolder = remoteStore.getFolder(destFolder);
if (isCopy)
{
remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
}
if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
}
finally
{
if (remoteSrcFolder != null)
{
remoteSrcFolder.close();
}
if (remoteDestFolder != null)
{
remoteDestFolder.close();
}
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids)
{
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.size() == 0)
{
return;
}
remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Folder remoteFolder = null;
try
{
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null)
{
return;
}
remoteMessage.setFlag(flag, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
private void queueExpunge(final Account account, final String folderName)
{
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException
{
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = account.getRemoteStore();
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null)
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy)
{
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException
{
String folder = command.arguments[0];
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners())
{
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, 0);
}
if (account.getErrorFolderName().equals(folder))
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true);
remoteFolder.close();
}
catch (UnsupportedOperationException uoe)
{
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, String subject, Throwable t)
{
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
if (subject == null) {
subject = getRootCauseMessage(t);
}
addErrorMessage(account, subject, baos.toString());
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(
final Message[] messages,
final Flag flag,
final boolean newState)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
String[] uids = new String[messages.size()];
for (int i = 0; i < messages.size(); i++)
{
uids[i] = messages.get(i).getUid();
}
setFlag(account, folder.getName(), uids, flag, newState);
}
});
}
public void setFlag(
final Account account,
final String folderName,
final String[] uids,
final Flag flag,
final boolean newState)
{
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
ArrayList<Message> messages = new ArrayList<Message>();
for (int i = 0; i < uids.length; i++)
{
String uid = uids[i];
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folderName))
{
sendCount.remove(uid);
}
Message msg = localFolder.getMessage(uid);
if (msg != null)
{
messages.add(msg);
}
}
localFolder.setFlags(messages.toArray(new Message[0]), new Flag[] {flag}, newState);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount());
}
if (account.getErrorFolderName().equals(folderName))
{
return;
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException(me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}//setMesssageFlag
public void clearAllPending(final Account account)
{
try
{
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = account.getLocalStore();
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, null, me);
}
}
private void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener)
{
put("loadMessageForViewRemote", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
}
else
{
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
finally
{
if (remoteFolder!=null)
{
remoteFolder.close();
}
if (localFolder!=null)
{
localFolder.close();
}
}//finally
}//run
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewStarted(account, folder, uid);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
LocalMessage message = (LocalMessage)localFolder.getMessage(uid);
if (message==null
|| message.getId()==0)
{
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
if (!message.isSet(Flag.SEEN))
{
message.setFlag(Flag.SEEN, true);
setFlag(new Message[] { message }, Flag.SEEN, true);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
loadMessageForViewRemote(account, folder, uid, listener);
if (!message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
localFolder.close();
return;
}
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
message
}, fp, null);
localFolder.close();
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
}
});
}
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener)
{
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try
{
if (part.getBody() != null)
{
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, false);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me)
{
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, true);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
put("loadAttachment", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments)
{
attachment.setBody(null);
}
Store remoteStore = account.getRemoteStore();
localFolder = localStore.getFolder(message.getFolder().getName());
remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
//FIXME: This is an ugly hack that won't be needed once the Message objects have been united.
Message remoteMessage = remoteFolder.getMessage(message.getUid());
remoteMessage.setBody(message.getBody());
remoteFolder.fetchPart(remoteMessage, part, null);
localFolder.updateMessage((LocalMessage)message);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Exception loading attachment", me);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
if (listener != null)
{
listener.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, null, me);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, null);
}
catch (Exception e)
{
/*
for (MessagingListener l : getListeners())
{
// TODO general failed
}
*/
addErrorMessage(account, null, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener)
{
putBackground("sendPendingMessages", listener, new Runnable()
{
public void run()
{
sendPendingMessagesSynchronous(account);
}
});
}
public boolean messagesPendingSend(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return false;
}
localFolder.open(OpenMode.READ_WRITE);
int localMessages = localFolder.getMessageCount();
if (localMessages > 0)
{
return true;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return;
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
int progress = 0;
int todo = localMessages.length;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account);
for (Message message : localMessages)
{
if (message.isSet(Flag.DELETED))
{
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try
{
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS)
{
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try
{
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
if (K9.FOLDER_NONE.equals(account.getSentFolderName()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message");
message.setFlag(Flag.DELETED, true);
}
else
{
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
localSentFolder.getName(),
message.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
}
catch (Exception e)
{
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
if (localFolder.getMessageCount() == 0)
{
localFolder.delete(false);
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void getAccountStats(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
try
{
AccountStats stats = account.getStats(context);
l.accountStatusChanged(account, stats);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
}
};
put("getAccountStats:" + account.getDescription(), l, unreadRunnable);
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
int unreadMessageCount = 0;
try
{
Folder localFolder = account.getLocalStore().getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public boolean isMoveCapable(Message message)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
return true;
}
else
{
return false;
}
}
public boolean isCopyCapable(Message message)
{
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
for (Message message : messages)
{
suppressMessage(account, srcFolder, message);
}
putBackground("moveMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener);
}
});
}
public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
putBackground("copyMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener);
}
});
}
public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false))
{
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false))
{
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
List<String> uids = new LinkedList<String>();
for (Message message : inMessages)
{
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
uids.add(uid);
}
}
Message[] messages = localSrcFolder.getMessages(uids.toArray(new String[0]), null);
if (messages.length > 0)
{
Map<String, Message> origUidMap = new HashMap<String, Message>();
for (Message message : messages)
{
origUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy)
{
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(messages, fp, null);
localSrcFolder.copyMessages(messages, localDestFolder);
}
else
{
localSrcFolder.moveMessages(messages, localDestFolder);
for (String origUid : origUidMap.keySet())
{
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(new String[0]));
}
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener)
{
putBackground("expunge", null, new Runnable()
{
public void run()
{
queueExpunge(account, folder);
}
});
}
public void deleteDraft(final Account account, String uid)
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message != null)
{
deleteMessages(new Message[] { message }, null);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void deleteMessages(final Message[] messages, final MessagingListener listener)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
for (Message message : messages)
{
suppressMessage(account, folder.getName(), message);
}
putBackground("deleteMessages", null, new Runnable()
{
public void run()
{
deleteMessagesSynchronous(account, folder.getName(), messages.toArray(new Message[0]), listener);
}
});
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages,
MessagingListener listener)
{
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try
{
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages)
{
if (listener != null)
{
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners())
{
l.messageDeleted(account, folder, message);
}
}
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
else
{
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (localTrashFolder.exists() == false)
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists() == true)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount());
if (localTrashFolder != null)
{
l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount());
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
if (folder.equals(account.getOutboxFolderName()))
{
for (Message message : messages)
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
}
else
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
for (String uid : uids)
{
unsuppressMessage(account, folder, uid);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (localTrashFolder != null)
{
localTrashFolder.close();
}
}
}
private String[] getUidsFromMessages(Message[] messages)
{
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++)
{
uids[i] = messages[i].getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException
{
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try
{
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
public void emptyTrash(final Account account, MessagingListener listener)
{
putBackground("emptyTrash", listener, new Runnable()
{
public void run()
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
for (MessagingListener l : getListeners())
{
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null)
{
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null)
{
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener)
{
TracingWakeLock twakeLock = null;
if (useManualWakeLock)
{
TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final TracingWakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners())
{
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable()
{
public void run()
{
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null)
{
accounts = new Account[]
{
account
};
}
else
{
accounts = prefs.getAccounts();
}
for (final Account account : accounts)
{
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
account.setRingNotified(false);
putBackground("sendPending " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (messagesPendingSend(account))
{
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never sync a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aSyncMode, fSyncClass))
{
// Do not sync folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
continue;
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder tLocalFolder = null;
try
{
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName(), listener, null);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
}
);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
putBackground("clear notification flag for " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription());
account.setRingNotified(false);
try
{
AccountStats stats = account.getStats(context);
int unreadMessageCount = stats.unreadMessageCount;
if (unreadMessageCount == 0)
{
notifyAccountCancel(context, account);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
}
}
);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, null, e);
}
putBackground("finalize sync", null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null)
{
wakeLock.release();
}
for (MessagingListener l : getListeners())
{
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e);
}
}
});
}
public void recreate(final Account account, final MessagingListener ml)
{
putBackground("recreate:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.recreate();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e);
}
}
});
}
/** Creates a notification of new email messages
* ringtone, lights, and vibration to be played
*/
private boolean notifyAccount(Context context, Account account, Message message)
{
int unreadMessageCount = 0;
try
{
AccountStats stats = account.getStats(context);
unreadMessageCount = stats.unreadMessageCount;
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
// Do not notify if the user does not have notifications
// enabled or if the message has been read
if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN))
{
return false;
}
Folder folder = message.getFolder();
if (folder != null)
{
// No notification for new messages in Trash, Drafts, or Sent folder.
// But do notify if it's the INBOX (see issue 1817).
String folderName = folder.getName();
if (!K9.INBOX.equals(folderName) &&
(account.getTrashFolderName().equals(folderName)
|| account.getDraftsFolderName().equals(folderName)
|| account.getSentFolderName().equals(folderName)))
{
return false;
}
}
// If we have a message, set the notification to "<From>: <Subject>"
StringBuffer messageNotice = new StringBuffer();
try
{
if (message != null && message.getFrom() != null)
{
Address[] fromAddrs = message.getFrom();
String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null;
String subject = message.getSubject();
if (subject == null)
{
subject = context.getString(R.string.general_no_subject);
}
if (from != null)
{
// Show From: address by default
if (account.isAnIdentity(fromAddrs) == false)
{
messageNotice.append(from + ": " + subject);
}
// show To: if the message was sent from me
else
{
// Do not notify of mail from self if !isNotifySelfNewMail
if (!account.isNotifySelfNewMail())
{
return false;
}
Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null;
if (to != null)
{
messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject);
}
else
{
messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject);
}
}
}
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e);
}
// If we could not set a per-message notification, revert to a default message
if (messageNotice.length() == 0)
{
messageNotice.append(context.getString(R.string.notification_new_title));
}
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis());
notif.number = unreadMessageCount;
Intent i = FolderList.actionHandleNotification(context, account, account.getAutoExpandFolderName());
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, account.getDescription());
notif.setLatestEventInfo(context, accountNotice, messageNotice, pi);
// Only ring or vibrate if we have not done so already on this
// account and fetch
if (!account.isRingNotified())
{
account.setRingNotified(true);
if (account.isRing())
{
String ringtone = account.getRingtone();
notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
}
if (account.isVibrate())
{
int times = account.getVibrateTimes();
long[] pattern1 = new long[] {100,200};
long[] pattern2 = new long[] {100,500};
long[] pattern3 = new long[] {200,200};
long[] pattern4 = new long[] {200,500};
long[] pattern5 = new long[] {500,500};
long[] src = null;
switch (account.getVibratePattern())
{
case 1:
src = pattern1;
break;
case 2:
src = pattern2;
break;
case 3:
src = pattern3;
break;
case 4:
src = pattern4;
break;
case 5:
src = pattern5;
break;
default:
notif.defaults |= Notification.DEFAULT_VIBRATE;
break;
}
if (src != null)
{
long[] dest = new long[src.length * times];
for (int n = 0; n < times; n++)
{
System.arraycopy(src, 0, dest, n * src.length, src.length);
}
notif.vibrate = dest;
}
}
}
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
notif.audioStreamType = AudioManager.STREAM_NOTIFICATION;
notifMgr.notify(account.getAccountNumber(), notif);
return true;
}
/** Cancel a notification of new email messages */
public void notifyAccountCancel(Context context, Account account)
{
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(account.getAccountNumber());
notifMgr.cancel(-1000 - account.getAccountNumber());
}
public Message saveDraft(final Account account, final Message message)
{
Message localMessage = null;
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[]
{
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, null, e);
}
return localMessage;
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode)
{
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS))
{
return true;
}
else
{
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
class Command implements Comparable<Command>
{
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
@Override
public int compareTo(Command other)
{
if (other.isForeground == true && isForeground == false)
{
return 1;
}
else if (other.isForeground == false && isForeground == true)
{
return -1;
}
else
{
return (sequence - other.sequence);
}
}
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
public Collection<Pusher> getPushers()
{
return pushers.values();
}
public boolean setupPushing(final Account account)
{
try
{
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null)
{
previousPusher.stop();
}
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
if (folder.getName().equals(account.getErrorFolderName())
|| folder.getName().equals(account.getOutboxFolderName()))
{
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which should never be pushed");
continue;
}
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never push a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aPushMode, fPushClass))
{
// Do not push folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (names.size() > 0)
{
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try
{
Store store = account.getRemoteStore();
if (store.isPushCapable() == false)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
if (pusher != null)
{
Pusher oldPusher = pushers.putIfAbsent(account, pusher);
if (oldPusher == null)
{
pusher.start(names);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
}
else
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext())
{
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder= localStore.getFolder(remoteFolder.getName());
localFolder.open(OpenMode.READ_WRITE);
account.setRingNotified(false);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size());
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0)
{
notifyAccountCancel(mApplication, account);
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
}
catch (Exception e)
{
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try
{
localFolder.setStatus(errorMessage);
}
catch (Exception se)
{
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to close localFolder", e);
}
}
latch.countDown();
}
}
});
try
{
latch.await();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
enum MemorizingState { STARTED, FINISHED, FAILED };
class Memory
{
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName)
{
account = nAccount;
folderName = nFolderName;
}
String getKey()
{
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName)
{
return taccount.getDescription() + ":" + tfolderName;
}
class MemorizingListener extends MessagingListener
{
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName)
{
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null)
{
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
@Override
public synchronized void synchronizeMailboxStarted(Account account, String folder)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
@Override
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other)
{
if (other != null)
{
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values())
{
if (memory.syncingState != null)
{
switch (memory.syncingState)
{
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null)
{
switch (memory.sendingState)
{
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null)
{
switch (memory.pushingState)
{
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
}
}
if (memory.processingState != null)
{
switch (memory.processingState)
{
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null)
{
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null)
{
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null)
{
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null)
{
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
}
else
{
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0)
{
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active)
{
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
@Override
public synchronized void sendPendingMessagesStarted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void sendPendingMessagesCompleted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
@Override
public synchronized void sendPendingMessagesFailed(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
@Override
public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total)
{
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
@Override
public synchronized void pendingCommandsProcessing(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void pendingCommandsFinished(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
@Override
public synchronized void pendingCommandStarted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
@Override
public synchronized void pendingCommandCompleted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
private void actOnMessages(Message[] messages, MessageActor actor)
{
Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>();
for (Message message : messages)
{
Folder folder = message.getFolder();
Account account = folder.getAccount();
Map<Folder, List<Message>> folderMap = accountMap.get(account);
if (folderMap == null)
{
folderMap = new HashMap<Folder, List<Message>>();
accountMap.put(account, folderMap);
}
List<Message> messageList = folderMap.get(folder);
if (messageList == null)
{
messageList = new LinkedList<Message>();
folderMap.put(folder, messageList);
}
messageList.add(message);
}
for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet())
{
Account account = entry.getKey();
//account.refresh(Preferences.getPreferences(K9.app));
Map<Folder, List<Message>> folderMap = entry.getValue();
for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet())
{
Folder folder = folderEntry.getKey();
List<Message> messageList = folderEntry.getValue();
actor.act(account, folder, messageList);
}
}
}
interface MessageActor
{
public void act(final Account account, final Folder folder, final List<Message> messages);
}
} |
package org.jsimpledb;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.core.DeleteAction;
import org.jsimpledb.core.FieldType;
import org.jsimpledb.core.ListField;
import org.jsimpledb.core.MapField;
import org.jsimpledb.core.SetField;
import org.jsimpledb.core.UnknownFieldException;
import org.jsimpledb.schema.SchemaCompositeIndex;
import org.jsimpledb.schema.SchemaField;
import org.jsimpledb.schema.SchemaObjectType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Information about a Java class that is used to represent a specific JSimpleDB object type.
*
* @param <T> the Java class
*/
public class JClass<T> extends JSchemaObject {
final Logger log = LoggerFactory.getLogger(this.getClass());
final Class<T> type;
final ClassGenerator<T> classGenerator;
final TreeMap<Integer, JField> jfields = new TreeMap<>(); // does not include sub-fields
final TreeMap<String, JField> jfieldsByName = new TreeMap<>(); // does not include sub-fields
final TreeMap<Integer, JCompositeIndex> jcompositeIndexes = new TreeMap<>();
final TreeMap<String, JCompositeIndex> jcompositeIndexesByName = new TreeMap<>();
final ArrayList<JSimpleField> uniqueConstraintFields = new ArrayList<>();
Set<OnCreateScanner<T>.MethodInfo> onCreateMethods;
Set<OnDeleteScanner<T>.MethodInfo> onDeleteMethods;
Set<OnChangeScanner<T>.MethodInfo> onChangeMethods;
Set<OnValidateScanner<T>.MethodInfo> onValidateMethods;
ArrayList<OnVersionChangeScanner<T>.MethodInfo> onVersionChangeMethods;
boolean requiresDefaultValidation;
boolean hasSnapshotCreateOrChangeMethods;
AnnotatedElement elementRequiringJSR303Validation;
int[] simpleFieldStorageIds;
JClass(JSimpleDB jdb, String name, int storageId, Class<T> type) {
super(jdb, name, storageId, "object type `" + name + "' (" + type + ")");
Preconditions.checkArgument(name != null, "null name");
this.type = type;
this.classGenerator = new ClassGenerator<>(this);
}
// Get class generator
ClassGenerator<T> getClassGenerator() {
return this.classGenerator;
}
// Public API
/**
* Get the Java model object type associated with this instance.
*
* @return associated Java type
*/
public Class<T> getType() {
return this.type;
}
/**
* Get all {@link JField}'s associated with this instance, indexed by storage ID.
*
* @return read-only mapping from storage ID to {@link JClass}
*/
public SortedMap<Integer, JField> getJFieldsByStorageId() {
return Collections.unmodifiableSortedMap(this.jfields);
}
/**
* Get all {@link JField}'s associated with this instance, indexed by name.
*
* @return read-only mapping from storage ID to {@link JClass}
*/
public SortedMap<String, JField> getJFieldsByName() {
return Collections.unmodifiableSortedMap(this.jfieldsByName);
}
/**
* Get the {@link JField} in this instance associated with the specified storage ID, cast to the given type.
*
* @param storageId field storage ID
* @param type required type
* @param <T> expected field type
* @return {@link JField} in this instance corresponding to {@code storageId}
* @throws UnknownFieldException if {@code storageId} does not correspond to any field in this instance
* @throws UnknownFieldException if the field is not an instance of of {@code type}
*/
public <T extends JField> T getJField(int storageId, Class<T> type) {
Preconditions.checkArgument(type != null, "null type");
final JField jfield = this.jfields.get(storageId);
if (jfield == null)
throw new UnknownFieldException(storageId, "object type `" + this.name + "' has no field with storage ID " + storageId);
try {
return type.cast(jfield);
} catch (ClassCastException e) {
throw new UnknownFieldException(storageId, "object type `" + this.name + "' has no field with storage ID "
+ storageId + " of type " + type.getName() + " (found " + jfield + " instead)");
}
}
// Internal methods
void createFields(JSimpleDB jdb) {
// Auto-generate properties?
final JSimpleClass jsimpleClass = this.type.getAnnotation(JSimpleClass.class);
// Scan for Simple and Counter fields
final JFieldScanner<T> simpleFieldScanner = new JFieldScanner<>(this, jsimpleClass);
for (JFieldScanner<T>.MethodInfo info : simpleFieldScanner.findAnnotatedMethods()) {
// Get info
final org.jsimpledb.annotation.JField annotation = info.getAnnotation();
final Method getter = info.getMethod();
final String description = simpleFieldScanner.getAnnotationDescription() + " annotation on method " + getter;
final String fieldName = this.getFieldName(annotation.name(), info, description);
final TypeToken<?> fieldTypeToken = TypeToken.of(this.type).resolveType(getter.getGenericReturnType());
if (this.log.isTraceEnabled())
this.log.trace("found " + description);
// Get storage ID
int storageId = annotation.storageId();
if (storageId == 0)
storageId = jdb.getStorageIdGenerator(annotation, getter).generateFieldStorageId(getter, fieldName);
// Handle Counter fields
if (fieldTypeToken.equals(TypeToken.of(Counter.class))) {
// Sanity check annotation
if (annotation.type().length() != 0)
throw new IllegalArgumentException("invalid " + description + ": counter fields must not specify a type");
if (annotation.indexed())
throw new IllegalArgumentException("invalid " + description + ": counter fields cannot be indexed");
// Create counter field
final JCounterField jfield = new JCounterField(this.jdb, fieldName, storageId,
"counter field `" + fieldName + "' of object type `" + this.name + "'", getter);
// Add field
this.addField(jfield);
continue;
}
// Find corresponding setter method
final Method setter;
try {
setter = Util.findJFieldSetterMethod(this.type, getter);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid " + description + ": " + e.getMessage());
}
// Create simple field
final JSimpleField jfield = this.createSimpleField(description, fieldTypeToken,
fieldName, storageId, annotation, getter, setter, "field `" + fieldName + "' of object type `" + this.name + "'");
// Add field
this.addField(jfield);
// Remember unique constraint fields
if (jfield.unique)
this.uniqueConstraintFields.add(jfield);
}
// Scan for Set fields
final JSetFieldScanner<T> setFieldScanner = new JSetFieldScanner<>(this, jsimpleClass);
for (JSetFieldScanner<T>.MethodInfo info : setFieldScanner.findAnnotatedMethods()) {
// Get info
final org.jsimpledb.annotation.JSetField annotation = info.getAnnotation();
final org.jsimpledb.annotation.JField elementAnnotation = annotation.element();
final Method getter = info.getMethod();
final String description = setFieldScanner.getAnnotationDescription() + " annotation on method " + getter;
final String fieldName = this.getFieldName(annotation.name(), info, description);
if (this.log.isTraceEnabled())
this.log.trace("found " + description);
// Get storage ID's
int storageId = annotation.storageId();
if (storageId == 0)
storageId = jdb.getStorageIdGenerator(annotation, getter).generateFieldStorageId(getter, fieldName);
int elementStorageId = elementAnnotation.storageId();
if (elementStorageId == 0) {
elementStorageId = jdb.getStorageIdGenerator(elementAnnotation, getter)
.generateSetElementStorageId(getter, fieldName);
}
// Get element type (the raw return type has already been validated by the annotation scanner)
final TypeToken<?> elementType = TypeToken.of(this.type).resolveType(this.getParameterType(description, getter, 0));
// Create element sub-field
final JSimpleField elementField = this.createSimpleField("element() property of " + description, elementType,
SetField.ELEMENT_FIELD_NAME, elementStorageId, elementAnnotation, null, null,
"element field of set field `" + fieldName + "' in object type `" + this.name + "'");
// Create set field
final JSetField jfield = new JSetField(this.jdb, fieldName, storageId, elementField,
"set field `" + fieldName + "' in object type `" + this.name + "'", getter);
elementField.parent = jfield;
// Add field
this.addField(jfield);
}
// Scan for List fields
final JListFieldScanner<T> listFieldScanner = new JListFieldScanner<>(this, jsimpleClass);
for (JListFieldScanner<T>.MethodInfo info : listFieldScanner.findAnnotatedMethods()) {
// Get info
final org.jsimpledb.annotation.JListField annotation = info.getAnnotation();
final org.jsimpledb.annotation.JField elementAnnotation = annotation.element();
final Method getter = info.getMethod();
final String description = listFieldScanner.getAnnotationDescription() + " annotation on method " + getter;
final String fieldName = this.getFieldName(annotation.name(), info, description);
if (this.log.isTraceEnabled())
this.log.trace("found " + description);
// Get storage ID's
int storageId = annotation.storageId();
if (storageId == 0)
storageId = jdb.getStorageIdGenerator(annotation, getter).generateFieldStorageId(getter, fieldName);
int elementStorageId = elementAnnotation.storageId();
if (elementStorageId == 0) {
elementStorageId = jdb.getStorageIdGenerator(elementAnnotation, getter)
.generateListElementStorageId(getter, fieldName);
}
// Get element type (the raw return type has already been validated by the annotation scanner)
final TypeToken<?> elementType = TypeToken.of(this.type).resolveType(this.getParameterType(description, getter, 0));
// Create element sub-field
final JSimpleField elementField = this.createSimpleField("element() property of " + description, elementType,
ListField.ELEMENT_FIELD_NAME, elementStorageId, elementAnnotation, null, null,
"element field of list field `" + fieldName + "' in object type `" + this.name + "'");
// Create list field
final JListField jfield = new JListField(this.jdb, fieldName, storageId, elementField,
"list field `" + fieldName + "' in object type `" + this.name + "'", getter);
elementField.parent = jfield;
// Add field
this.addField(jfield);
}
// Scan for Map fields
final JMapFieldScanner<T> mapFieldScanner = new JMapFieldScanner<>(this, jsimpleClass);
for (JMapFieldScanner<T>.MethodInfo info : mapFieldScanner.findAnnotatedMethods()) {
// Get info
final org.jsimpledb.annotation.JMapField annotation = info.getAnnotation();
final org.jsimpledb.annotation.JField keyAnnotation = annotation.key();
final org.jsimpledb.annotation.JField valueAnnotation = annotation.value();
final Method getter = info.getMethod();
final String description = mapFieldScanner.getAnnotationDescription() + " annotation on method " + getter;
final String fieldName = this.getFieldName(annotation.name(), info, description);
if (this.log.isTraceEnabled())
this.log.trace("found " + description);
// Get storage ID's
int storageId = annotation.storageId();
if (storageId == 0)
storageId = jdb.getStorageIdGenerator(annotation, getter).generateFieldStorageId(getter, fieldName);
int keyStorageId = keyAnnotation.storageId();
if (keyStorageId == 0)
keyStorageId = jdb.getStorageIdGenerator(keyAnnotation, getter).generateMapKeyStorageId(getter, fieldName);
int valueStorageId = valueAnnotation.storageId();
if (valueStorageId == 0)
valueStorageId = jdb.getStorageIdGenerator(valueAnnotation, getter).generateMapValueStorageId(getter, fieldName);
// Get key and value types (the raw return type has already been validated by the annotation scanner)
final TypeToken<?> keyType = TypeToken.of(this.type).resolveType(this.getParameterType(description, getter, 0));
final TypeToken<?> valueType = TypeToken.of(this.type).resolveType(this.getParameterType(description, getter, 1));
// Create key and value sub-fields
final JSimpleField keyField = this.createSimpleField("key() property of " + description, keyType,
MapField.KEY_FIELD_NAME, keyStorageId, keyAnnotation, null, null,
"key field of map field `" + fieldName + "' in object type `" + this.name + "'");
final JSimpleField valueField = this.createSimpleField("value() property of " + description, valueType,
MapField.VALUE_FIELD_NAME, valueStorageId, valueAnnotation, null, null,
"value field of map field `" + fieldName + "' in object type `" + this.name + "'");
// Create map field
final JMapField jfield = new JMapField(this.jdb, fieldName, storageId, keyField, valueField,
"map field `" + fieldName + "' in object type `" + this.name + "'", getter);
keyField.parent = jfield;
valueField.parent = jfield;
// Add field
this.addField(jfield);
}
// Verify that the generated class will not have any remaining abstract methods
final Map<MethodKey, Method> abstractMethods = Util.findAbstractMethods(this.type);
for (JField jfield : this.jfields.values()) {
abstractMethods.remove(new MethodKey(jfield.getter));
if (jfield instanceof JSimpleField)
abstractMethods.remove(new MethodKey(((JSimpleField)jfield).setter));
}
for (Method method : JObject.class.getDeclaredMethods())
abstractMethods.remove(new MethodKey(method));
if (!abstractMethods.isEmpty()) {
throw new IllegalArgumentException("the @JSimpleClass-annotated type " + this.type.getName() + " is invalid because"
+ " " + abstractMethods.size() + " abstract method(s) remain unimplemented: "
+ abstractMethods.values().toString().replaceAll("^\\[(.*)\\]$", "$1"));
}
// Calculate which fields require default validation
this.jfields.values()
.forEach(JField::calculateRequiresDefaultValidation);
// Gather simple field storage ID's
this.simpleFieldStorageIds = Ints.toArray(this.jfields.values().stream()
.filter(jfield -> jfield instanceof JSimpleField)
.map(jfield -> jfield.storageId)
.collect(Collectors.toList()));
}
void addCompositeIndex(JSimpleDB jdb, org.jsimpledb.annotation.JCompositeIndex annotation) {
// Get info
final String indexName = annotation.name();
// Resolve field names
final String[] fieldNames = annotation.fields();
final JSimpleField[] indexFields = new JSimpleField[fieldNames.length];
final int[] indexFieldStorageIds = new int[fieldNames.length];
final HashSet<String> seenFieldNames = new HashSet<>();
for (int i = 0; i < fieldNames.length; i++) {
final String fieldName = fieldNames[i];
if (!seenFieldNames.add(fieldName))
throw this.invalidIndex(annotation, "field `" + fieldName + "' appears more than once");
final JField jfield = this.jfieldsByName.get(fieldName);
if (!(jfield instanceof JSimpleField)) {
throw this.invalidIndex(annotation, "field `" + fieldName + "' "
+ (jfield != null ? "is not a simple field" : "not found"));
}
indexFields[i] = (JSimpleField)jfield;
indexFieldStorageIds[i] = jfield.storageId;
}
// Get storage ID
int storageId = annotation.storageId();
if (storageId == 0) {
storageId = jdb.getStorageIdGenerator(annotation, type)
.generateCompositeIndexStorageId(this.type, indexName, indexFieldStorageIds);
}
// Create and add index
final JCompositeIndex index = new JCompositeIndex(this.jdb, indexName, storageId, indexFields);
if (this.jcompositeIndexes.put(index.storageId, index) != null)
throw this.invalidIndex(annotation, "duplicate use of storage ID " + index.storageId);
if (this.jcompositeIndexesByName.put(index.name, index) != null)
throw this.invalidIndex(annotation, "duplicate use of composite index name `" + index.name + "'");
}
void scanAnnotations() {
this.onCreateMethods = new OnCreateScanner<>(this).findAnnotatedMethods();
this.onDeleteMethods = new OnDeleteScanner<>(this).findAnnotatedMethods();
this.onChangeMethods = new OnChangeScanner<>(this).findAnnotatedMethods();
this.onValidateMethods = new OnValidateScanner<>(this).findAnnotatedMethods();
final OnVersionChangeScanner<T> onVersionChangeScanner = new OnVersionChangeScanner<>(this);
this.onVersionChangeMethods = new ArrayList<>(onVersionChangeScanner.findAnnotatedMethods());
Collections.sort(this.onVersionChangeMethods, onVersionChangeScanner);
// Determine if we need to enable notifications when copying into snapshot transactions
for (OnCreateScanner<T>.MethodInfo methodInfo : this.onCreateMethods) {
if (methodInfo.getAnnotation().snapshotTransactions()) {
this.hasSnapshotCreateOrChangeMethods = true;
break;
}
}
for (OnChangeScanner<T>.MethodInfo methodInfo : this.onChangeMethods) {
if (methodInfo.getAnnotation().snapshotTransactions()) {
this.hasSnapshotCreateOrChangeMethods = true;
break;
}
}
}
void calculateValidationRequirement() {
// Check for use of JSR 303 annotations
this.elementRequiringJSR303Validation = Util.hasValidation(this.type);
// Check for JSR 303 or @OnValidate annotations in default group
if (Util.requiresDefaultValidation(this.type)) {
this.requiresDefaultValidation = true;
return;
}
// Check for any uniqueness constraints
if (!this.uniqueConstraintFields.isEmpty()) {
this.requiresDefaultValidation = true;
return;
}
}
@Override
SchemaObjectType toSchemaItem(JSimpleDB jdb) {
final SchemaObjectType schemaObjectType = new SchemaObjectType();
this.initialize(jdb, schemaObjectType);
for (JField field : this.jfields.values()) {
final SchemaField schemaField = field.toSchemaItem(jdb);
schemaObjectType.getSchemaFields().put(schemaField.getStorageId(), schemaField);
}
for (JCompositeIndex index : this.jcompositeIndexes.values()) {
final SchemaCompositeIndex schemaIndex = index.toSchemaItem(jdb);
schemaObjectType.getSchemaCompositeIndexes().put(index.getStorageId(), schemaIndex);
}
return schemaObjectType;
}
private IllegalArgumentException invalidIndex(org.jsimpledb.annotation.JCompositeIndex annotation, String message) {
return new IllegalArgumentException("invalid @JCompositeIndex annotation for index `"
+ annotation.name() + "' on " + this.type + ": " + message);
}
// Add new JField (and sub-fields, if any), checking for name and storage ID conflicts
private void addField(JField jfield) {
// Check for storage ID conflict; note we can get this legitimately when a field is declared only
// in supertypes, where two of the supertypes are mutually unassignable from each other. In that
// case, verify that the generated field is the same.
JField other = this.jfields.get(jfield.storageId);
if (other != null) {
// If the descriptions differ, no need to give any more details
if (!other.toString().equals(jfield.toString())) {
throw new IllegalArgumentException("illegal duplicate use of storage ID "
+ jfield.storageId + " for both " + other + " and " + jfield);
}
// Check whether the fields are exactly the same; if not, there is a conflict
if (!other.isSameAs(jfield)) {
throw new IllegalArgumentException("two or more methods defining " + jfield + " conflict: "
+ other.getter + " and " + jfield.getter);
}
// OK - they are the same thing
return;
}
this.jfields.put(jfield.storageId, jfield);
// Check for name conflict
if ((other = this.jfieldsByName.get(jfield.name)) != null)
throw new IllegalArgumentException("illegal duplicate use of field name `" + jfield.name + "' in " + this);
this.jfieldsByName.put(jfield.name, jfield);
jfield.parent = this;
// Logging
if (this.log.isTraceEnabled())
this.log.trace("added " + jfield + " to object type `" + this.name + "'");
}
// Get field name, deriving it from the getter property name if necessary
private String getFieldName(String fieldName, AnnotationScanner<T, ?>.MethodInfo info, String description) {
if (fieldName.length() > 0)
return fieldName;
try {
return info.getMethodPropertyName();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid " + description + ": can't infer field name: " + e, e);
}
}
// Get the n'th generic type parameter
private Type getParameterType(String description, Method method, int index) {
try {
return Util.getTypeParameter(method.getGenericReturnType(), index);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid " + description + ": invalid method return type: " + e.getMessage(), e);
}
}
// Create a simple field, either regular object field or sub-field of complex field
@SuppressWarnings("unchecked")
private JSimpleField createSimpleField(String description, TypeToken<?> fieldTypeToken, String fieldName,
int storageId, org.jsimpledb.annotation.JField annotation, Method getter, Method setter, String fieldDescription) {
// Get explicit type name, if any
final String typeName = annotation.type().length() > 0 ? annotation.type() : null;
// Include containing type for annotation description; with autogenProperties it can be more than one
description += " in " + this.type;
// Complex sub-field?
final boolean isSubField = setter == null;
// Sanity check annotation
if (isSubField && annotation.unique())
throw new IllegalArgumentException("invalid " + description + ": unique() constraint not allowed on complex sub-field");
if (annotation.uniqueExclude().length > 0 && !annotation.unique())
throw new IllegalArgumentException("invalid " + description + ": use of uniqueExclude() requires unique = true");
if (annotation.uniqueExcludeNull() && !annotation.unique())
throw new IllegalArgumentException("invalid " + description + ": use of uniqueExcludeNull() requires unique = true");
// See if field type encompasses one or more JClass types and is therefore a reference type
boolean isReferenceType = false;
for (JClass<?> jclass : this.jdb.jclasses.values()) {
if (fieldTypeToken.getRawType().isAssignableFrom(jclass.type)) {
isReferenceType = true;
break;
}
}
// See if field type is a simple type, known either by explicitly-given name or type
FieldType<?> nonReferenceType = null;
if (typeName != null) {
// Field type is explicitly specified by name
if ((nonReferenceType = this.jdb.db.getFieldTypeRegistry().getFieldType(typeName)) == null)
throw new IllegalArgumentException("invalid " + description + ": unknown simple field type `" + typeName + "'");
// Verify field type matches what we expect
final TypeToken<?> expectedType = isSubField ? nonReferenceType.getTypeToken().wrap() : nonReferenceType.getTypeToken();
if (!expectedType.equals(fieldTypeToken)) {
throw new IllegalArgumentException("invalid " + description + ": field type `" + typeName
+ "' supports values of type " + nonReferenceType.getTypeToken() + " but " + fieldTypeToken
+ " is required (according to the getter method's return type)");
}
} else {
// Try to find a field type supporting getter method return type
final List<? extends FieldType<?>> fieldTypes = this.jdb.db.getFieldTypeRegistry().getFieldTypes(fieldTypeToken);
switch (fieldTypes.size()) {
case 0:
nonReferenceType = null;
break;
case 1:
nonReferenceType = fieldTypes.get(0);
break;
default:
if (!isReferenceType) {
throw new IllegalArgumentException("invalid " + description + ": an explicit type() must be specified"
+ " because type " + fieldTypeToken + " is supported by multiple registered simple field types: "
+ fieldTypes);
}
break;
}
}
// Detect enum types
final Class<? extends Enum<?>> enumType = Enum.class.isAssignableFrom(fieldTypeToken.getRawType()) ?
(Class<? extends Enum<?>>)fieldTypeToken.getRawType().asSubclass(Enum.class) : null;
// If field type neither refers to a JClass type, nor is a registered field type, nor is an enum type, fail
if (!isReferenceType && nonReferenceType == null && enumType == null) {
throw new IllegalArgumentException("invalid " + description + ": an explicit type() must be specified"
+ " because no known type supports values of type " + fieldTypeToken);
}
// Handle ambiguity between reference vs. non-reference
if (isReferenceType && nonReferenceType != null) {
// If an explicit type name was provided, assume they want the specified non-reference type
if (typeName != null)
isReferenceType = false;
else {
throw new IllegalArgumentException("invalid " + description + ": an explicit type() must be specified"
+ " because type " + fieldTypeToken + " is ambiguous, being both a @" + JSimpleClass.class.getSimpleName()
+ " reference type and a simple Java type supported by type `" + nonReferenceType + "'");
}
}
// Sanity check annotation some more
if (!isReferenceType && annotation.onDelete() != DeleteAction.EXCEPTION)
throw new IllegalArgumentException("invalid " + description + ": onDelete() only allowed on reference fields");
if (!isReferenceType && annotation.cascadeDelete())
throw new IllegalArgumentException("invalid " + description + ": cascadeDelete() only allowed on reference fields");
if (!isReferenceType && annotation.unique() && !annotation.indexed())
throw new IllegalArgumentException("invalid " + description + ": unique() constraint requires field to be indexed");
if (nonReferenceType != null && nonReferenceType.getTypeToken().isPrimitive() && annotation.uniqueExcludeNull()) {
throw new IllegalArgumentException("invalid " + description + ": uniqueExcludeNull() is incompatible with fields"
+ " having primitive type");
}
// Create simple, enum, or reference field
try {
return
isReferenceType ?
new JReferenceField(this.jdb, fieldName, storageId, fieldDescription, fieldTypeToken, annotation, getter, setter) :
enumType != null ?
new JEnumField(this.jdb, fieldName, storageId, enumType, annotation, fieldDescription, getter, setter) :
new JSimpleField(this.jdb, fieldName, storageId, fieldTypeToken,
nonReferenceType, annotation.indexed(), annotation, fieldDescription, getter, setter);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid " + description + ": " + e.getMessage(), e);
}
}
} |
package com.sailthru.client.params;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
public interface ApiFileParams {
public Map<String, FileInputStream> getFileParams();
} |
package application;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.rmi.server.RMISocketFactory;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Scanner;
import java.util.logging.Level;
import data.Favourites;
import data.PastUsernames;
import data.SQLDatabase;
import data.SampServer;
import gui.controllers.MainController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import logging.Logging;
import util.FileUtility;
import util.windows.OSInfo;
public class BrowserMain extends Application
{
public static final String APPLICATION_NAME = "SA-MP Client Extension";
private static final String VERSION = "1.1.0";
@Override
public void start(final Stage primaryStage)
{
checkOperatingSystemCompatibility();
checkVersion();
prepareData();
setRMISocketFactory();
loadUI(primaryStage);
}
private void loadUI(final Stage primaryStage)
{
final FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/views/Main.fxml"));
final MainController controller = new MainController();
loader.setController(controller);
try
{
final Parent root = loader.load();
final Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.getScene().getStylesheets().add(getClass().getResource("/views/style.css").toExternalForm());
primaryStage.getIcons().add(new Image(this.getClass().getResourceAsStream("/icons/icon.png")));
primaryStage.setTitle(APPLICATION_NAME);
primaryStage.show();
primaryStage.setMinWidth(primaryStage.getWidth());
primaryStage.setMinHeight(primaryStage.getHeight());
primaryStage.setIconified(false);
primaryStage.setMaximized(false);
controller.init();
primaryStage.setOnCloseRequest(close ->
{
controller.onClose();
});
}
catch (final Exception e)
{
Logging.logger.log(Level.SEVERE, "Couldn't load UI", e);
System.exit(0);
}
}
/**
* Checks if the operating system is windows, if not, the application will shutdown.
*/
private void checkOperatingSystemCompatibility()
{
if (!OSInfo.isWindows())
{
final Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Launching Application");
alert.setHeaderText("Operating System not supported");
alert.setContentText("You seem to be not using windows, sorry, but this application does not support other systems than Windows.");
alert.showAndWait();
System.exit(0);
}
}
/**
* Creates files and folders that are necessary for the application to run properly.
*/
private static void prepareData()
{
File file = new File(System.getProperty("user.home") + File.separator + "sampex");
if (!file.exists())
{
file.mkdir();
}
SQLDatabase.init();
file = new File(System.getProperty("user.home") + File.separator + "sampex" + File.separator + "favourites.xml");
// Migration from XML to SQLLite
if (file.exists())
{
for (final SampServer server : Favourites.getFavouritesFromXML())
{
Favourites.addServerToFavourites(server);
}
file.delete();
}
file = new File(System.getProperty("user.home") + File.separator + "sampex" + File.separator + "pastusernames.xml");
if (file.exists())
{
for (final String username : PastUsernames.getPastUsernamesFromXML())
{
PastUsernames.addPastUsername(username);
}
file.delete();
}
}
/**
* Compares the local version number to the one lying on the server. If an update is
* availbable the user will be asked if he wants to update.
*/
private static void checkVersion()
{
try
{
final URI url = new URI("http://ts3.das-chat.xyz/sampversion/launcher/version.info");
try (final Scanner s = new Scanner(url.toURL().openStream()))
{
if (!VERSION.equals(s.nextLine()))
{
final Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Launching Application");
alert.setHeaderText("Update required");
alert.setContentText("The launcher needs an update. Not updating the client might lead to problems. Click 'OK' to update and 'Cancel' to not update.");
final Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK)
{
updateLauncher();
}
}
}
}
catch (final Exception e)
{
Logging.logger.log(Level.SEVERE, "Couldn't retrieve Update / Update Info.", e);
}
}
/**
* Downloads the latest version and restarts the client.
*/
private static void updateLauncher()
{
try
{
final URI url = new URI("http://ts3.das-chat.xyz/sampversion/launcher/launcher.jar");
FileUtility.downloadUsingNIO(url.toString(), getOwnJarFile().getPath().toString());
selfRestart();
}
catch (final IOException | URISyntaxException e)
{
Logging.logger.log(Level.SEVERE, "Couldn't retrieve update.", e);
}
}
/**
* @return a File pointing to the applications own jar file
*/
private static File getOwnJarFile()
{
return new File(System.getProperty("java.class.path")).getAbsoluteFile();
}
/**
* Restarts the application.
*/
private static void selfRestart()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = getOwnJarFile();
if (!currentJar.getName().endsWith(".jar"))
{
return;
}
final ArrayList<String> command = new ArrayList<>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
try
{
builder.start();
System.exit(0);
}
catch (final IOException e)
{
Logging.logger.log(Level.SEVERE, "Couldn't selfrestart.", e);
}
}
private static void setRMISocketFactory()
{
try
{
RMISocketFactory.setSocketFactory(new RMISocketFactory()
{
@Override
public Socket createSocket(final String host, final int port) throws IOException
{
final Socket socket = new Socket();
socket.setSoTimeout(1500);
socket.setSoLinger(false, 0);
socket.connect(new InetSocketAddress(host, port), 1500);
return socket;
}
@Override
public ServerSocket createServerSocket(final int port) throws IOException
{
return new ServerSocket(port);
}
});
}
catch (final IOException e)
{
Logging.logger.log(Level.WARNING, "Couldb't set custom RMI Socket Factory.", e);
}
}
public static void main(final String[] args)
{
launch(args);
}
} |
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.graph.DiGraph;
import java.util.*;
/**
* @author arcadoss
*/
class AnalyzerState implements LatticeElement, BaseObj<AnalyzerState> {
Store store;
Stack stack;
Marker marker;
AnalyzerState(Store store, Stack stack, Marker marker) {
this.store = store;
this.stack = stack;
this.marker = marker;
}
/**
* @author arcadoss
*/
public static class Store implements BaseObj<Store> {
Map<Label, AbsObject> store;
public Store() {
store = new HashMap<Label, AbsObject>();
}
private Store(Map<Label, AbsObject> store) {
this.store = store;
}
@Override
public Store union(Store rValue) {
Map<Label, AbsObject> newStore = joinMaps(store, rValue.getStore());
return new Store(newStore);
}
public Map<Label, AbsObject> getStore() {
return store;
}
}
/**
* @author arcadoss
*/
public static class Stack implements BaseObj<Stack> {
Map<String, Value> tempValues;
Set<ExecutionContext> context;
final String varForFunc = "v_call";
final String varForExept = "v_ex";
Value funcRes;
Value exeptRes;
public Stack() {
tempValues = new HashMap<String, Value>();
context = new HashSet<ExecutionContext>();
funcRes = new Value();
exeptRes = new Value();
tempValues.put(varForFunc, funcRes);
tempValues.put(varForExept, exeptRes);
}
private Stack(Map<String, Value> tempValues, Set<ExecutionContext> context) {
this.tempValues = tempValues;
this.context = context;
}
@Override
public Stack union(Stack rValue) {
Map<String, Value> newTempVal = joinMaps(tempValues, rValue.getTempValues());
Set<ExecutionContext> newContext = joinSets(context, rValue.getContext());
Stack newStack = new Stack(newTempVal, newContext);
return newStack;
}
public Map<String, Value> getTempValues() {
return tempValues;
}
public Set<ExecutionContext> getContext() {
return context;
}
public Value getFuncRes() {
return funcRes;
}
public void setFuncRes(Value funcRes) {
this.funcRes = funcRes;
}
public Value getExeptRes() {
return exeptRes;
}
public void setExeptRes(Value exeptRes) {
this.exeptRes = exeptRes;
}
}
/**
* @author arcadoss
*/
public static class Marker implements BaseObj<Marker> {
Set<MyFlowGraph.Branch> markers;
public Marker() {
this.markers = new HashSet<MyFlowGraph.Branch>();
}
public Marker(Set<MyFlowGraph.Branch> set) {
this.markers = set;
}
@Override
public Marker union(Marker rValue) {
Set<MyFlowGraph.Branch> set = joinSets(markers, rValue.getMarkers());
return new Marker(set);
}
public Set<MyFlowGraph.Branch> getMarkers() {
return markers;
}
}
/**
* @author arcadoss
*/
public static class Label {
int label;
}
/**
* @author arcadoss
*/
public static class Value implements BaseObj<Value> {
// todo: add unknown here ?
static final int typeCount = 6;
BaseObj undefVal;
BaseObj nullVal;
BaseObj boolVal;
BaseObj numVal;
BaseObj strVal;
BaseObj objVal;
List<BaseObj> values;
public Value() {
undefVal = new SimpleObj();
nullVal = new SimpleObj();
boolVal = new BoolObj();
numVal = new IntObj();
strVal = new StrObj();
objVal = new ObjectObj();
values = makeList(undefVal, nullVal, boolVal, numVal, strVal, objVal);
}
private Value(BaseObj undefVal, BaseObj nullVal, BaseObj boolVal, BaseObj numVal, BaseObj strVal, BaseObj objVal) {
this.undefVal = undefVal;
this.nullVal = nullVal;
this.boolVal = boolVal;
this.numVal = numVal;
this.strVal = strVal;
this.objVal = objVal;
this.values = makeList(undefVal, nullVal, boolVal, numVal, strVal, objVal);
}
private Value(List<BaseObj> newValues) {
if (newValues.size() != typeCount) {
throw new IllegalArgumentException("Trying initialize Value type with wrong arguments");
}
undefVal = newValues.get(0);
nullVal = newValues.get(1);
boolVal = newValues.get(2);
numVal = newValues.get(3);
strVal = newValues.get(4);
objVal = newValues.get(5);
values = newValues;
}
@Override
public Value union(Value rValue) {
Iterator<BaseObj> iter1 = values.iterator();
Iterator<BaseObj> iter2 = rValue.getValues().iterator();
List<BaseObj> newValues = new ArrayList<BaseObj>();
while (iter1.hasNext()) {
newValues.add(iter1.next().union(iter2.next()));
}
Value out = new Value(newValues);
return out;
}
public List<BaseObj> getValues() {
return values;
}
private static List<BaseObj> makeList(BaseObj undefVal, BaseObj nullVal, BaseObj boolVal, BaseObj numVal, BaseObj strVal, BaseObj objVal) {
List<BaseObj> out = new ArrayList<BaseObj>();
out.add(undefVal);
out.add(nullVal);
out.add(boolVal);
out.add(numVal);
out.add(strVal);
out.add(objVal);
return out;
}
}
/**
* @author arcadoss
*/
public static class ExecutionContext {
LinkedList<Label> scopeChain;
Label thisObj;
Label varObj;
//todo : initialize objects here
}
/**
* @author arcadoss
*/
public static class AbsObject implements BaseObj<AbsObject> {
Map<String, Property> properties;
Set<LinkedList<Label>> scopeChains;
boolean isFunction;
DiGraph.DiGraphNode<MyNode, MyFlowGraph.Branch> functionEntry;
public AbsObject() {
this.properties = new HashMap<String, Property>();
this.scopeChains = new HashSet<LinkedList<Label>>();
this.isFunction = false;
this.functionEntry = null;
}
private AbsObject(Map<String, Property> properties, Set<LinkedList<Label>> scopeChains) {
this.properties = properties;
this.scopeChains = scopeChains;
}
@Override
public AbsObject union(AbsObject rValue) {
Map<String, Property> newProp = joinMaps(properties, rValue.getProperties());
Set<LinkedList<Label>> newChains = joinSets(scopeChains, rValue.getScopeChains());
return new AbsObject(newProp, newChains);
}
public Map<String, Property> getProperties() {
return properties;
}
public Set<LinkedList<Label>> getScopeChains() {
return scopeChains;
}
}
/**
* @author arcadoss
*/
public static class Property implements BaseObj<Property> {
private static final int PropCount = 5;
Value value;
BaseObj absent;
BaseObj readOnly;
BaseObj dontDelete;
BaseObj dontEnum;
BaseObj modified;
List<BaseObj> properties;
public Property() {
value = new Value();
absent = new SimpleObj();
readOnly = new BoolObj();
dontDelete = new BoolObj();
dontEnum = new BoolObj();
modified = new SimpleObj();
properties = makeList(absent, readOnly, dontDelete, dontEnum, modified);
}
private Property(Value value, List<BaseObj> properties) {
if (properties.size() != PropCount) {
throw new IllegalArgumentException("Trying to initialize Property object with wrong parameters");
}
this.value = value;
this.absent = properties.get(0);
this.readOnly = properties.get(1);
this.dontDelete = properties.get(2);
this.dontEnum = properties.get(3);
this.modified = properties.get(4);
this.properties = properties;
}
@Override
public Property union(Property rValue) {
Value newValue = value.union(rValue.getValue());
Iterator<BaseObj> iter1 = properties.iterator();
Iterator<BaseObj> iter2 = rValue.getProperties().iterator();
List<BaseObj> newProps = new ArrayList<BaseObj>();
while (iter1.hasNext()) {
newProps.add(iter1.next().union(iter2.next()));
}
return new Property(newValue, newProps);
}
public Value getValue() {
return value;
}
public List<BaseObj> getProperties() {
return properties;
}
private static List<BaseObj> makeList(BaseObj absent, BaseObj readOnly, BaseObj dnd, BaseObj dne, BaseObj modified) {
List<BaseObj> out = new ArrayList<BaseObj>(PropCount);
out.add(absent);
out.add(readOnly);
out.add(dnd);
out.add(dne);
out.add(modified);
return out;
}
}
@Override
public AnalyzerState union(AnalyzerState rValue) {
Stack newStack = stack.union(rValue.getStack());
Store newStore = store.union(rValue.getStore());
marker = marker.union(rValue.getMarker());
return new AnalyzerState(newStore, newStack, marker);
}
public Store getStore() {
return store;
}
public Stack getStack() {
return stack;
}
public Marker getMarker() {
return marker;
}
public static AnalyzerState createGlobal() {
Stack initStack = new Stack();
Marker initMarker = new Marker();
Store initStore = new Store();
return new AnalyzerState(initStore, initStack, initMarker);
}
public static AnalyzerState bottom() {
Stack initStack = new Stack();
Marker initMarker = new Marker();
Store initStore = new Store();
return new AnalyzerState(initStore, initStack, initMarker);
}
private static <K, V extends BaseObj<V>> Map<K, V> joinMaps(Map<K, V> map1, Map<K, V> map2) {
Map<K, V> out = new HashMap(map1);
Set<Map.Entry<K, V>> rMap = map2.entrySet();
for (Map.Entry<K, V> elem : rMap) {
if (out.containsKey(elem.getKey())) {
out.get(elem.getKey()).union(elem.getValue());
} else {
out.put(elem.getKey(), elem.getValue());
}
}
return out;
}
private static <T> Set<T> joinSets(Set<T> context1, Set<T> context2) {
Set<T> out = new HashSet<T>(context1);
out.addAll(context2);
return out;
}
} |
package com.macro.mall.dao;
import com.macro.mall.dto.SmsCouponParam;
import org.apache.ibatis.annotations.Param;
public interface SmsCouponDao {
SmsCouponParam getItem(@Param("id") Long id);
} |
package aeronicamc.mods.mxtune.util;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class Color3f implements Comparable<Color3f>
{
protected static final float[][] rainbow =
{{0F, 0F, 1F},
{0F, 1F, 0F},
{0F, 1F, 1F},
{1F, 0F, 0F},
{1F, 0F, 1F},
{1F, 1F, 0F}};
protected final float r;
protected final float g;
protected final float b;
public Color3f(float r, float g, float b)
{
this.r = r;
this.g = g;
this.b = b;
}
public static Color3f rainbowFactory()
{
int row = RandomUtils.nextInt(0, rainbow.length);
return new Color3f(rainbow[row][0], rainbow[row][1], rainbow[row][2]);
}
public float getR()
{
return r;
}
public float getG()
{
return g;
}
public float getB()
{
return b;
}
@Override
public String toString()
{
int shift = RandomUtils.nextInt(1, 10);
return String.format("Stage: %s", StringUtils.rotate("0123456789", shift));
}
@Override
public int hashCode()
{
return new HashCodeBuilder(17, 37)
.append(r)
.append(g)
.append(b)
.toHashCode();
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Color3f color3f = (Color3f) o;
return new EqualsBuilder()
.append(r, color3f.getR())
.append(g, color3f.getG())
.append(b, color3f.getB())
.isEquals();
}
@Override
public int compareTo(Color3f o)
{
return new CompareToBuilder()
.append(r, o.getR())
.append(g, o.getG())
.append(b, o.getB())
.toComparison();
}
} |
package algorithms.search;
import algorithms.util.PairInt;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import thirdparty.ods.Integerizer;
import thirdparty.ods.XFastTrie;
import thirdparty.ods.XFastTrieNode;
public class NearestNeighbor2D {
private final XFastTrie<XFastTrieNode<Integer>, Integer> xbt;
private final int width;
private final int height;
private final int maxIndex;
private boolean useCache = true;
private TIntIntMap pCache = new TIntIntHashMap();
private TIntIntMap sCache = new TIntIntHashMap();
private Logger log = Logger.getLogger(this.getClass().getName());
/**
*
* @param points non-negative coordinates
* @param maxX maximum x value of any data point including
* those to be queries
* @param maxY maximum y value of any data point including
* those to be queries
*/
public NearestNeighbor2D(Set<PairInt> points,
int maxX, int maxY) {
this.width = maxX + 1;
this.height = maxY + 1;
maxIndex = width * height;
Integerizer<Integer> it = new Integerizer<Integer>() {
@Override
public int intValue(Integer x) {
return x;
}
};
int maxW = 1 + (int)Math.ceil(Math.log(maxIndex)/Math.log(2));
xbt = new XFastTrie<XFastTrieNode<Integer>, Integer>(
new XFastTrieNode<Integer>(), it, maxW);
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
if (x > width || x < 0) {
throw new IllegalArgumentException(
"x cannot be larger than "
+ " maxX given in constructor " + width
+ ". x=" + x);
}
if (y > height || y < 0) {
throw new IllegalArgumentException(
"y cannot be larger than "
+ " maxY given in constructor " + height + ". y=" + y);
}
int index = getInternalIndex(x, y);
xbt.add(Integer.valueOf(index));
}
}
/**
*
* @param pointIdxs pixel indexes formed from relationship
* pixIdx = (row * width) + col
* @param imgWidth maximum x value of any data point including
* those to be queries
* @param maxY maximum y value of any data point including
* those to be queries
*/
public NearestNeighbor2D(TIntSet pointIdxs, int imgWidth, int maxY) {
this.width = imgWidth;
this.height = maxY + 1;
maxIndex = width * height;
Integerizer<Integer> it = new Integerizer<Integer>() {
@Override
public int intValue(Integer x) {
return x;
}
};
int maxW = 1 + (int)Math.ceil(Math.log(maxIndex)/Math.log(2));
xbt = new XFastTrie<XFastTrieNode<Integer>, Integer>(
new XFastTrieNode<Integer>(), it, maxW);
TIntIterator iter = pointIdxs.iterator();
while (iter.hasNext()) {
int pixIdx = iter.next();
int x = getCol(pixIdx);
int y = getRow(pixIdx);
if (x > width || x < 0) {
throw new IllegalArgumentException(
"x cannot be larger than "
+ " maxX given in constructor " + width
+ ". x=" + x);
}
if (y > height || y < 0) {
throw new IllegalArgumentException(
"y cannot be larger than "
+ " maxY given in constructor " + height + ". y=" + y);
}
xbt.add(Integer.valueOf(pixIdx));
}
}
public void doNotUseCache() {
useCache = false;
}
protected int getInternalIndex(int col, int row) {
return (row * width) + col;
}
protected int getRow(int internalIndex) {
int row = internalIndex/width;
return row;
}
protected int getCol(int internalIndex) {
int row = internalIndex/width;
int col = internalIndex - (row * width);
return col;
}
/**
<pre>
runtime complexity is
best case: 2 * O(log_2(maxW)).
Note that caching leads to an O(1) term
over time instead of the logarithmic term.
worst case: nRows * 2 * O(log_2(maxW))
Note, worst case is: first column
filled with points and all else is empty and
the number of rows is same or larger than
number of columns and the
query is for the point in the last column and
last row... a predecessor call is necessary for
each row in the worst case.
Note: maxW = 1 + Math.ceil(Math.log(maxX * maxY)/Math.log(2));
</ore>
* @param x non-negative x coord to query for
* @param y non-negative y coord to query for
*/
public Set<PairInt> findClosest(final int x, final int y) {
return findClosestWithinTolerance(x, y, 0);
}
/**
* NOTE: NOT READY FOR USE
* method to return only the nearest point and any
* that are at the same distance within a tolerance.
* This is meant to be a nearest neighbor method
* with ability to return more than one at same distance within a tolerance
* of that distance.
* TODO: calculate the runtime complexity bounds....
* @param x non-negative x coord to query for
* @param y non-negative y coord to query for
* @param tolerance
* @return
*/
public Set<PairInt> findClosestWithinTolerance(int x, int y,
double tolerance) {
if (x >= width || x < 0) {
log.fine(
"x cannot be larger than "
+ " maxX given in constructor " + width
+ ". x=" + x);
return null;
}
if (y >= height || y < 0) {
log.fine(
"y cannot be larger than "
+ " maxY given in constructor " + height + ". y=" + y);
return null;
}
double closestDist = Double.MAX_VALUE;
double closestDistPlusTol = Double.MAX_VALUE;
TIntSet closestIndexes = new TIntHashSet();
int idx = getInternalIndex(x, y);
Integer index = Integer.valueOf(idx);
Integer q = xbt.find(index);
if (q != null) {
// have found nearest, but still need to search
// within tolerance distance for others.
closestDist = 0;
closestDistPlusTol = tolerance;
closestIndexes.add(index.intValue());
}
Integer predecessor = null;
Integer successor = null;
if (useCache && pCache.containsKey(idx)) {
predecessor = Integer.valueOf(pCache.get(idx));
} else {
//O(log_2(maxW))
predecessor = xbt.predecessor(index);
if (useCache && predecessor != null) {
pCache.put(idx, predecessor.intValue());
}
}
if (useCache && sCache.containsKey(idx)) {
successor = Integer.valueOf(sCache.get(idx));
} else {
//O(log_2(maxW))
successor = xbt.successor(index);
if (useCache && successor != null){
sCache.put(idx, successor.intValue());
}
}
double dp2 = dist(x, y, predecessor);
double ds2 = dist(x, y, successor);
double dMin = Math.min(dp2, ds2);
/*
if smallest is smaller than closest
if the new closest diff with current is greater
than tol, clear the indexes and reset closest
vars and add smallest to indexes
also add the other if within tolerance
else if closer is within tolerance,
update closest vars and add whichever or both
s2 and p2 to indexes (delaying detailed checks
of indexes until end of method)
else if smallest is <= closestPlusTol
add s2 and/or p2 to indexes
*/
if (dMin <= closestDist) {
if (Math.abs(closestDist - dMin) > tolerance) {
closestIndexes.clear();
closestDist = dMin;
closestDistPlusTol = closestDist + tolerance;
}
if ((predecessor != null) &&
(dp2 <= closestDistPlusTol)) {
closestIndexes.add(predecessor.intValue());
}
if ((successor != null) &&
(ds2 <= closestDistPlusTol)) {
closestIndexes.add(successor.intValue());
}
} else if (dMin <= closestDistPlusTol) {
if ((predecessor != null) &&
(dp2 <= closestDistPlusTol)) {
closestIndexes.add(predecessor.intValue());
}
if ((successor != null) &&
(ds2 <= closestDistPlusTol)) {
closestIndexes.add(successor.intValue());
}
}
//add tolerance to goal
int goal = (closestDist != Double.MAX_VALUE) ?
(int)Math.ceil(closestDistPlusTol) : 0;
int yLow = estimateLowBound(y, goal);
int yCurrent;
if (predecessor == null) {
yCurrent = Integer.MIN_VALUE;
} else {
int pRow = getRow(predecessor.intValue());
if (pRow < y) {
yCurrent = pRow;
} else {
yCurrent = pRow - 1;
}
}
// predecessor searches until reach yLow, adjusting goal by
// min distances
Integer p2 = null;
Integer s2 = null;
while (yCurrent >= yLow) {
int cIdx = getInternalIndex(x, yCurrent);
Integer cIndex = Integer.valueOf(cIdx);
q = xbt.find(cIndex);
if (q != null) {
p2 = q;
dp2 = dist(x, y, p2);
ds2 = Double.MAX_VALUE;
} else {
if (useCache && pCache.containsKey(cIdx)) {
p2 = Integer.valueOf(pCache.get(cIdx));
} else {
//O(log_2(maxW))
p2 = xbt.predecessor(cIndex);
if (useCache && p2 != null) {
pCache.put(cIdx, p2.intValue());
}
}
if (useCache && sCache.containsKey(cIdx)) {
s2 = Integer.valueOf(sCache.get(cIdx));
} else {
//O(log_2(maxW))
s2 = xbt.successor(cIndex);
if (useCache && s2 != null) {
sCache.put(cIdx, s2.intValue());
}
}
dp2 = dist(x, y, p2);
ds2 = dist(x, y, s2);
}
dMin = Math.min(dp2, ds2);
if (dMin <= closestDist) {
if (Math.abs(closestDist - dMin) > tolerance) {
closestIndexes.clear();
closestDist = dMin;
closestDistPlusTol = closestDist + tolerance;
goal = (int)Math.ceil(closestDistPlusTol);
yLow = estimateLowBound(y, goal);
}
if ((p2 != null) && dp2 <= closestDistPlusTol) {
closestIndexes.add(p2.intValue());
}
if ((s2 != null) && ds2 <= closestDistPlusTol) {
closestIndexes.add(s2.intValue());
}
} else if (dMin <= closestDistPlusTol) {
if ((p2 != null) && dp2 <= closestDistPlusTol) {
closestIndexes.add(p2.intValue());
}
if ((s2 != null) && ds2 <= closestDistPlusTol) {
closestIndexes.add(s2.intValue());
}
}
if (p2 != null) {
int expectedNext = getInternalIndex(x, yCurrent - 1);
if (p2.intValue() > expectedNext) {
yCurrent -= 1;
} else {
yCurrent = getRow(p2.intValue()) - 1;
}
} else {
yCurrent = Integer.MIN_VALUE;
}
}
// successor searches to higher bounds
if (successor == null) {
yCurrent = Integer.MAX_VALUE;
} else {
int sr = getRow(successor.intValue());
if (sr > y) {
yCurrent = sr;
} else {
yCurrent = sr + 1;
}
}
int yHigh = estimateHighBound(y, goal);
while (yCurrent <= yHigh) {
int cIdx = getInternalIndex(x, yCurrent);
Integer cIndex = Integer.valueOf(cIdx);
q = xbt.find(cIndex);
if (q != null) {
p2 = q;
dp2 = dist(x, y, p2);
ds2 = Double.MAX_VALUE;
} else {
if (useCache && pCache.containsKey(cIdx)) {
p2 = Integer.valueOf(pCache.get(cIdx));
} else {
//O(log_2(maxW))
p2 = xbt.predecessor(cIndex);
if (useCache && p2 != null) {
pCache.put(cIdx, p2.intValue());
}
}
if (useCache && sCache.containsKey(cIdx)) {
s2 = Integer.valueOf(sCache.get(cIdx));
} else {
//O(log_2(maxW))
s2 = xbt.successor(cIndex);
if (useCache && s2 != null) {
sCache.put(cIdx, s2.intValue());
}
}
dp2 = dist(x, y, p2);
ds2 = dist(x, y, s2);
}
dMin = Math.min(dp2, ds2);
if (dMin <= closestDist) {
if (Math.abs(closestDist - dMin) > tolerance) {
closestIndexes.clear();
closestDist = dMin;
closestDistPlusTol = closestDist + tolerance;
goal = (int)Math.ceil(closestDistPlusTol);
yHigh = estimateHighBound(y, goal);
}
if ((p2 != null) && dp2 <= closestDistPlusTol) {
closestIndexes.add(p2.intValue());
}
if ((s2 != null) && ds2 <= closestDistPlusTol) {
closestIndexes.add(s2.intValue());
}
} else if (dMin <= closestDistPlusTol) {
if ((p2 != null) && dp2 <= closestDistPlusTol) {
closestIndexes.add(p2.intValue());
}
if ((s2 != null) && ds2 <= closestDistPlusTol) {
closestIndexes.add(s2.intValue());
}
}
if (s2 != null) {
int expectedNext = getInternalIndex(x, yCurrent + 1);
if (s2.intValue() < expectedNext) {
yCurrent += 1;
} else {
yCurrent = getRow(s2.intValue()) + 1;
}
} else {
yCurrent = Integer.MAX_VALUE;
}
}
//filter results for closest and tolerance
Set<PairInt> results = new HashSet<PairInt>();
TIntIterator iter = closestIndexes.iterator();
while (iter.hasNext()) {
int index2 = iter.next();
if (dist(x, y, index2) <= closestDistPlusTol) {
int x2 = getCol(index2);
int y2 = getRow(index2);
PairInt p3 = new PairInt(x2, y2);
results.add(p3);
}
}
return results;
}
/**
<pre>
runtime complexity is
best case: 2 * O(log_2(maxW)).
Note that caching leads to an O(1) term
over time instead of the logarithmic term.
worst case: nRows * 2 * O(log_2(maxW))
Note, worst case is: first column
filled with points and all else is empty and
the number of rows is same or larger than
number of columns and the
query is for the point in the last column and
last row... a predecessor call is necessary for
each row in the worst case.
Note: maxW = 1 + Math.ceil(Math.log(maxX * maxY)/Math.log(2));
</ore>
* @param x non-negative x coord to query for
* @param y non-negative y coord to query for
*/
public Set<PairInt> findClosestNotEqual(final int x, final int y) {
return findClosest(x, y, Integer.MAX_VALUE, false);
}
/**
<pre>
runtime complexity is
best case: 2 * O(log_2(maxW)).
Note that caching leads to an O(1) term
over time instead of the logarithmic term.
worst case: dMax * 4 * O(log_2(maxW))
Note: maxW = 1 + Math.ceil(Math.log(maxX * maxY)/Math.log(2));
</ore>
* @param x
* @param y
* @param dMax
* @return a set of points within dMax that are the
* closest points, else returns an empty set
*/
public Set<PairInt> findClosest(int x, int y, int dMax) {
return findClosest(x, y, dMax, true);
}
/**
<pre>
runtime complexity is
best case: 2 * O(log_2(maxW)).
Note that caching leads to an O(1) term
over time instead of the logarithmic term.
worst case: dMax * 4 * O(log_2(maxW))
Note: maxW = 1 + Math.ceil(Math.log(maxX * maxY)/Math.log(2));
</ore>
* @param x
* @param y
* @param dMax
* @return a set of points within dMax that are the
* closest points, else returns an empty set
*/
private Set<PairInt> findClosest(int x, int y, int dMax, boolean includeEquals) {
if (x >= width || x < 0) {
log.fine(
"x cannot be larger than "
+ " maxX given in constructor " + width
+ ". x=" + x);
return null;
}
if (y >= height || y < 0) {
log.fine(
"y cannot be larger than "
+ " maxY given in constructor " + height + ". y=" + y);
return null;
}
int idx = getInternalIndex(x, y);
Integer index = Integer.valueOf(idx);
if (includeEquals) {
Integer q = xbt.find(index);
if (q != null) {
Set<PairInt> results = new HashSet<PairInt>();
results.add(new PairInt(x, y));
return results;
}
}
TIntSet closestIndexes = new TIntHashSet();
double closestDist = Double.MAX_VALUE;
Integer predecessor = null;
Integer successor = null;
if (useCache && pCache.containsKey(idx)) {
predecessor = Integer.valueOf(pCache.get(idx));
} else {
//O(log_2(maxW))
predecessor = xbt.predecessor(index);
if (useCache && predecessor != null) {
pCache.put(idx, predecessor.intValue());
}
}
if (useCache && sCache.containsKey(idx)) {
successor = Integer.valueOf(sCache.get(idx));
} else {
//O(log_2(maxW))
successor = xbt.successor(index);
if (useCache && successor != null) {
sCache.put(idx, successor.intValue());
}
}
double dp2 = dist(x, y, predecessor);
double ds2 = dist(x, y, successor);
if (!includeEquals) {
if (dp2 == 0) {
ds2 = Integer.MAX_VALUE;
} else if (ds2 == 0) {
ds2 = Integer.MAX_VALUE;
}
}
if (dp2 <= ds2 && (dp2 <= dMax)) {
closestDist = dp2;
closestIndexes.add(predecessor.intValue());
if (dp2 == ds2) {
closestIndexes.add(successor.intValue());
}
} else if (ds2 < dp2 && (ds2 <= dMax)) {
closestDist = ds2;
closestIndexes.add(successor.intValue());
}
int goal = (closestDist != Double.MAX_VALUE) ?
(int)Math.ceil(closestDist) : dMax;
if (goal > dMax) {
goal = dMax;
}
int yLow = estimateLowBound(y, goal);
int yCurrent;
if (predecessor == null) {
yCurrent = Integer.MIN_VALUE;
} else {
int pRow = getRow(predecessor.intValue());
if (pRow < y) {
yCurrent = pRow;
} else {
yCurrent = pRow - 1;
}
}
// predecessor searches until reach yLow, adjusting goal by
// min distances
Integer p2 = null;
Integer s2 = null;
while (yCurrent >= yLow) {
int cIdx = getInternalIndex(x, yCurrent);
Integer cIndex = Integer.valueOf(cIdx);
Integer q = xbt.find(cIndex);
if (q != null) {
p2 = q;
dp2 = dist(x, y, p2);
ds2 = Double.MAX_VALUE;
} else {
if (useCache && pCache.containsKey(cIdx)) {
p2 = Integer.valueOf(pCache.get(cIdx));
} else {
//O(log_2(maxW))
p2 = xbt.predecessor(cIndex);
if (useCache && p2 != null) {
pCache.put(cIdx, p2.intValue());
}
}
if (useCache && sCache.containsKey(cIdx)) {
s2 = Integer.valueOf(sCache.get(cIdx));
} else {
//O(log_2(maxW))
s2 = xbt.successor(cIndex);
if (useCache && s2 != null) {
sCache.put(cIdx, s2.intValue());
}
}
dp2 = dist(x, y, p2);
ds2 = dist(x, y, s2);
}
if (!includeEquals) {
if (s2 != null && s2.intValue() == idx) {
ds2 = Integer.MAX_VALUE;
}
}
if ((dp2 < ds2) && (dp2 < closestDist) && (dp2 <= dMax)) {
closestIndexes.clear();
closestDist = dp2;
closestIndexes.add(p2);
goal = (int)Math.ceil(closestDist);
if (goal > dMax) {
goal = dMax;
}
yLow = estimateLowBound(y, goal);
} else if ((ds2 < dp2) && (ds2 < closestDist) && (ds2 <= dMax)) {
closestIndexes.clear();
closestDist = ds2;
closestIndexes.add(s2);
goal = (int)Math.ceil(closestDist);
if (goal > dMax) {
goal = dMax;
}
yLow = estimateLowBound(y, goal);
} else if (dp2 == closestDist && (dp2 != Double.MAX_VALUE)
&& (dp2 <= dMax)) {
closestIndexes.add(p2.intValue());
if (dp2 == ds2) {
closestIndexes.add(s2.intValue());
}
} else if (ds2 == closestDist && (ds2 != Double.MAX_VALUE)
&& (ds2 <= dMax)) {
closestIndexes.add(s2.intValue());
}
if (p2 != null) {
int expectedNext = getInternalIndex(x, yCurrent - 1);
if (p2.intValue() > expectedNext) {
yCurrent -= 1;
} else {
yCurrent = getRow(p2.intValue()) - 1;
}
} else {
yCurrent = Integer.MIN_VALUE;
}
}
// successor searches to higher bounds
if (successor == null) {
yCurrent = Integer.MAX_VALUE;
} else {
int sr = getRow(successor.intValue());
if (sr > y) {
yCurrent = sr;
} else {
yCurrent = sr + 1;
}
}
int yHigh = estimateHighBound(y, goal);
while (yCurrent <= yHigh) {
int cIdx = getInternalIndex(x, yCurrent);
Integer cIndex = Integer.valueOf(cIdx);
Integer q = xbt.find(cIndex);
if (q != null) {
p2 = q;
dp2 = dist(x, y, p2);
ds2 = Double.MAX_VALUE;
} else {
if (useCache && pCache.containsKey(cIdx)) {
p2 = Integer.valueOf(pCache.get(cIdx));
} else {
//O(log_2(maxW))
p2 = xbt.predecessor(cIndex);
if (useCache && p2 != null) {
pCache.put(cIdx, p2.intValue());
}
}
if (useCache && sCache.containsKey(cIdx)) {
s2 = Integer.valueOf(sCache.get(cIdx));
} else {
//O(log_2(maxW))
s2 = xbt.successor(cIndex);
if (useCache && s2 != null) {
sCache.put(cIdx, s2.intValue());
}
}
dp2 = dist(x, y, p2);
ds2 = dist(x, y, s2);
}
if (!includeEquals) {
if (p2 != null && p2.intValue() == idx) {
dp2 = Integer.MAX_VALUE;
} else if (s2 != null && s2.intValue() == idx) {
ds2 = Integer.MAX_VALUE;
}
}
if ((dp2 < ds2) && (dp2 < closestDist) && (dp2 <= dMax)) {
closestIndexes.clear();
closestDist = dp2;
closestIndexes.add(p2);
goal = (int)Math.ceil(closestDist);
if (goal > dMax) {
goal = dMax;
}
yHigh = estimateHighBound(y, goal);
} else if ((ds2 < dp2) && (ds2 < closestDist) && (ds2 <= dMax)) {
closestIndexes.clear();
closestDist = ds2;
closestIndexes.add(s2);
goal = (int)Math.ceil(closestDist);
if (goal > dMax) {
goal = dMax;
}
yHigh = estimateHighBound(y, goal);
} else if (dp2 == closestDist && (dp2 != Double.MAX_VALUE)
&& (dp2 <= dMax)) {
closestIndexes.add(p2.intValue());
if (dp2 == ds2) {
closestIndexes.add(s2.intValue());
}
} else if (ds2 == closestDist && (ds2 != Double.MAX_VALUE)
&& (ds2 <= dMax)) {
closestIndexes.add(s2.intValue());
}
if (s2 != null) {
int expectedNext = getInternalIndex(x, yCurrent + 1);
if (s2.intValue() < expectedNext) {
yCurrent += 1;
} else {
yCurrent = getRow(s2.intValue()) + 1;
}
} else {
yCurrent = Integer.MAX_VALUE;
}
}
Set<PairInt> results = new HashSet<PairInt>();
TIntIterator iter = closestIndexes.iterator();
while (iter.hasNext()) {
int index2 = iter.next();
int x2 = getCol(index2);
int y2 = getRow(index2);
results.add(new PairInt(x2, y2));
}
return results;
}
private double dist(int x, int y, Integer p2) {
if (p2 == null) {
return Double.MAX_VALUE;
}
int x2 = getCol(p2.intValue());
int y2 = getRow(p2.intValue());
int diffX = x2 - x;
int diffY = y2 - y;
double dist = Math.sqrt(diffX * diffX + diffY * diffY);
return dist;
}
private int estimateLowBound(int y, int goal) {
int low = y - goal;
if (low < 0) {
low = 0;
}
return low;
}
private int estimateHighBound(int y, int goal) {
int high = y + goal;
if (high > height) {
high = height;
}
return high;
}
} |
package br.uff.ic.provviewer.GUI;
import br.uff.ic.utility.graph.Edge;
import br.uff.ic.utility.GraphAttribute;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.utility.graph.ActivityVertex;
import br.uff.ic.utility.graph.AgentVertex;
import br.uff.ic.utility.graph.EntityVertex;
import br.uff.ic.utility.graph.Vertex;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections15.Transformer;
/**
* Class responsible for managing the tooltip system from Prov Viewer
* @author Kohwalter
*/
public class GuiTooltip {
static int agents = 0;
static int activities = 0;
static int entities = 0;
Map<String, GraphAttribute> attributes;
/**
* Method to generate vertex tooltips in the interface
* Called when initializing the application's components (GuiInitialization)
* @param variables is the global variables from Prov Viewer
*/
public static void Tooltip(Variables variables) {
// Vertex Tooltips
variables.view.setVertexToolTipTransformer(new ToStringLabeller() {
@Override
public String transform(Object v) {
if (v instanceof Graph) {
return "<html>" + GraphTooltip(v) + "</html>";
}
return "<html>" + v.toString() + "</html>";
}
});
// Edges Tooltips
variables.view.setEdgeToolTipTransformer(new Transformer<Edge, String>() {
@Override
public String transform(Edge n) {
return "<html><font size=\"4\">" + n.getEdgeTooltip() + "</html>";
}
});
}
/**
* Tooltip generator for collapsed vertices, also known as Graph vertices or Composite vertices
* @param v represents the targeted vertex for the tooltip
* @return a string that is the tooltip
*/
public static String GraphTooltip(Object v) {
String nodeTypes = "";
Map<String, String> ids = new HashMap<>();
Map<String, String> labels = new HashMap<>();
Map<String, String> times = new HashMap<>();
Map<String, GraphAttribute> attributes = new HashMap<>();
agents = 0;
activities = 0;
entities = 0;
GraphTooltip(v, ids, labels, times, attributes);
if (agents > 0) {
nodeTypes = "Agents: " + agents + "<br>";
}
if (activities > 0) {
nodeTypes += "Activities: " + activities + "<br>";
}
if (entities > 0) {
nodeTypes += "Entities: " + entities + "<br>";
}
return "<b>Summarized Vertex" + "</b>" + "<br>" + nodeTypes
+ "<br>IDs: " + ids.values().toString() + "<br>"
+ "<b>Labels: " + labels.values().toString() + "</b>"
+ " <br>" + "Times: " + times.values().toString()
+ " <br>" + PrintAttributes(attributes);
}
/**
* Recursive method to generate the tooltip.
* It considers Graph vertices inside the collapsed vertex.
* @param v is the current vertex for the tooltip
* @param ids is all computed ids for the tooltip
* @param labels is all computed labels for the tooltip
* @param times is all computed times for the tooltip
* @param attributes is the attribute list for the tooltip
*/
public static void GraphTooltip(Object v,
Map<String, String> ids,
Map<String, String> labels,
Map<String, String> times,
Map<String, GraphAttribute> attributes){
Collection vertices = ((Graph) v).getVertices();
for (Object vertex : vertices) {
if (!(vertex instanceof Graph))
{
ids.put(((Vertex) vertex).getID(), ((Vertex) vertex).getID());
labels.put(((Vertex) vertex).getLabel(), ((Vertex) vertex).getLabel());
times.put(((Vertex) vertex).getTimeString(), ((Vertex) vertex).getTimeString());
if (vertex instanceof AgentVertex) {
agents++;
} else if (vertex instanceof ActivityVertex) {
activities++;
} else if (vertex instanceof EntityVertex) {
entities++;
}
for (GraphAttribute att : ((Vertex) vertex).getAttributes()) {
if (attributes.containsKey(att.getName())) {
GraphAttribute temporary = attributes.get(att.getName());
temporary.updateAttribute(att.getAverageValue());
attributes.put(att.getName(), temporary);
} else {
attributes.put(att.getName(), new GraphAttribute(att.getName(), att.getAverageValue()));
}
}
}
else //(vertex instanceof Graph)
{
GraphTooltip(vertex, ids, labels, times, attributes);
}
}
}
/**
* Prints the tooltip attributes
* @param attributes is the list of all attributes
* @return a string that represents all attributes and their respective values
*/
public static String PrintAttributes(Map<String, GraphAttribute> attributes) {
String attributeList = "";
if (!attributes.values().isEmpty()) {
for (GraphAttribute att : attributes.values()) {
attributeList += att.printAttribute();
}
}
return attributeList;
}
} |
package manifold.internal.javac;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Trees;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import manifold.internal.host.ManifoldHost;
import static javax.lang.model.SourceVersion.RELEASE_8;
@SupportedSourceVersion(RELEASE_8)
@SupportedAnnotationTypes({"*"})
public class JavacHook extends AbstractProcessor
{
private static JavacHook INSTANCE = null;
private static final String GOSU_SOURCE_FILES = "gosu.source.files";
private JavacProcessingEnvironment _jpe;
private Context _ctx;
private ManifoldJavaFileManager _manFileManager;
private JavaFileManager _fileManager;
private Set<JavaFileObject> _javaInputFiles;
private List<String> _gosuInputFiles;
private TreeMaker _treeMaker;
private JavacElements _javacElements;
private TypeProcessor _typeProcessor;
public static JavacHook instance()
{
return INSTANCE;
}
public JavacHook()
{
INSTANCE = this;
}
@Override
public synchronized void init( ProcessingEnvironment processingEnv )
{
super.init( processingEnv );
_jpe = (JavacProcessingEnvironment)processingEnv;
_ctx = _jpe.getContext();
_fileManager = _ctx.get( JavaFileManager.class );
_javaInputFiles = fetchJavaInputFiles();
_gosuInputFiles = fetchGosuInputFiles();
_treeMaker = TreeMaker.instance( _ctx );
_javacElements = JavacElements.instance( _ctx );
_typeProcessor = new TypeProcessor( JavacTask.instance( _jpe ) );
hijackJavacFileManager();
}
ManifoldJavaFileManager getManFileManager()
{
return _manFileManager;
}
JavaFileManager getJavaFileManager()
{
return _fileManager;
}
Context getContext()
{
return _ctx;
}
public JavacTask getJavacTask()
{
return JavacTask.instance( processingEnv );
}
TreeMaker getTreeMaker()
{
return _treeMaker;
}
JavacElements getJavacElements()
{
return _javacElements;
}
private void hijackJavacFileManager()
{
if( !(_fileManager instanceof ManifoldJavaFileManager) )
{
injectManFileManager();
ManifoldHost.initializeAndCompileNonJavaFiles( _jpe, _fileManager, _gosuInputFiles, this::deriveSourcePath, this::deriveClasspath, this::deriveOutputPath );
}
}
private void injectManFileManager()
{
_manFileManager = new ManifoldJavaFileManager( _fileManager, Log.instance( _ctx ), true );
_ctx.put( JavaFileManager.class, (JavaFileManager)null );
_ctx.put( JavaFileManager.class, _manFileManager );
}
private String deriveOutputPath()
{
try
{
String ping = "__dummy__";
//JavaFileObject classFile = _jpe.getFiler().createClassFile( ping );
JavaFileObject classFile = _fileManager.getJavaFileForOutput( StandardLocation.CLASS_OUTPUT, ping, JavaFileObject.Kind.CLASS, null );
if( !isPhysicalFile( classFile ) )
{
return "";
}
File dummyFile = new File( classFile.toUri() );
String path = dummyFile.getAbsolutePath();
path = path.substring( 0, path.length() - (File.separatorChar + ping + ".class").length() );
return path;
}
catch( IOException e )
{
throw new RuntimeException( e );
}
}
private List<String> deriveClasspath()
{
URL[] classpathUrls = ((URLClassLoader)_jpe.getProcessorClassLoader()).getURLs();
List<String> paths = Arrays.stream( classpathUrls )
.map( url ->
{
try
{
return new File( url.toURI() ).getAbsolutePath();
}
catch( URISyntaxException e )
{
throw new RuntimeException( e );
}
} ).collect( Collectors.toList() );
return removeBadPaths( paths );
}
private List<String> removeBadPaths( List<String> paths )
{
// Remove a path that is a parent of another path.
// For instance, "/foo/." is a parent of "/foo/classes", this must be unintentional
List<String> actualPaths = new ArrayList<>();
outer:
for( String path : paths )
{
for( String p : paths )
{
//noinspection StringEquality
String unmodifiedPath = path;
if( path.endsWith( File.separator + '.' ) )
{
path = path.substring( 0, path.length() - 2 );
}
if( p != unmodifiedPath && p.startsWith( path ) )
{
continue outer;
}
}
actualPaths.add( path );
}
return actualPaths;
}
private Set<String> deriveSourcePath()
{
Set<String> sourcePath = new HashSet<>();
deriveSourcePath( _javaInputFiles, sourcePath );
return sourcePath;
}
private void deriveSourcePath( Set<JavaFileObject> inputFiles, Set<String> sourcePath )
{
outer:
for( JavaFileObject inputFile : inputFiles )
{
if( !isPhysicalFile( inputFile ) )
{
continue;
}
for( String sp : sourcePath )
{
if( inputFile.getName().startsWith( sp + File.separatorChar ) )
{
continue outer;
}
}
TypeElement type = findType( inputFile );
if( type != null )
{
String path = derivePath( type, inputFile );
sourcePath.add( path );
}
else
{
_jpe.getMessager().printMessage( Diagnostic.Kind.WARNING, "Could not find type for file: " + inputFile );
}
}
}
private boolean isPhysicalFile( JavaFileObject inputFile )
{
URI uri = inputFile.toUri();
return uri != null && uri.getScheme().equalsIgnoreCase( "file" );
}
private String derivePath( TypeElement type, JavaFileObject inputFile )
{
String filename = inputFile.getName();
int iDot = filename.lastIndexOf( '.' );
String ext = iDot > 0 ? filename.substring( iDot ) : "";
String pathRelativeFile = type.getQualifiedName().toString().replace( '.', File.separatorChar ) + ext;
assert filename.endsWith( pathRelativeFile );
return filename.substring( 0, filename.indexOf( pathRelativeFile ) - 1 );
}
private TypeElement findType( JavaFileObject inputFile )
{
String path = inputFile.getName();
int dotJava = path.lastIndexOf( ".java" );
if( dotJava < 0 )
{
return null;
}
path = path.substring( 0, dotJava );
List<String> tokens = new ArrayList<>();
for( StringTokenizer tokenizer = new StringTokenizer( path, File.separator, false ); tokenizer.hasMoreTokens(); )
{
tokens.add( tokenizer.nextToken() );
}
String typeName = "";
TypeElement type = null;
for( int i = tokens.size() - 1; i >= 0; i
{
typeName = tokens.get( i ) + typeName;
TypeElement csr = getType( typeName );
if( csr != null )
{
type = csr;
}
if( i > 0 )
{
typeName = '.' + typeName;
}
}
return type;
}
private Set<JavaFileObject> fetchJavaInputFiles()
{
try
{
JavaCompiler javaCompiler = JavaCompiler.instance( _ctx );
Field field = javaCompiler.getClass().getDeclaredField( "inputFiles" );
field.setAccessible( true );
//noinspection unchecked
return (Set<JavaFileObject>)field.get( javaCompiler );
}
catch( Exception e )
{
throw new RuntimeException( e );
}
}
private List<String> fetchGosuInputFiles()
{
String property = System.getProperty( GOSU_SOURCE_FILES, "" );
if( !property.isEmpty() )
{
return Arrays.asList( property.split( " " ) );
}
return Collections.emptyList();
}
private TypeElement getType( String className )
{
return _jpe.getElementUtils().getTypeElement( className );
// DeclaredType declaredType = jpe.getTypeUtils().getDeclaredType( typeElement );
// return new ElementTypePair( typeElement, declaredType );
}
@Override
public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv )
{
_typeProcessor.addTypesToProcess( roundEnv );
if( roundEnv.processingOver() )
{
return false;
}
insertBootstrap( roundEnv );
return false;
}
private void insertBootstrap( RoundEnvironment roundEnv )
{
Trees trees = Trees.instance( _jpe );
Set<? extends Element> elements = roundEnv.getRootElements();
for( Element elem : elements )
{
if( elem.getKind() == ElementKind.CLASS )
{
JCTree tree = (JCTree)trees.getTree( elem );
TreeTranslator visitor = new BootstrapInserter( this );
tree.accept( visitor );
}
}
}
} |
package bisq.network;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.net.discovery.PeerDiscovery;
import org.bitcoinj.net.discovery.PeerDiscoveryException;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
/**
* Socks5SeedOnionDiscovery provides a list of known Bitcoin .onion seeds.
* These are nodes running as hidden services on the Tor network.
*/
public class Socks5SeedOnionDiscovery implements PeerDiscovery {
private InetSocketAddress[] seedAddrs;
/**
* Supports finding peers by hostname over a socks5 proxy.
*
* @param proxy proxy the socks5 proxy to connect over.
* @param params param to be used for seed and port information.
*/
public Socks5SeedOnionDiscovery(@SuppressWarnings("UnusedParameters") Socks5Proxy proxy, NetworkParameters params) {
// We do this because NetworkParameters does not contain any .onion
// seeds. Perhaps someday...
String[] seedAddresses = {};
switch (params.getId()) {
case NetworkParameters.ID_MAINNET:
seedAddresses = mainNetSeeds();
break;
case NetworkParameters.ID_TESTNET:
seedAddresses = testNet3Seeds();
break;
}
this.seedAddrs = convertAddrsString(seedAddresses, params.getPort());
}
/**
* returns .onion nodes available on mainnet
*/
private String[] mainNetSeeds() {
// List copied from bitcoin-core on 2017-11-03
return new String[]{
"226eupdnaouu4h2v.onion",
"2frgxpe5mheghyom.onion",
"3ihjnsvwc3x6dp2o.onion",
"3w77hrilg6q64opl.onion",
"4ls4o6iszcd7mkfw.onion",
"4p3abjxqppzxi7qi.onion",
"546esc6botbjfbxb.onion",
"5msftytzlsskr4ut.onion",
"5ty6rxpgrkmdnk4a.onion",
"akmqyuidrf56ip26.onion",
"alhlegtjkdmbqsvt.onion",
"bafk5ioatlgt7dgl.onion",
"bup5n5e3kurvjzf3.onion",
"cjygd7pu5lqkky5j.onion",
"cyvpgt25274i5b7c.onion",
"dekj4wacywpqsad3.onion",
"dqpxwlpnv3z3hznl.onion",
"drarzpycbtxwbcld.onion",
"drp4pvejybx2ejdr.onion",
"dxkmtmwiq7ddtgul.onion",
"e6j57zkyibu2smad.onion",
"ejcqevujcqltqn7d.onion",
"eqgbt2ghfvsshbvo.onion",
"fgizgkdnndilo6ka.onion",
"fqxup4oev33eeidg.onion",
"gb5ypqt63du3wfhn.onion",
"ggdy2pb2avlbtjwq.onion",
"hahhloezyfqh3hci.onion",
"ihdv6bzz2gx72fs7.onion",
"in7r5ieo7ogkxbne.onion",
"kvd44sw7skb5folw.onion",
"mn744hbioayn3ojs.onion",
"ms4ntrrisfxzpvmy.onion",
"n5lqwpjabqg62ihx.onion",
"o4sl5na6jeqgi3l6.onion",
"omjv24nbck4k5ud6.onion",
"po3j2hfkmf7sh36o.onion",
"psco6bxjewljrczx.onion",
"qi5yr6lvlckzffor.onion",
"qlv6py6hdtzipntn.onion",
"qynmpgdbp23xyfnj.onion",
"rhtawcs7xak4gi3t.onion",
"rjacws757ai66lre.onion",
"rjlnp3hwvrsmap6e.onion",
"rkdvqcrtfv6yt4oy.onion",
"rlafimkctvz63llg.onion",
"rlj4ppok4dnsdu5n.onion",
"seoskudzk6vn6mqz.onion",
"tayqi57tfiy7x3vk.onion",
"tchop676j6yppwwm.onion",
"trrtyp3sirmwttyu.onion",
"tx4zd7d5exonnblh.onion",
"u4ecb7txxi6l3gix.onion",
"umcxcmfycvejw264.onion",
"v7xqd42ocemalurd.onion",
"vb267mt3lnwfdmdb.onion",
"vev3n5fxfrtqj6e5.onion",
"visevrizz3quyagj.onion",
"vpg6p5e5ln33dqtp.onion",
"vr2ruasinafoy3fl.onion",
"x6pthvd5x6abyfo7.onion",
"xbwbzrspvav7u5ie.onion",
"xfcevnql2chnawko.onion",
"ycivnom44dmxx4ob.onion",
"yzdvlv5daitafekn.onion"
};
}
/**
* returns .onion nodes available on testnet3
*/
private String[] testNet3Seeds() {
// this list copied from bitcoin-core on 2017-01-19
return new String[]{
"thfsmmn2jbitcoin.onion",
"it2pj4f7657g3rhi.onion",
"nkf5e6b7pl4jfd4a.onion",
"4zhkir2ofl7orfom.onion",
"t6xj6wilh4ytvcs7.onion",
"i6y6ivorwakd7nw3.onion",
"ubqj4rsu3nqtxmtp.onion"
};
}
/**
* returns .onion nodes available on mainnet
*/
private String[] LitecoinMainNetSeeds() {
return new String[]{
};
}
/**
* returns .onion nodes available on testnet3
*/
private String[] LitecoinTestNet4Seeds() {
return new String[]{
};
}
/**
* Returns an array containing all the Bitcoin nodes within the list.
*/
@Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
if (services != 0)
throw new PeerDiscoveryException("DNS seeds cannot filter by services: " + services);
return seedAddrs;
}
/**
* Converts an array of hostnames to array of unresolved InetSocketAddress
*/
private InetSocketAddress[] convertAddrsString(String[] addrs, int port) {
InetSocketAddress[] list = new InetSocketAddress[addrs.length];
for (int i = 0; i < addrs.length; i++) {
list[i] = InetSocketAddress.createUnresolved(addrs[i], port);
}
return list;
}
@Override
public void shutdown() {
//TODO should we add a DnsLookupTor.shutdown() ?
}
} |
package com.beowulfe.hap.accessories;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import com.beowulfe.hap.*;
import com.beowulfe.hap.impl.services.OutletService;
/**
* A power outlet with boolean power and usage states.
*
* @author Andy Lintner
*/
public interface Outlet extends HomekitAccessory {
@Override
default public Collection<Service> getServices() {
return Collections.singleton(new OutletService(this));
}
/**
* Retrieves the current binary state of the outlet's power.
* @return a future that will contain the binary state
*/
public CompletableFuture<Boolean> getPowerState();
/**
* Retrieves the current binary state indicating whether the outlet is in use.
* @return a future that will contain the binary state
*/
public CompletableFuture<Boolean> getOutletInUse();
/**
* Sets the binary state of the outlet's power.
* @param state the binary state to set
* @return a future that completes when the change is made
* @throws Exception when the change cannot be made
*/
public CompletableFuture<Void> setPowerState(boolean state) throws Exception;
/**
* Subscribes to changes in the binary state of the outlet's power.
* @param callback the function to call when the state changes.
*/
public void subscribePowerState(HomekitCharacteristicChangeCallback callback);
/**
* Subscribes to changes in the binary state indicating whether the outlet is in use.
* @param callback the function to call when the state changes.
*/
public void subscribeOutletInUse(HomekitCharacteristicChangeCallback callback);
/**
* Unsubscribes from changes in the binary state of the outlet's power.
*/
public void unsubscribePowerState();
/**
* Unsubscribes from changes in the binary state indicating whether hte outlet is in use.
*/
public void unsubscribeOutletInUse();
} |
package com.incidentlocator.client;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.provider.Settings;
import android.util.Log;
import java.text.DecimalFormat;
public class IncidentLocator extends Activity
{
private static final String TAG = "IncidentLocator";
protected LocationManager locationManager;
protected final LocationListener locationListener = new GetLocationListener();
private static Location location;
private EditText coordinatesBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
coordinatesBox = (EditText) findViewById(R.id.show_message);
locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onStart() {
super.onStart();
// check if GPS is enabled
boolean isGpsEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (! isGpsEnabled) {
promptOpenLocationSettings("GPS is disabled. Do you want to enable it?");
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
public void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}
public class GetLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
location = loc;
Log.d(TAG, "[GPS]" + location.toString());
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
public void getLocation(View view) {
StringBuilder sb = new StringBuilder(512);
if (location == null) {
sb.append("waiting location data...\n");
} else {
DecimalFormat df = new DecimalFormat(".000000");
df.setRoundingMode(java.math.RoundingMode.DOWN);
sb
.append("Lat: ")
.append(df.format(location.getLatitude()))
.append("Lng: ")
.append(df.format(location.getLongitude()))
.append("\n");
}
coordinatesBox.append(sb.toString());
}
private void promptOpenLocationSettings(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(message)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// intent to open settings
Intent settings = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settings);
}
});
AlertDialog alert = builder.create();
alert.show();
}
} |
package de.gurkenlabs.litiengine.sound;
import java.awt.geom.Point2D;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.util.MathUtilities;
import de.gurkenlabs.util.geom.GeometricUtilities;
/**
* This class is responsible for the playback of all sounds in the engine. If
* specified, it calculates the sound volume and pan depending to the assigned
* entity or location.
*/
public class SoundSource {
private static final Logger log = Logger.getLogger(SoundSource.class.getName());
private static final ExecutorService executorServie;
protected static final SourceDataLineCloseQueue closeQueue;
private SourceDataLine dataLine;
private IEntity entity;
private float gain;
private FloatControl gainControl;
private final Point2D initialListenerLocation;
private Point2D location;
private FloatControl panControl;
private boolean played;
private boolean playing;
private final Sound sound;
private PlayRunnable runnable;
static {
closeQueue = new SourceDataLineCloseQueue();
closeQueue.start();
executorServie = Executors.newCachedThreadPool();
}
protected SoundSource(final Sound sound) {
this(sound, null);
}
protected SoundSource(final Sound sound, final Point2D listenerLocation) {
this.sound = sound;
this.initialListenerLocation = listenerLocation;
}
protected SoundSource(final Sound sound, final Point2D listenerLocation, final IEntity sourceEntity) {
this(sound, listenerLocation);
this.entity = sourceEntity;
}
protected SoundSource(final Sound sound, final Point2D listenerLocation, final Point2D location) {
this(sound, listenerLocation);
this.location = location;
}
public void dispose() {
if (this.dataLine != null) {
closeQueue.enqueue(this.dataLine);
this.dataLine = null;
this.gainControl = null;
this.panControl = null;
}
}
public Sound getSound() {
return this.sound;
}
public boolean isPlaying() {
return this.played || this.playing;
}
/**
* Plays the sound without any volume or pan adjustments.
*/
public void play() {
this.play(false, null, -1);
}
public void interrupt() {
runnable.setCancelled(true);
}
/**
* Loops the sound with the specified volume.
*
* @param loop
* @param volume
*/
public void play(final boolean loop, final float volume) {
this.play(loop, null, volume);
}
public void play(final boolean loop, final Point2D location, final float gain) {
// clip must be disposed
if (this.dataLine != null) {
return;
}
this.gain = gain;
this.location = location;
this.runnable = new PlayRunnable(loop);
executorServie.execute(this.runnable);
this.played = true;
}
protected static void terminate() {
closeQueue.terminate();
}
protected void updateControls(final Point2D listenerLocation) {
if (listenerLocation == null) {
return;
}
final Point2D loc = this.entity != null ? this.entity.getLocation() : this.location;
if (loc == null) {
return;
}
this.setGain(calculateGain(loc, listenerLocation));
this.setPan(calculatePan(loc, listenerLocation));
}
private static float calculateGain(final Point2D currentLocation, final Point2D listenerLocation) {
if (currentLocation == null || listenerLocation == null) {
return 0;
}
float gain;
final float distanceFromListener = (float) currentLocation.distance(listenerLocation);
if (distanceFromListener <= 0) {
gain = 1.0f;
} else if (distanceFromListener >= Game.getSoundEngine().getMaxDistance()) {
gain = 0.0f;
} else {
gain = 1.0f - distanceFromListener / Game.getSoundEngine().getMaxDistance();
}
gain = MathUtilities.clamp(gain, 0, 1);
gain *= Game.getConfiguration().sound().getSoundVolume();
return gain;
}
private static float calculatePan(final Point2D currentLocation, final Point2D listenerLocation) {
final double angle = GeometricUtilities.calcRotationAngleInDegrees(listenerLocation, currentLocation);
return (float) -Math.sin(angle);
}
protected void setGain(final float g) {
// Make sure there is a gain control
if (this.gainControl == null) {
return;
}
// make sure the value is valid (between 0 and 1)
final float newGain = MathUtilities.clamp(g, 0, 1);
final double minimumDB = this.gainControl.getMinimum();
final double maximumDB = 1;
// convert the supplied linear gain into a "decible change" value
// minimumDB is no volume
// maximumDB is maximum volume
// (Number of decibles is a logrithmic function of linear gain)
final double ampGainDB = 10.0f / 20.0f * maximumDB - minimumDB;
final double cste = Math.log(10.0) / 20;
final float valueDB = (float) (minimumDB + 1 / cste * Math.log(1 + (Math.exp(cste * ampGainDB) - 1) * newGain));
// Update the gain:
this.gainControl.setValue(valueDB);
}
private void setPan(final float p) {
// Make sure there is a pan control
if (this.panControl == null) {
return;
}
final float pan = MathUtilities.clamp(p, -1, 1);
// Update the pan:
this.panControl.setValue(pan);
}
private class PlayRunnable implements Runnable {
private boolean loop;
private boolean cancelled;
public PlayRunnable(final boolean loop) {
this.loop = loop;
}
@Override
public void run() {
this.loadDataLine();
if (SoundSource.this.dataLine == null) {
return;
}
this.initControls();
this.initGain();
SoundSource.this.updateControls(SoundSource.this.initialListenerLocation);
SoundSource.this.dataLine.start();
SoundSource.this.played = false;
SoundSource.this.playing = true;
final byte[] buffer = new byte[1024];
ByteArrayInputStream str = new ByteArrayInputStream(SoundSource.this.sound.getStreamData());
while (!this.cancelled) {
int readCount;
try {
readCount = str.read(buffer);
if (readCount < 0) {
if (!this.loop || SoundSource.this.dataLine == null) {
break;
}
restartDataLine();
str = new ByteArrayInputStream(SoundSource.this.sound.getStreamData());
} else if (SoundSource.this.dataLine != null) {
SoundSource.this.dataLine.write(buffer, 0, readCount);
}
} catch (final IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (SoundSource.this.dataLine != null) {
SoundSource.this.dataLine.drain();
}
SoundSource.this.playing = false;
}
private void initGain() {
final float initialGain = SoundSource.this.gain > 0 ? SoundSource.this.gain : Game.getConfiguration().sound().getSoundVolume();
SoundSource.this.setGain(initialGain);
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
private void loadDataLine() {
final DataLine.Info dataInfo = new DataLine.Info(SourceDataLine.class, SoundSource.this.sound.getFormat());
try {
SoundSource.this.dataLine = (SourceDataLine) AudioSystem.getLine(dataInfo);
SoundSource.this.dataLine.open();
} catch (final LineUnavailableException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
private void restartDataLine() {
SoundSource.this.dataLine.drain();
this.loadDataLine();
this.initControls();
this.initGain();
SoundSource.this.dataLine.start();
}
private void initControls() {
if (SoundSource.this.dataLine == null) {
return;
}
// Check if panning is supported:
try {
if (!SoundSource.this.dataLine.isControlSupported(FloatControl.Type.PAN)) {
SoundSource.this.panControl = null;
} else {
// Create a new pan Control:
SoundSource.this.panControl = (FloatControl) SoundSource.this.dataLine.getControl(FloatControl.Type.PAN);
}
} catch (final IllegalArgumentException iae) {
SoundSource.this.panControl = null;
}
// Check if changing the volume is supported:
try {
if (!SoundSource.this.dataLine.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
SoundSource.this.gainControl = null;
} else {
// Create a new gain control:
SoundSource.this.gainControl = (FloatControl) SoundSource.this.dataLine.getControl(FloatControl.Type.MASTER_GAIN);
// Store it's initial gain to use as "maximum volume" later:
}
} catch (final IllegalArgumentException iae) {
SoundSource.this.gainControl = null;
}
}
}
private static class SourceDataLineCloseQueue extends Thread {
private boolean isRunning = true;
private final Queue<SourceDataLine> queue = new ConcurrentLinkedQueue<>();
public void enqueue(final SourceDataLine clip) {
this.queue.add(clip);
}
@Override
public void run() {
while (this.isRunning) {
while (this.queue.peek() != null) {
final SourceDataLine clip = this.queue.poll();
clip.stop();
clip.flush();
clip.close();
}
try {
Thread.sleep(50);
} catch (final InterruptedException e) {
this.interrupt();
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (!this.queue.isEmpty()) {
for (final SourceDataLine line : this.queue) {
line.stop();
line.flush();
line.close();
}
}
}
public void terminate() {
this.isRunning = false;
}
}
} |
package com.intellij.psi.stubs;
import com.intellij.psi.PsiNamedElement;
import com.intellij.util.io.StringRef;
/**
* @author yole
*/
public abstract class NamedStubBase<T extends PsiNamedElement> extends StubBase<T> implements NamedStub<T> {
private final StringRef myName;
protected NamedStubBase(StubElement parent, IStubElementType elementType, StringRef name) {
super(parent, elementType);
myName = name;
}
protected NamedStubBase(final StubElement parent, final IStubElementType elementType, final String name) {
this(parent, elementType, StringRef.fromString(name));
}
public String getName() {
return myName.getString();
}
} |
package mb.p_raffrayi.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.metaborg.util.future.CompletableFuture;
import org.metaborg.util.future.IFuture;
import org.metaborg.util.unit.Unit;
import mb.p_raffrayi.IUnitResult;
import mb.p_raffrayi.actors.IActor;
import mb.p_raffrayi.actors.IActorRef;
import mb.p_raffrayi.impl.diff.RemovingDiffer;
import mb.p_raffrayi.nameresolution.DataLeq;
import mb.p_raffrayi.nameresolution.DataWf;
import mb.scopegraph.ecoop21.LabelOrder;
import mb.scopegraph.ecoop21.LabelWf;
import mb.scopegraph.oopsla20.diff.BiMap;
import mb.scopegraph.oopsla20.diff.BiMap.Immutable;
import mb.scopegraph.oopsla20.reference.Env;
import mb.scopegraph.oopsla20.terms.newPath.ScopePath;
public class PhantomUnit<S, L, D> extends AbstractUnit<S, L, D, Unit> {
private final IUnitResult<S, L, D, ?> previousResult;
public PhantomUnit(IActor<? extends IUnit<S, L, D, Unit>> self, IActorRef<? extends IUnit<S, L, D, ?>> parent,
IUnitContext<S, L, D> context, Iterable<L> edgeLabels, IUnitResult<S, L, D, ?> previousResult) {
super(self, parent, context, edgeLabels);
this.previousResult = previousResult;
}
@Override public IFuture<IUnitResult<S, L, D, Unit>> _start(List<S> rootScopes) {
doStart(rootScopes);
initDiffer(new RemovingDiffer<>(previousResult.scopeGraph(), differOps()), rootScopes,
previousResult.rootScopes());
// Add Phantom unit for all previous subunits.
for(Map.Entry<String, IUnitResult<S, L, D, ?>> entry : previousResult.subUnitResults().entrySet()) {
this.<Unit>doAddSubUnit(entry.getKey(),
(subself, subcontext) -> new PhantomUnit<>(subself, self, subcontext, edgeLabels, entry.getValue()),
new ArrayList<>(), true);
}
return doFinish(CompletableFuture.completedFuture(Unit.unit));
}
@Override public IFuture<Env<S, L, D>> _queryPrevious(ScopePath<S, L> path, LabelWf<L> labelWF,
DataWf<S, L, D> dataWF, LabelOrder<L> labelOrder, DataLeq<S, L, D> dataEquiv) {
return doQueryPrevious(previousResult.scopeGraph(), path, labelWF, dataWF, labelOrder, dataEquiv);
}
@Override public IFuture<StateSummary<S>> _requireRestart() {
return CompletableFuture.completedFuture(StateSummary.released());
}
@Override public void _release(Immutable<S> patches) {
// ignore
}
@Override public void _restart() {
// ignore
}
@Override public IFuture<Optional<Immutable<S>>> _confirm(ScopePath<S, L> path, LabelWf<L> labelWF,
DataWf<S, L, D> dataWF, boolean prevEnvEmpty) {
if(prevEnvEmpty) {
return CompletableFuture.completedFuture(Optional.of(BiMap.Immutable.of()));
}
return doQueryPrevious(previousResult.scopeGraph(), path, labelWF, dataWF, LabelOrder.none(), DataLeq.any()).thenApply(env -> {
return env.isEmpty() ? Optional.of(BiMap.Immutable.of()) : Optional.empty();
});
}
@Override protected IFuture<D> getExternalDatum(D datum) {
return CompletableFuture.completedFuture(datum);
}
} |
package com.bloatit.framework;
import com.bloatit.model.Member;
import com.bloatit.model.exceptions.ElementNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class MemberManager {
private final static ArrayList<Member> members = new ArrayList<Member>();
static {
members.add(new Member(1, "Yoann", "yplenet@gmail.com", "Yoann Plénet", -14413));
members.add(new Member(1, "Fred", "fred@gmail.com", "Frédéric Bertolus", 12));
members.add(new Member(1, "Tom", "tom@gmail.com", "Thomas Guyard", 3000000000000000000L));
}
public static Member getMemberByLogin(String login) throws ElementNotFoundException {
for (Member m : members) {
if (login.equalsIgnoreCase(m.getLogin())) {
return m;
}
}
throw new ElementNotFoundException();
}
public static boolean existsMember(String login){
for (Member m : members) {
if (login.equals(m.getLogin())) {
return true;
}
}
return false;
}
public static List<Member> getMemberList() {
return members;
}
} |
package com.incidentlocator.client;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.provider.Settings;
import android.util.Log;
import java.text.DecimalFormat;
public class IncidentLocator extends Activity
{
private static final String TAG = "IncidentLocator";
protected LocationManager locationManager;
protected final LocationListener locationListener = new GetLocationListener();
private static Location location;
private EditText coordinatesBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
coordinatesBox = (EditText) findViewById(R.id.show_message);
locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onStart() {
super.onStart();
// check if GPS is enabled
boolean isGpsEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (! isGpsEnabled) {
// create a new dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("GPS is disabled. Do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// intent to open settings
Intent settings = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settings);
}
});
AlertDialog alert = builder.create();
alert.show();
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
public void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}
public class GetLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
location = loc;
Log.d(TAG, "[GPS]" + location.toString());
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
public void getLocation(View view) {
DecimalFormat df = new DecimalFormat(".000000");
df.setRoundingMode(java.math.RoundingMode.DOWN);
StringBuilder sb = new StringBuilder(512);
sb
.append("Lat: ")
.append(df.format(location.getLatitude()))
.append("Lng: ")
.append(df.format(location.getLongitude()))
.append("\n");
coordinatesBox.append(sb.toString());
}
} |
package org.micromanager.imageDisplay;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import ij.ImagePlus;
import ij.gui.StackWindow;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.Point;
import java.awt.Toolkit;
import java.lang.StackTraceElement;
import java.lang.Thread;
import javax.swing.SwingConstants;
import javax.swing.event.MouseInputAdapter;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicArrowButton;
import net.miginfocom.swing.MigLayout;
import org.micromanager.internalinterfaces.DisplayControls;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.utils.ReportingUtils;
/**
* This class is the Frame that handles image viewing: it contains the
* canvas and controls for determining which channel, Z-slice, etc. is shown.
* HACK: we have overridden getComponents() on this function to "fix" bugs
* in other bits of code; see that function's comment.
*/
public class DisplayWindow extends StackWindow {
private boolean closed_ = false;
private EventBus bus_;
// This class is used to signal that a window is closing.
public static class RequestToCloseEvent {
public DisplayWindow window_;
public RequestToCloseEvent(DisplayWindow window) {
window_ = window;
}
};
public DisplayWindow(final ImagePlus ip, DisplayControls controls,
EventBus bus) {
super(ip);
// HACK: hide ImageJ's native scrollbars; we provide our own.
if (cSelector != null) {
remove(cSelector);
}
if (tSelector != null) {
remove(tSelector);
}
if (zSelector != null) {
remove(zSelector);
}
// Override the default layout with our own, so we can do more
// customized controls.
// This layout is intended to minimize distances between elements.
setLayout(new MigLayout("insets 1, fillx"));
// Re-add the ImageJ canvas.
add(ic, "align center, wrap");
add(controls, "align center, wrap");
pack();
// Add a listener so we can update the histogram when an ROI is drawn.
ic.addMouseListener(new MouseInputAdapter() {
@Override
public void mouseReleased(MouseEvent me) {
if (ip instanceof MMCompositeImage) {
((MMCompositeImage) ip).updateAndDraw(true);
} else {
ip.updateAndDraw();
}
}
});
setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(this);
bus_ = bus;
bus.register(this);
zoomToPreferredSize();
}
/**
* Set our canvas' magnification based on the preferred window
* magnification.
*/
private void zoomToPreferredSize() {
Point location = getLocation();
setLocation(new Point(0,0));
double mag = MMStudioMainFrame.getInstance().getPreferredWindowMag();
if (mag < ic.getMagnification()) {
while (mag < ic.getMagnification()) {
ic.zoomOut(ic.getWidth() / 2, ic.getHeight() / 2);
}
} else if (mag > ic.getMagnification()) {
while (mag > ic.getMagnification()) {
ic.zoomIn(ic.getWidth() / 2, ic.getHeight() / 2);
}
}
//Make sure the window is fully on the screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point newLocation = new Point(location.x,location.y);
if (newLocation.x + getWidth() > screenSize.width && getWidth() < screenSize.width) {
newLocation.x = screenSize.width - getWidth();
}
if (newLocation.y + getHeight() > screenSize.height && getHeight() < screenSize.height) {
newLocation.y = screenSize.height - getHeight();
}
setLocation(newLocation);
}
@Override
public boolean close() {
windowClosing(null);
return closed_;
}
@Override
public void windowClosing(WindowEvent e) {
if (!closed_) {
bus_.post(new RequestToCloseEvent(this));
}
}
/**
* Our controls have changed size; repack the window.
*/
@Subscribe
public void onLayoutChange(ScrollerPanel.LayoutChangedEvent event) {
pack();
}
// Force this window to go away.
public void forceClosed() {
try {
super.close();
} catch (NullPointerException ex) {
ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window");
}
MMStudioMainFrame.getInstance().removeMMBackgroundListener(this);
closed_ = true;
}
@Override
public void windowClosed(WindowEvent E) {
try {
super.windowClosed(E);
} catch (NullPointerException ex) {
ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window");
}
}
@Override
public void windowActivated(WindowEvent e) {
if (!isClosed()) {
super.windowActivated(e);
}
}
/**
* HACK HACK HACK HACK HACK HACK ACK HACK HACK HACK HACK HACK ACK HACK
* We override this function to "fix" the Orthogonal Views plugin, which
* assumes that item #2 in the array returned by getComponents() is the
* cSelector object of an ImageJ StackWindow. Of course, actually changing
* this behavior for everyone else causes *them* to break horribly, hence
* why we have to examine the stack trace to determine our caller. Ugh!
* HACK HACK HACK HACK HACK HACK ACK HACK HACK HACK HACK HACK ACK HACK
*/
@Override
public Component[] getComponents() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (StackTraceElement element : stack) {
if (element.getClassName().contains("Orthogonal_Views")) {
return new Component[] {ic, cSelector};
}
}
return super.getComponents();
}
} |
package com.comandante.creeper;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.stream.Collectors;
public class CreeperUtils {
public static String asciiColorPattern = "\u001B\\[[;\\d]*m";
public static String printStringsNextToEachOther(List<String> inputStrings, String seperator) {
// Find the "longest", meaning most newlines string.
final String[] maxHeightLine = {inputStrings.get(0)};
inputStrings.forEach(s -> {
int height = splitToArrayLines(s).size();
if (maxHeightLine[0] != null && height > splitToArrayLines(maxHeightLine[0]).size()) {
maxHeightLine[0] = s;
}
});
final int[] maxLineLength = {0};
// Split all of the strings, to create a List of a List Of Strings
// Make them all even length. This is terrible streams api usage.
// remove any hidden ascii color characters as they mess with the line length math
List<List<String>> textToJoin =
inputStrings.stream()
.map(CreeperUtils::splitToArrayLines)
.map(strings -> {
maxLineLength[0] = getLongestStringLength(strings);
List<String> newStrings = Lists.newArrayList();
strings.forEach(s -> {
int diff = maxLineLength[0] - removeAllAsciiColorCodes(s).length();
String whiteSpacePadded = addTrailingWhiteSpace(s, diff);
newStrings.add(whiteSpacePadded);
});
return newStrings;
}).collect(Collectors.toList());
// Go through and piece together the lines, by removing the top of each list and concatenating it
final StringBuilder[] outputBuilder = {new StringBuilder()};
List<String> splitLines = splitToArrayLines(maxHeightLine[0]);
splitLines.forEach(s -> {
textToJoin.forEach(listOfLines -> {
if (listOfLines.size() > 0) {
String nextLine = listOfLines.remove(0);
outputBuilder[0].append(nextLine);
outputBuilder[0].append(seperator);
} else {
outputBuilder[0].append(seperator);
}
});
outputBuilder[0].append("\r\n");
String formatted = outputBuilder[0].toString();
outputBuilder[0] = new StringBuilder(replaceLast(formatted, seperator + "\r\n", "\r\n"));
});
return outputBuilder[0].toString();
}
public static int getLongestStringLength(List<String> strings) {
final int[] maxLineLength = {0};
strings.forEach(s -> {
if (s.replaceAll(asciiColorPattern, "").length() > maxLineLength[0]) {
maxLineLength[0] = s.replaceAll(asciiColorPattern, "").length();
}
});
return maxLineLength[0];
}
public static String addTrailingWhiteSpace(String s, int numberOfWhiteSpace) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < numberOfWhiteSpace; i++) {
sb.append(" ");
}
return sb.toString();
}
public static String removeAllAsciiColorCodes(String s) {
return s.replaceAll(asciiColorPattern, "");
}
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos) + replacement + string.substring(pos + toReplace.length(), string.length());
} else {
return string;
}
}
public static List<String> splitToArrayLines(String s) {
return Lists.newArrayList(s.split("[\\r\\n]+"));
}
public static String trimTrailingBlanks(String str) {
if (str == null) {
return null;
}
int len = str.length();
for (; len > 0; len
if (!Character.isWhitespace(str.charAt(len - 1))) {
break;
}
}
return str.substring(0, len);
}
} |
package com.michaldabski.fileexplorer;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.michaldabski.fileexplorer.clipboard.Clipboard;
import com.michaldabski.fileexplorer.clipboard.Clipboard.ClipboardListener;
import com.michaldabski.fileexplorer.clipboard.ClipboardFileAdapter;
import com.michaldabski.fileexplorer.folders.FolderFragment;
import com.michaldabski.fileexplorer.nav_drawer.NavDrawerAdapter;
import com.michaldabski.fileexplorer.nav_drawer.NavDrawerAdapter.NavDrawerItem;
import com.michaldabski.fileexplorer.nav_drawer.NavDrawerDivider;
import com.michaldabski.fileexplorer.nav_drawer.NavDrawerShortcut;
import com.readystatesoftware.systembartint.SystemBarTintManager;
public class MainActivity extends Activity implements OnItemClickListener, ClipboardListener
{
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private SystemBarTintManager tintManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setIcon(R.drawable.folder_white);
tintManager = new SystemBarTintManager(this);
setupNavDrawer();
Clipboard.getInstance().addListener(this);
}
@Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
@Override
protected void onPause()
{
if (lastFolder != null)
{
FileExplorerApplication application = (FileExplorerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
}
public void setActionbarVisible(boolean visible)
{
if (visible)
{
getActionBar().show();
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.accent_color);
}
else
{
getActionBar().hide();
tintManager.setStatusBarTintEnabled(false);
tintManager.setStatusBarTintResource(android.R.color.transparent);
}
}
private void setupNavDrawer()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;;
@Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
}
@Override
public void onDrawerClosed(View drawerView)
{
actionBarShown=false;
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
onClipboardContentsChange(Clipboard.getInstance());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
listNavigation.setAdapter(new NavDrawerAdapter(this, getNavDrawerItems()));
listNavigation.setOnItemClickListener(this);
// TODO: add favourites
}
List<NavDrawerItem> getNavDrawerItems()
{
return Arrays.asList(
new NavDrawerDivider(getString(R.string.bookmarks)),
new NavDrawerShortcut(new File("/"), getString(R.string.root)),
new NavDrawerShortcut(Environment.getRootDirectory(), getString(R.string.system)),
new NavDrawerShortcut(Environment.getExternalStorageDirectory(), getString(R.string.sd_card)),
new NavDrawerShortcut(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Downloads"),
new NavDrawerShortcut(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "Music"),
new NavDrawerShortcut(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Pictures"),
new NavDrawerShortcut(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "DCIM")
);
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public boolean canGoBack()
{
return getFragmentManager().getBackStackEntryCount() > 0;
}
public void goBack()
{
getFragmentManager().popBackStack();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
menu.findItem(R.id.menu_paste).setVisible(Clipboard.getInstance().isEmpty() == false);
return super.onPrepareOptionsMenu(menu);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerItem item = (NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
break;
default:
break;
}
}
@Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
TextView tvMessage = (TextView) findViewById(R.id.tvClipboardMessage);
if (clipboardListView != null)
{
if (clipboard.isEmpty())
{
clipboardListView.setVisibility(View.GONE);
tvMessage.setVisibility(View.VISIBLE);
}
else
{
clipboardListView.setVisibility(View.VISIBLE);
tvMessage.setVisibility(View.GONE);
clipboardListView.setAdapter(new ClipboardFileAdapter(this, clipboard));
}
}
}
} |
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class CmsNewResourceFolder extends CmsWorkplaceDefault implements I_CmsWpConstants,
I_CmsConstants {
/**
* Indicates if the results of this class are cacheable.
*
* @param cms A_CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
/**
* Overwrites the getContent method of the CmsWorkplaceDefault.<br>
* Gets the content of the new resource page template and processed the data input.
* @param cms The CmsObject.
* @param templateFile The new folder template file
* @param elementName not used
* @param parameters Parameters of the request and the template.
* @param templateSelector Selector of the template tag to be displayed.
* @return Bytearry containing the processed data of the template.
* @exception Throws CmsException if something goes wrong.
*/
public byte[] getContent(A_CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector)
throws CmsException {
// the template to be displayed
String template=null;
HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true);
//get the current filelist
String currentFilelist=(String)session.getValue(C_PARA_FILELIST);
if (currentFilelist==null) {
currentFilelist=cms.rootFolder().getAbsolutePath();
}
// get request parameters
String newFolder=(String)parameters.get(C_PARA_NEWFOLDER);
String title=(String)parameters.get(C_PARA_TITLE);
String navtitle=(String)parameters.get(C_PARA_NAVTITLE);
String navpos=(String)parameters.get(C_PARA_NAVPOS);
// get the current phase of this wizard
String step=cms.getRequestContext().getRequest().getParameter("step");
if (step != null) {
if (step.equals("1")) {
try {
// create the folder
CmsFolder folder=cms.createFolder(currentFilelist,newFolder);
cms.lockResource(folder.getAbsolutePath());
cms.writeMetainformation(folder.getAbsolutePath(),C_METAINFO_TITLE,title);
// now check if navigation informations have to be added to the new page.
if (navtitle != null) {
cms.writeMetainformation(folder.getAbsolutePath(),C_METAINFO_NAVTITLE,navtitle);
// update the navposition.
if (navpos != null) {
updateNavPos(cms,folder,navpos);
}
}
cms.unlockResource(folder.getAbsolutePath());
} catch (CmsException ex) {
throw new CmsException("Error while creating new Folder"+ex.getMessage(),ex.getType(),ex);
}
// TODO: ErrorHandling
// now return to filelist
try {
cms.getRequestContext().getResponse().sendCmsRedirect( getConfigFile(cms).getWorkplaceActionPath()+C_WP_EXPLORER_FILELIST);
} catch (Exception e) {
throw new CmsException("Redirect fails :"+ getConfigFile(cms).getWorkplaceActionPath()+C_WP_EXPLORER_FILELIST,CmsException.C_UNKNOWN_EXCEPTION,e);
}
}
} else {
session.removeValue(C_PARA_FOLDER);
}
// get the document to display
CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms,templateFile);
// process the selected template
return startProcessing(cms,xmlTemplateDocument,"",parameters,template);
}
/**
* Gets the templates displayed in the template select box.
* @param cms The CmsObject.
* @param lang The langauge definitions.
* @param names The names of the new rescources.
* @param values The links that are connected with each resource.
* @param parameters Hashtable of parameters (not used yet).
* @returns The vectors names and values are filled with the information found in the
* workplace.ini.
* @exception Throws CmsException if something goes wrong.
*/
public Integer getTemplates(A_CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters)
throws CmsException {
Vector files=cms.getFilesInFolder(C_CONTENTTEMPLATEPATH);
Enumeration enum=files.elements();
while (enum.hasMoreElements()) {
CmsFile file =(CmsFile)enum.nextElement();
if (file.getState() != C_STATE_DELETED) {
String nicename=cms.readMetainformation(file.getAbsolutePath(),C_METAINFO_TITLE);
if (nicename == null) {
nicename=file.getName();
}
names.addElement(nicename);
values.addElement(file.getAbsolutePath());
}
}
return new Integer(0);
}
/**
* Gets the files displayed in the navigation select box.
* @param cms The CmsObject.
* @param lang The langauge definitions.
* @param names The names of the new rescources.
* @param values The links that are connected with each resource.
* @param parameters Hashtable of parameters (not used yet).
* @returns The vectors names and values are filled with data for building the navigation.
* @exception Throws CmsException if something goes wrong.
*/
public Integer getNavPos(A_CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters)
throws CmsException {
// get the nav information
Hashtable storage = getNavData(cms);
if (storage.size() >0) {
String[] nicenames=(String[])storage.get("NICENAMES");
int count=((Integer)storage.get("COUNT")).intValue();
// finally fill the result vectors
for (int i=0;i<=count;i++) {
names.addElement(nicenames[i]);
values.addElement(nicenames[i]);
}
} else {
values=new Vector();
}
return new Integer(values.size()-1);
}
/**
* Updates the navigation position of all resources in the actual folder.
* @param cms The CmsObject.
* @param newfile The new file added to the nav.
* @param navpos The file after which the new entry is sorted.
*/
private void updateNavPos(A_CmsObject cms, CmsFolder newfolder, String newpos)
throws CmsException {
float newPos=0;
// get the nav information
Hashtable storage = getNavData(cms);
if (storage.size() >0 ) {
String[] nicenames=(String[])storage.get("NICENAMES");
String[] positions=(String[])storage.get("POSITIONS");
int count=((Integer)storage.get("COUNT")).intValue();
// now find the file after which the new file is sorted
int pos=0;
for (int i=0;i<nicenames.length;i++) {
if (newpos.equals((String)nicenames[i])) {
pos=i;
}
}
if (pos < count) {
float low=new Float(positions[pos]).floatValue();
float high=new Float(positions[pos+1]).floatValue();
newPos= (high+low)/2;
} else {
newPos= new Float(positions[pos]).floatValue()+1;
}
} else {
newPos=1;
}
cms.writeMetainformation(newfolder.getAbsolutePath(),C_METAINFO_NAVPOS,new Float(newPos).toString());
}
/**
* Sorts a set of three String arrays containing navigation information depending on
* their navigation positions.
* @param cms Cms Object for accessign files.
* @param filenames Array of filenames
* @param nicenames Array of well formed navigation names
* @param positions Array of navpostions
*/
private void sort(A_CmsObject cms, String[] filenames, String[] nicenames,
String[] positions,int max){
// Sorting algorithm
// This method uses an bubble sort, so replace this with something more
// efficient
for (int i=max-1;i>1;i
for (int j=1;j<i;j++) {
float a=new Float(positions[j]).floatValue();
float b=new Float(positions[j+1]).floatValue();
if (a > b) {
String tempfilename= filenames[j];
String tempnicename = nicenames[j];
String tempposition = positions[j];
filenames[j]=filenames[j+1];
nicenames[j]=nicenames[j+1];
positions[j]=positions[j+1];
filenames[j+1]=tempfilename;
nicenames[j+1]=tempnicename;
positions[j+1]=tempposition;
}
}
}
}
/**
* Gets all required navigation information from the files and subfolders of a folder.
* A file list of all files and folder is created, for all those resources, the navigation
* metainformation is read. The list is sorted by their navigation position.
* @param cms The CmsObject.
* @return Hashtable including three arrays of strings containing the filenames,
* nicenames and navigation positions.
* @exception Throws CmsException if something goes wrong.
*/
private Hashtable getNavData(A_CmsObject cms)
throws CmsException {
HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true);
CmsXmlLanguageFile lang= new CmsXmlLanguageFile(cms);
String[] filenames;
String[] nicenames;
String[] positions;
Hashtable storage=new Hashtable();
CmsFolder folder=null;
CmsFile file=null;
String nicename=null;
String currentFilelist=null;
int count=1;
float max=0;
// get the current folder
currentFilelist=(String)session.getValue(C_PARA_FILELIST);
if (currentFilelist==null) {
currentFilelist=cms.rootFolder().getAbsolutePath();
}
// get all files and folders in the current filelist.
Vector files=cms.getFilesInFolder(currentFilelist);
Vector folders=cms.getSubFolders(currentFilelist);
// combine folder and file vector
Vector filefolders=new Vector();
Enumeration enum=folders.elements();
while (enum.hasMoreElements()) {
folder=(CmsFolder)enum.nextElement();
filefolders.addElement(folder);
}
enum=files.elements();
while (enum.hasMoreElements()) {
file=(CmsFile)enum.nextElement();
filefolders.addElement(file);
}
if (filefolders.size()>0) {
// Create some arrays to store filename, nicename and position for the
// nav in there. The dimension of this arrays is set to the number of
// found files and folders plus two more entrys for the first and last
// element.
filenames=new String[filefolders.size()+2];
nicenames=new String[filefolders.size()+2];
positions=new String[filefolders.size()+2];
//now check files and folders that are not deleted and include navigation
// information
enum=filefolders.elements();
while (enum.hasMoreElements()) {
CmsResource res =(CmsResource)enum.nextElement();
// check if the resource is not marked as deleted
if (res.getState() != C_STATE_DELETED) {
String navpos= cms.readMetainformation(res.getAbsolutePath(),C_METAINFO_NAVPOS);
// check if there is a navpos for this file/folder
if (navpos!= null) {
nicename=cms.readMetainformation(res.getAbsolutePath(),C_METAINFO_NAVTITLE);
if (nicename == null) {
nicename=res.getName();
}
// add this file/folder to the storage.
filenames[count]=res.getAbsolutePath();
nicenames[count]=nicename;
positions[count]=navpos;
if (new Float(navpos).floatValue() > max) {
max = new Float(navpos).floatValue();
}
count++;
}
}
}
} else {
filenames=new String[2];
nicenames=new String[2];
positions=new String[2];
}
// now add the first and last value
filenames[0]="FIRSTENTRY";
nicenames[0]=lang.getDataValue("input.firstelement");
positions[0]="0";
filenames[count]="LASTENTRY";
nicenames[count]=lang.getDataValue("input.lastelement");
positions[count]=new Float(max+1).toString();
// finally sort the nav information.
sort(cms,filenames,nicenames,positions,count);
// put all arrays into a hashtable to return them to the calling method.
storage.put("FILENAMES",filenames);
storage.put("NICENAMES",nicenames);
storage.put("POSITIONS",positions);
storage.put("COUNT",new Integer(count));
return storage;
}
} |
//@author A0112918H
package com.epictodo.engine;
import com.epictodo.logic.CRUDLogic;
import com.epictodo.model.Task;
import java.util.ArrayList;
public class WorkDistributor {
private static CRUDLogic _logic = new CRUDLogic();
private final static String[] COMMAND_EXIT = {"exit", "quit"};
private final static String[] COMMAND_ADD = {"add", "create"};
private final static String[] COMMAND_UPDATE = {"update", "change", "modify"};
private final static String[] COMMAND_DELETE = {"delete", "remove"};
private final static String[] COMMAND_SEARCH = {"search", "find"};
private final static String[] COMMAND_DISPLAY = {"display", "upcoming"};
private final static String[] COMMAND_DISPLAYALL = {"all", "displayall", "showall"};
private final static String[] COMMAND_UNDO = {"undo", "revert"};
private final static String[] COMMAND_REDO = {"redo"};
private final static String[] COMMAND_DONE = {"done", "mark"};
private static final String MSG_INVALID_INPUT = "invalid input";
enum CommandType {
DISPLAY, DISPLAYALL, ADD, DELETE, UPDATE, SEARCH, EXIT, INVALID, NULL, UNDO, REDO, DONE
}
enum KeywordType {
WORD, TIME, OPTION
}
public static boolean loadData() {
try {
return _logic.loadFromFile();
} catch (Exception ex) {
return false;
}
}
/**
* Return message after every command is operated
* If command is not operated successfully, "invalid input" is returned.
*
* @param input User input
* @return Operation result Message.
*/
public static String processCommand(String input) {
String result = "";
ArrayList<Task> list = null;
Task t = null;
// Clear expired timed tasks
_logic.clearExpiredTask();
CommandType command = defineCommandType(input);
input = getInstruction(input);
switch (command) {
case DISPLAY:
return _logic.displayIncompleteTaskList();
case DISPLAYALL:
return _logic.displayAllTaskList();
case ADD:
t = CommandWorker.createTask(input);
result = _logic.createTask(t);
return result;
case DELETE:
case DONE:
case UPDATE:
case SEARCH:
list = searchThroughKeywords(input);
if (list.size() == 0) {
return "Cannnot find '" + input + "'";
}
result = selectItemProcess(list, command);
return result;
case EXIT:
System.exit(0);
break;
case UNDO:
result = _logic.undoMostRecent();
return result;
case INVALID:
// todo: defined all invalid cases
return MSG_INVALID_INPUT;
default:
break;
}
// todo handle invalid input here
return null;
}
/**
* Calls MenuWorker to prompt for user input
* Return operation result message
*
* @param list list of possible option from the search result
* @param commandType Defined user command type
* @return result message.
*/
private static String selectItemProcess(ArrayList<Task> list, CommandType commandType) {
String result = null;
Task tempTask = null;
try {
tempTask = MenuWorker.selectItemFromList(commandType, list,
_logic.displayList(list));
} catch (IndexOutOfBoundsException iobe) {
return MSG_INVALID_INPUT;
}
result = processCommand(commandType, tempTask);
return result;
}
/**
* Calls CRUDLogic class to process the task
* Return proper result message given from CRUDLogic
*
* @param command System defined command type
* @param task Y coordinate of position.
* @return Operation result message
*/
private static String processCommand(CommandType command, Task task) {
String result = "";
switch (command) {
case DELETE:
result = _logic.deleteTask(task);
break;
case DONE:
result = _logic.markAsDone(task);
break;
case UPDATE:
Task updatedTask = MenuWorker.updateTask(task);
if (updatedTask != null) {
result = _logic.updateTask(task, updatedTask);
}
break;
case SEARCH:
result = task.getDetail();
break;
default:
break;
}
return result;
}
/**
* Calls CRUDLogic search by using the keywords
* Return a list of tasks from the searches
*
* @param keyword the key words from user input
* @return list of possible tasks base on the search result.
*/
private static ArrayList<Task> searchThroughKeywords(String keyword) {
ArrayList<Task> list = new ArrayList<Task>();
Task tempTask = _logic.translateWorkingListId(keyword);
String date = CommandWorker.getDateViaNlp(keyword);
KeywordType keywordType = CommandWorker.getKeywordType(tempTask, date);
switch (keywordType) {
case WORD:
list = _logic.getTasksByName(keyword);
break;
case TIME:
list = _logic.getTasksByDate(date);
break;
case OPTION:
list.add(tempTask);
break;
}
return list;
}
/**
* Return CommandType base on the command given from the input
*
* @param input user input
* @return Command type
*/
private static CommandType defineCommandType(String input) {
//retrieve command key from the user input
String command = getCommand(input);
//match them with proper command type
if (compareString(command, ""))
return CommandType.NULL;
else if (matchCommand(command, COMMAND_ADD)) {
return CommandType.ADD;
} else if (matchCommand(command, COMMAND_DELETE)) {
return CommandType.DELETE;
} else if (matchCommand(command, COMMAND_UPDATE)) {
return CommandType.UPDATE;
} else if (matchCommand(command, COMMAND_SEARCH)) {
return CommandType.SEARCH;
} else if (matchCommand(command, COMMAND_DISPLAY)) {
return CommandType.DISPLAY;
} else if (matchCommand(command, COMMAND_DISPLAYALL)) {
return CommandType.DISPLAYALL;
} else if (matchCommand(command, COMMAND_EXIT)) {
return CommandType.EXIT;
} else if (matchCommand(command, COMMAND_UNDO)) {
return CommandType.UNDO;
} else if (matchCommand(command, COMMAND_REDO)) {
return CommandType.REDO;
} else if (matchCommand(command, COMMAND_DONE)) {
return CommandType.DONE;
} else {
return CommandType.INVALID;
}
}
/**
* Return true when the command matches with the vocab or its synonyms
* if it does not match with each other, false is returned
*
* @param command System define command.
* @param vocabs command key and its synonyms
* @return Boolean.
*/
private static boolean matchCommand(String command, final String[] vocabs) {
for (int i = 0; i < vocabs.length; i++) {
if (compareString(command, vocabs[i])) {
return true;
}
}
return false;
}
/**
* Return true if both strings are the same
*
* @param text1 First String to be compared.
* @param text2 Second String to be compared.
* @return true/false
*/
private static boolean compareString(String text1, String text2) {
return (text1.equalsIgnoreCase(text2));
}
private static String getInstruction(String input) {
return input.substring(getCommandLength(input), input.length()).trim();
}
/**
* Return command length.
*
* @param instruc user's input.
* @return commands length.
*/
private static int getCommandLength(String instruc) {
String commandTypeString = instruc.trim().split("\\s+")[0];
return commandTypeString.length();
}
/**
* Return command type.
*
* @param instruc user's input.
* @return commands.
*/
private static String getCommand(String instruc) {
String commandTypeString = instruc.trim().split("\\s+")[0];
return commandTypeString;
}
} |
package com.redpois0n.gitj.ui.components;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
import com.redpois0n.git.Chunk;
import com.redpois0n.git.CodeLine;
import com.redpois0n.git.Diff;
@SuppressWarnings("serial")
public class DiffPanel extends JPanel {
private Diff diff;
public DiffPanel(Diff diff) {
this.diff = diff;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int prefWidth = 0;
int prefHeight = 0;
FontMetrics metrics = g.getFontMetrics(g.getFont());
for (Chunk chunk : diff.getChunks()) {
prefHeight += 10;
for (CodeLine line : chunk.getLines()) {
int sw = metrics.stringWidth(line.getLine());
if (sw > prefWidth) {
prefWidth = sw;
}
prefHeight += metrics.getHeight() + 2;
}
}
int y = 0;
for (Chunk chunk : diff.getChunks()) {
y += 10;
for (CodeLine line : chunk.getLines()) {
y += metrics.getHeight() + 2;
g.drawString(line.getLine(), 5, y);
}
}
Dimension d = new Dimension(prefWidth, prefHeight);
super.setSize(d);
super.setPreferredSize(d);
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
} |
package com.google.sps.data;
import java.util.Date;
/** Class that creates constants for tables. **/
public final class EntityConstants {
/** Class that creates entity constants for the Attendee table. **/
final static class AttendeeEntity {
public final static String TABLE_NAME = "Attendee";
public final static String SESSION_ID = "SessionId";
public final static String SCREEN_NAME = "ScreenName";
public final static String TIME_LAST_POLLED = "TimeLastPolled";
}
/** Class that creates entity constants for the Instance table. **/
final static class InstanceEntity {
public final static String TABLE_NAME = "Instance";
public final static String INSTANCE_NAME = "InstanceName";
public final static String SESSION_ID = "SessionId";
}
/** Class that creates entity constants for the Session table. **/
final static class SessionEntity {
public final static String TABLE_NAME = "Session";
public final static String SESSION_ID = "SessionId";
public final static String SCREEN_NAME_OF_CONTROLLER = "ScreenNameOfController";
public final static String IP_OF_VM = "IpOfVM";
}
} |
package com.lenis0012.bukkit.npc;
import net.minecraft.server.v1_7_R3.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_7_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_7_R3.entity.CraftEntity;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.Plugin;
import java.util.List;
import java.util.ArrayList;
/**
* NPCFactory main class, intializes and creates npcs.
*
* @author lenis0012
*/
public class NPCFactory implements Listener {
private final Plugin plugin;
private final NPCNetworkManager networkManager;
public NPCFactory(Plugin plugin) {
this.plugin = plugin;
this.networkManager = new NPCNetworkManager();
Bukkit.getPluginManager().registerEvents(this, plugin);
}
/**
* Spawn a new npc at a speciafied location.
*
* @param location Location to spawn npc at.
* @param profile NPCProfile to use for npc
* @return New npc instance.
*/
public NPC spawnHumanNPC(Location location, NPCProfile profile) {
World world = location.getWorld();
WorldServer worldServer = ((CraftWorld) world).getHandle();
NPCEntity entity = new NPCEntity(world, profile, networkManager);
entity.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
worldServer.addEntity(entity);
worldServer.players.remove(entity);
entity.getBukkitEntity().setMetadata("NPC", new FixedMetadataValue(plugin, true));
return entity.getNPC();
}
/**
* Get npc from entity.
*
* @param entity Entity to get npc from.
* @return NPC instance, null if entity is not an npc.
*/
public NPC getNPC(Entity entity) {
if(!isNPC(entity)) {
return null;
}
NPCEntity npcEntity = (NPCEntity) ((CraftEntity) entity).getHandle();
return npcEntity.getNPC();
}
public List<NPC> getNPCs() {
List<NPC> npcList = new ArrayList<NPC>();
for (World world : Bukkit.getWorlds()) {
npcList.addAll(getNPCs(world));
}
return npcList;
}
public List<NPC> getNPCs(World world) {
List<NPC> npcList = new ArrayList<NPC>();
for (Entity entity : world.getEntities()) {
if (isNPC(entity)) npcList.add(this.getNPC(entity));
}
return npcList;
}
/**
* Check if an entity is a NPC.
*
* @param entity Entity to check.
* @return Entity is a npc?
*/
public boolean isNPC(Entity entity) {
return entity.hasMetadata("NPC");
}
/**
* Despawn all npc's on all worlds.
*/
public void despawnAll() {
for(World world : Bukkit.getWorlds()) {
despawnAll(world);
}
}
/**
* Despawn all npc's on a single world.
*
* @param world World to despawn npc's on.
*/
public void despawnAll(World world) {
for(Entity entity : world.getEntities()) {
if(entity.hasMetadata("NPC")) {
entity.remove();
}
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if(event.getPlugin().equals(plugin)) {
despawnAll();
}
}
} |
package com.montealegreluis.yelpv3;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Business {
private final String id;
private final String name;
private final String phone;
private final String url;
private final String image;
private final double distanceInMeters;
private final double rating;
private final int reviewCount;
private final boolean claimed;
private final PricingLevel pricingLevel;
private final Location location;
private final Coordinates coordinates;
private final List<String> photos = new ArrayList<>();
private final List<String> transactions = new ArrayList<>();
private List<Category> categories = new ArrayList<>();
private boolean closedPermanently;
private Schedule schedule;
public static Business from(JSONObject information) {
try {
return new Business(information);
} catch (JSONException e) {
throw new RuntimeException(
String.format("Cannot parse object%s", information.toString(2)),
e
);
}
}
public String id() {
return id;
}
public String name() {
return name;
}
public String phone() {
return phone;
}
public String url() {
return url;
}
public String image() {
return image;
}
/**
* @return Distance in meters
*/
public double distance() {
return distanceInMeters;
}
public double rating() {
return rating;
}
public int reviewCount() {
return reviewCount;
}
public PricingLevel priceLevel() {
return pricingLevel;
}
public boolean isClaimed() {
return claimed;
}
public boolean isClosedPermanently() {
return closedPermanently;
}
public Location location() {
return location;
}
public Coordinates coordinates() {
return coordinates;
}
public Schedule schedule() {
return schedule;
}
public List<Category> categories() {
return categories;
}
public List<String> transactions() {
return transactions;
}
public List<String> photos() {
return photos;
}
private Business(JSONObject information) {
id = information.getString("id");
name = information.getString("name");
phone = information.getString("phone");
url = information.getString("url");
image = information.getString("image_url");
distanceInMeters = !information.isNull("distance") ? information.getDouble("distance") : 0.0;
rating = information.getDouble("rating");
reviewCount = information.getInt("review_count");
claimed = !information.isNull("is_claimed") && information.getBoolean("is_claimed");
pricingLevel = information.has("price") ? PricingLevel.fromSymbol(information.getString("price")) : null;
closedPermanently = information.getBoolean("is_closed");
location = Location.from(information.getJSONObject("location"));
coordinates = Coordinates.from(information.getJSONObject("coordinates"));
schedule = !information.isNull("hours") ? Schedule.from(information.getJSONArray("hours")) : null;
setCategories(information.getJSONArray("categories"));
addAllTo(information.getJSONArray("transactions"), transactions);
if (!information.isNull("photos")) addAllTo(information.getJSONArray("photos"), photos);
}
private void addAllTo(JSONArray entries, List<String> collection) {
for (int i = 0; i < entries.length(); i++) collection.add(entries.getString(i));
}
private void setCategories(JSONArray businessCategories) {
for (int i = 0; i < businessCategories.length(); i++) {
JSONObject category = businessCategories.getJSONObject(i);
categories.add(
new Category(category.getString("alias"), category.getString("title"))
);
}
}
public boolean isInCategory(String categoryAlias) {
return categories
.stream()
.filter(category -> category.hasAlias(categoryAlias))
.collect(Collectors.toList())
.size() > 0
;
}
} |
package piano;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.MIDIControl;
/**
* Player of MIDI events.
*
* @author Wincent Balin
*/
class MIDIPlayer
{
public static final int CHANNEL = 0;
public static final int VELOCITY = 100;
public static final int MUTE = 100;
private Player player;
private MIDIControl control;
private boolean bankQuerySupported;
private int[] banks;
/**
* Constructor.
*
* @throws IOException
* @throws MediaException
* @throws ClassNotFoundException
*/
MIDIPlayer() throws IOException, MediaException, ClassNotFoundException
{
// Create MIDI player
player = Manager.createPlayer(Manager.MIDI_DEVICE_LOCATOR);
player.prefetch();
// Create MIDI control
control = (MIDIControl) player.getControl("javax.microedition.media.control.MIDIControl");
// Check whether MIDI control was instantiated
if(control == null)
throw new ClassNotFoundException("MIDIControl not available!");
// Check whether it is possible to query banks
bankQuerySupported = control.isBankQuerySupported();
// If it is...
if(bankQuerySupported)
{
// Get all (=false) available banks
banks = control.getBankList(false);
}
}
/**
* Get list of names of all available MIDI programs.
*
* @return List with names
* @throws MediaException
*/
String[] getAllProgramNames() throws MediaException
{
Vector names = new Vector();
String[] result;
// If bank query supported ...
if(bankQuerySupported)
{
// Iterate through banks
final int banksLength = banks.length;
for(int i = 0; i < banksLength; i++)
{
final int bankNumber = banks[i];
int[] programs = control.getProgramList(bankNumber);
// Iterate through programs
final int programsLength = programs.length;
for(int j = 0; j < programsLength; j++)
{
final int programNumber = programs[j];
// Get name of the program
String programName =
control.getProgramName(bankNumber, programNumber);
// Add name of the program to the vector of names
names.addElement(programName);
}
}
}
// Convert vector to array and return it
result = new String[names.size()];
names.copyInto(result);
return result;
}
/**
* Set program on the first channel.
*
* @param index Index in the previously created list of program names
*/
void setProgram(int index)
{
int bank = banks[index / 127];
int program = index % 127;
// Use first channel
control.setProgram(CHANNEL, bank, program);
}
/**
* Convert octave/note combination to MIDI note number.
*
* @param octave Octave of the note (first: 0, second: 1, small: -1, etc)
* @param note Pitch of the note (C: 0, C#: 1, D: 2, etc)
* @return MIDI note number
*/
private int calculateMIDINote(int octave, int note)
{
return 60 + octave * 12 + note;
}
/**
* Play the given note.
*
* @param octave Octave of the note (first: 0, second: 1, small: -1, etc)
* @param note Pitch of the note (C: 0, C#: 1, D: 2, etc)
*/
void noteOn(int octave, int note)
{
int midiNote = calculateMIDINote(octave, note);
control.shortMidiEvent(control.NOTE_ON | CHANNEL, midiNote, VELOCITY);
}
/**
* Stop playing the given note.
*
* @param octave Octave of the note (first: 0, second: 1, small: -1, etc)
* @param note Pitch of the note (C: 0, C#: 1, D: 2, etc)
*/
void noteOff(int octave, int note)
{
int midiNote = calculateMIDINote(octave, note);
control.shortMidiEvent(control.NOTE_ON | CHANNEL, midiNote, MUTE);
}
} |
package com.pump.text.html.view;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.util.List;
import java.util.Objects;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.View;
import javax.swing.text.html.CSS;
import javax.swing.text.html.StyleSheet;
import javax.swing.text.html.StyleSheet.BoxPainter;
import com.pump.geom.ShapeBounds;
import com.pump.graphics.Graphics2DContext;
import com.pump.graphics.vector.GlyphVectorOperation;
import com.pump.graphics.vector.Operation;
import com.pump.graphics.vector.StringOperation;
import com.pump.graphics.vector.VectorGraphics2D;
import com.pump.graphics.vector.VectorImage;
import com.pump.image.shadow.ShadowAttributes;
import com.pump.text.html.css.CssColorParser;
import com.pump.text.html.css.CssLength;
import com.pump.text.html.css.CssOverflowParser;
import com.pump.text.html.css.CssOverflowValue;
import com.pump.text.html.css.CssTextShadowParser;
import com.pump.text.html.css.background.CssBackgroundClipValue;
import com.pump.text.html.css.image.CssImageParser;
import com.pump.text.html.css.image.CssImageValue;
import com.pump.util.list.AddElementsEvent;
import com.pump.util.list.ListAdapter;
import com.pump.util.list.ObservableList;
/**
* This helper class may be used by multiple View subclasses to help manage HTML
* enhancements.
* <p>
* Some properties (like background images) this object renders directly. Some
* properties (like text shadows) this object embeds as RenderingHints for the
* QHtmlBlockView to address later.
*/
public class QViewHelper {
/**
*
* @param g
* @param allocation
* @param boxPainter
* this should be non-null if this object is responsible for
* painting the background/border (and stripping out the legacy
* background/border)
* @param isBody
* if true then this is an attempt to paint the <body> tag.
* In this case we apply special clipping regardless of the
* "overflow" attribute.
*/
public static void paint(Graphics2D g, Shape allocation, View view,
LegacyCssView legacyView, StyleSheet styleSheet,
BoxPainter boxPainter, boolean isBody) {
QViewHelper helper = new QViewHelper(view, styleSheet, legacyView);
Rectangle r = ShapeBounds.getBounds(allocation).getBounds();
Graphics2D g2 = helper.createGraphics(g, allocation, isBody);
if (boxPainter != null) {
helper.paintBackground(g2, r);
g2 = helper.createGraphicsWithoutBoxPainter(g2, r, boxPainter);
}
legacyView.paintLegacyCss2(g2, allocation);
g2.dispose();
}
/**
* This RenderingHint.Key resolves to a List of ShadowAttributes (or null)
*/
public static final RenderingHints.Key HINT_KEY_TEXT_SHADOW = new RenderingHints.Key(
592393) {
@Override
public boolean isCompatibleValue(Object val) {
if (val == null)
return true;
if (!(val instanceof java.util.List))
return false;
for (Object e : ((List) val)) {
if (!(e instanceof ShadowAttributes))
return false;
}
return true;
}
@Override
public String toString() {
return CssTextShadowParser.PROPERTY_TEXT_SHADOW;
}
};
/**
* This RenderingHint.Key resolves to the javax.swing.text.Element currently
* being rendered (or null).
*/
public static final RenderingHints.Key HINT_KEY_ELEMENT = new RenderingHints.Key(
592394) {
@Override
public boolean isCompatibleValue(Object val) {
if (val == null)
return true;
return val instanceof Element;
}
@Override
public String toString() {
return "element";
}
};
/**
* This rendering hint should map to a Shape that is applied as a "soft
* clipping" for all incoming rendering operations. This lets you achieve an
* antialiased clipping. This is applied independently of the Graphics2D's
* clipping. (So the soft clipping alters what we paint to the underlying
* Graphics2D, and the underlying Graphics2D's clipping still applies.)
*/
public static final RenderingHints.Key HINT_KEY_SOFT_CLIP = new RenderingHints.Key(
-930183) {
@Override
public boolean isCompatibleValue(Object val) {
return val == null || val instanceof Shape;
}
};
private static class DropOperationsAndPassThrough
extends ListAdapter<Operation> {
Graphics2D delegate;
List<Operation> operationsToIgnore;
public DropOperationsAndPassThrough(Graphics2D delegate,
List<Operation> operationsToIgnore) {
this.delegate = delegate;
this.operationsToIgnore = operationsToIgnore;
}
@Override
public void elementsAdded(AddElementsEvent<Operation> event) {
for (Operation op : event.getNewElements()) {
if (operationsToIgnore.isEmpty()) {
op.paint(delegate);
} else {
// TODO: we should be able to call .remove(op), but the
// Operation#equal method is failing
operationsToIgnore.remove(0);
}
}
}
}
public static java.lang.Float getPredefinedSize(View view, int axis) {
// TODO: percents require incorporating parent size
// TODO: consider other unit sizes
if (axis == View.X_AXIS) {
Object z = (Object) view.getAttributes()
.getAttribute(CSS.Attribute.WIDTH);
if (z != null) {
CssLength l = new CssLength(z.toString());
return l.getValue();
}
return null;
} else if (axis == View.Y_AXIS) {
Object z = (Object) view.getAttributes()
.getAttribute(CSS.Attribute.HEIGHT);
if (z != null) {
CssLength l = new CssLength(z.toString());
return l.getValue();
}
return null;
}
throw new IllegalArgumentException("unrecognized axis: " + axis);
}
protected final View view;
protected final LegacyCssView legacyView;
protected final StyleSheet styleSheet;
private QViewHelper(View view, StyleSheet styleSheet,
LegacyCssView legacyView) {
Objects.requireNonNull(view);
Objects.requireNonNull(legacyView);
Objects.requireNonNull(styleSheet);
this.view = view;
this.styleSheet = styleSheet;
this.legacyView = legacyView;
}
/**
* Return an attribute associated.
*/
public Object getAttribute(Object attrKey) {
// get value from tag declaration
Object value = view.getElement().getAttributes().getAttribute(attrKey);
if (value == null) {
// get value from css rule
AttributeSet attrs = view.getAttributes();
value = attrs == null ? null : attrs.getAttribute(attrKey);
}
if (attrKey == CSS.Attribute.BACKGROUND_IMAGE && value != null) {
String str = value.toString();
return new CssImageParser().parse(str);
} else if (attrKey == CSS.Attribute.BACKGROUND_COLOR && value != null) {
String str = value.toString();
return new CssColorParser(CSS.Attribute.BACKGROUND_COLOR)
.parse(str);
}
return value;
}
/**
* Return a Graphics2D to paint a View to that embeds special RenderingHints
* and may set the clipping.
*
* @param isBody
* if true then this is an attempt to paint the <body> tag.
* In this case we apply special clipping regardless of the
* "overflow" attribute.
*/
private Graphics2D createGraphics(Graphics2D g, Shape allocation,
boolean isBody) {
Graphics2D returnValue = (Graphics2D) g.create();
returnValue.setRenderingHint(HINT_KEY_ELEMENT, view.getElement());
Object shadowValue = getAttribute(
CssTextShadowParser.PROPERTY_TEXT_SHADOW);
if (shadowValue != null)
returnValue.setRenderingHint(HINT_KEY_TEXT_SHADOW, shadowValue);
CssOverflowValue overflow = (CssOverflowValue) getAttribute(
CssOverflowParser.PROPERTY_OVERFLOW);
boolean requestedClipping = overflow != null
&& overflow.getMode() == CssOverflowValue.Mode.HIDDEN;
boolean requestedScrollbar = overflow != null
&& overflow.getMode() == CssOverflowValue.Mode.SCROLL;
boolean requestedAuto = overflow != null
&& overflow.getMode() == CssOverflowValue.Mode.AUTO;
// we don't support internal scrollpanes (yet), but if you wanted
// a scrollpane it's probably safe to say you didn't want text to
// spill out of view into other views, so we'll clip it.
if (isBody || requestedClipping || requestedScrollbar
|| requestedAuto) {
returnValue.clip(allocation);
}
CssBackgroundClipValue clipValue = (CssBackgroundClipValue) getAttribute(
CssBackgroundClipValue.PROPERTY_BACKGROUND_CLIP);
if (clipValue != null) {
CssBackgroundClipValue.Mode m = clipValue.getMode();
if (m == CssBackgroundClipValue.Mode.TEXT) {
Rectangle r = ShapeBounds.getBounds(allocation).getBounds();
Shape textShape = getTextShape(r);
returnValue.setRenderingHint(HINT_KEY_SOFT_CLIP, textShape);
}
}
return returnValue;
}
/**
* Create a Graphics2D that will skip instructions that come from the
* BoxPainter. This is a weird/hacky response to not being able to disable
* or replace the BoxPainter. (In Swing's default View implementations: the
* BoxPainter is non-null and paints immediately before anything else.)
*
* @param g
* the Graphics2D we want to eventually paint (certain)
* operations on.
* @param r
* the rectangle the BoxPainter will be asked to paint
* @param boxPainter
* the BoxPainter we want to ignore
* @return a new Graphics2D that skips certain rendering operations
*/
private Graphics2D createGraphicsWithoutBoxPainter(Graphics2D g,
Rectangle r, BoxPainter boxPainter) {
VectorImage boxPainterRendering = new VectorImage();
VectorGraphics2D boxPainterG = boxPainterRendering.createGraphics(r);
boxPainter.paint(boxPainterG, r.x, r.y, r.width, r.height, view);
ObservableList<Operation> operations = new ObservableList<>();
operations.addListListener(new DropOperationsAndPassThrough(g,
boxPainterRendering.getOperations()), false);
return new VectorGraphics2D(new Graphics2DContext(g), operations);
}
private void paintBackground(Graphics2D g, Rectangle r) {
Color bgColor = styleSheet
.getBackground(styleSheet.getViewAttributes(view));
CssBackgroundClipValue clipValue = (CssBackgroundClipValue) getAttribute(
CssBackgroundClipValue.PROPERTY_BACKGROUND_CLIP);
Graphics2D g2 = (Graphics2D) g.create();
if (clipValue != null) {
CssBackgroundClipValue.Mode m = clipValue.getMode();
if (m == CssBackgroundClipValue.Mode.BORDER_BOX) {
// do nothing, this is the the biggest/normal option
} else if (m == CssBackgroundClipValue.Mode.PADDING_BOX) {
Insets i = getBorderInsets(r.width, r.height);
Rectangle clipRect = new Rectangle(r.x + i.left, r.y + i.top,
r.width - i.left - i.right,
r.height - i.top - i.bottom);
g2.clipRect(clipRect.x, clipRect.y, clipRect.width,
clipRect.height);
} else if (m == CssBackgroundClipValue.Mode.CONTENT_BOX) {
Insets i1 = getBorderInsets(r.width, r.height);
Insets i2 = getPaddingInsets(r.width, r.height);
Rectangle clipRect = new Rectangle(r.x + i1.left + i2.left,
r.y + i1.top + i2.top,
r.width - i1.left - i1.right - i2.left - i2.right,
r.height - i1.top - i1.bottom - i2.top - i2.bottom);
g2.clipRect(clipRect.x, clipRect.y, clipRect.width,
clipRect.height);
} else if (m == CssBackgroundClipValue.Mode.TEXT) {
// do nothing, the SoftClipGraphics2D.KEY_SOFT_CLIP should
// already be set up in createGraphics(..)
}
}
if (bgColor != null) {
g2.setColor(bgColor);
g2.fillRect(r.x, r.y, r.width, r.height);
}
List<CssImageValue> bkgndImgs = (List<CssImageValue>) getAttribute(
CSS.Attribute.BACKGROUND_IMAGE);
if (bkgndImgs != null) {
for (int a = bkgndImgs.size() - 1; a >= 0; a
Graphics2D g3 = (Graphics2D) g2.create();
bkgndImgs.get(a).paintRectangle(g3, this, a, r.x, r.y, r.width,
r.height);
g3.dispose();
}
}
g2.dispose();
}
/**
* Return a Shape outline of all the text. This is used to isolate when the
* "background-clip" property is "text".
*/
private Shape getTextShape(Rectangle r) {
VectorImage vi = new VectorImage();
Graphics2D g = vi.createGraphics(r);
legacyView.paintLegacyCss2(g, r);
g.dispose();
Path2D returnValue = new Path2D.Float();
for (Operation op : vi.getOperations()) {
if (op instanceof StringOperation) {
StringOperation so = (StringOperation) op;
Shape outline = so.getShape();
returnValue.append(outline, false);
} else if (op instanceof GlyphVectorOperation) {
GlyphVectorOperation gvo = (GlyphVectorOperation) op;
returnValue.append(gvo.getOutline(), false);
}
}
return returnValue;
}
private Insets getPaddingInsets(int width, int height) {
int top = getLength(CSS.Attribute.PADDING_TOP, height);
int left = getLength(CSS.Attribute.PADDING_LEFT, width);
int bottom = getLength(CSS.Attribute.PADDING_BOTTOM, height);
int right = getLength(CSS.Attribute.PADDING_RIGHT, width);
return new Insets(top, left, bottom, right);
}
private int getLength(Object attributeKey, int range) {
Object attr = view.getAttributes().getAttribute(attributeKey);
if (attr == null)
return 0;
CssLength l = new CssLength(attr.toString().toString());
if (l.getUnit().equals("%")) {
return (int) (l.getValue() * range / 100);
} else if (l.getUnit().equals("px")) {
return (int) (l.getValue() + .5f);
}
throw new IllegalArgumentException(
"Unsupported unit in \"" + attr.toString() + "\"");
}
private Insets getBorderInsets(int width, int height) {
int top = getLength(CSS.Attribute.BORDER_TOP_WIDTH, height);
int left = getLength(CSS.Attribute.BORDER_LEFT_WIDTH, width);
int bottom = getLength(CSS.Attribute.BORDER_BOTTOM_WIDTH, height);
int right = getLength(CSS.Attribute.BORDER_RIGHT_WIDTH, width);
return new Insets(top, left, bottom, right);
}
/**
* Return the View associated with this QViewHelper.
*/
public View getView() {
return view;
}
} |
package com.rultor.agents.github;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Tv;
import com.jcabi.github.Repo;
import com.jcabi.github.RepoCommit;
import com.jcabi.github.Smarts;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.Locale;
import java.util.TimeZone;
import javax.json.JsonObject;
/**
* Log of commits.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.51
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
@Immutable
final class CommitsLog {
/**
* Repo.
*/
private final transient Repo repo;
/**
* Ctor.
* @param rpo Repo
*/
CommitsLog(final Repo rpo) {
this.repo = rpo;
}
/**
* Release body text.
* @param prev Previous release date.
* @param current Current release date.
* @return Release body text.
* @throws IOException In case of problem communicating with git.
*/
public String build(final Date prev, final Date current)
throws IOException {
final DateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm'Z'", Locale.ENGLISH
);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
final Collection<String> lines = new LinkedList<>();
final ImmutableMap<String, String> params =
new ImmutableMap.Builder<String, String>()
.put("since", format.format(prev))
.put("until", format.format(current))
.build();
final Iterable<RepoCommit.Smart> commits = new Smarts<>(
this.repo.commits().iterate(params)
);
int count = 0;
final StringBuilder line = new StringBuilder(0);
for (final RepoCommit.Smart commit : commits) {
if (count > Tv.TWENTY) {
lines.add(" * and more...");
break;
}
final JsonObject json = commit.json();
line.setLength(0);
line.append(" * ").append(commit.sha());
line.append(" by @").append(
json.getJsonObject("author").getString("login")
);
if (!json.getJsonObject("commit").isNull("message")) {
line.append(": ").append(
commit.message()
.replaceAll("[\\p{Cntrl}\\p{Space}]+", " ")
.replaceAll("(?<=^.{30}).+$", "...")
);
}
lines.add(line.toString());
++count;
}
return Joiner.on('\n').join(lines);
}
} |
package com.tallcraft.chatreplay;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ChatBuffer {
private ConcurrentLinkedQueue<ChatMessage> queue;
private int queueSize; //We store it ourselves for efficiency
private int bufferSize; //How many messages to store + replay
private String replayHeader;
private String replayFooter;
private String replayMsgFormat;
private String replayMsgHover;
public ChatBuffer(int bufferSize, String replayHeader, String replayFooter, String replayMsgFormat, String replayMsgHover) {
setReplayHeader(replayHeader);
setReplayFooter(replayFooter);
setReplayMsgFormat(replayMsgFormat);
setReplayMsgHover(replayMsgHover);
this.bufferSize = bufferSize;
queue = new ConcurrentLinkedQueue<ChatMessage>();
queueSize = 0;
}
public void addMessage(ChatMessage message) {
if (message != null) {
while (queueSize > bufferSize) {
queue.remove();
queueSize
}
queue.add(message);
queueSize++;
}
}
private ConcurrentLinkedQueue<ChatMessage> getQueue() {
return this.queue;
}
public void playTo(Player player) {
if (queueSize > 0) { //Only replay if there is data
int displaySize = bufferSize;
if (queueSize < bufferSize) {
displaySize = queueSize;
}
TextComponent header = new TextComponent(
TextComponent.fromLegacyText(
replayHeader.replace("{{msgCount}}", Integer.toString(displaySize)))
);
TextComponent footer = new TextComponent(
TextComponent.fromLegacyText(
replayFooter.replace("{{msgCount}}", Integer.toString(displaySize)))
);
TextComponent formattedMessage;
String replacedMsgFormat;
String replacedMsgHover;
player.sendMessage(header.toLegacyText());
for (ChatMessage msg : queue) {
replacedMsgFormat = new String(replayMsgFormat);
replacedMsgHover = new String(replayMsgHover);
try {
replacedMsgFormat = replaceVariables(new String[]{msg.getPlayerName(), msg.getMessage(),
msg.getTimestamp().toString()}, replacedMsgFormat);
replacedMsgHover = replaceVariables(new String[]{msg.getPlayerName(), msg.getMessage(),
msg.getTimestamp().toString()}, replacedMsgHover);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
formattedMessage = new TextComponent(TextComponent.fromLegacyText(replacedMsgFormat));
formattedMessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
new ComponentBuilder(replacedMsgHover).create()));
player.sendMessage(formattedMessage.toLegacyText());
}
player.sendMessage(footer.toLegacyText());
}
}
private String replaceVariables(String[] values, String str) throws IllegalArgumentException {
return replaceVariables(new String[]{"{{player}}", "{{message}}", "{{timestamp}}"}, values, str);
}
private String replaceVariables(String[] variables, String[] values, String str) throws IllegalArgumentException {
if (variables.length != values.length) {
throw new IllegalArgumentException("Arguments variables and values have to match in array-length");
}
for (int i = 0; i < variables.length; i++) {
str = str.replace(variables[i], values[i]);
}
return str;
}
public int getBufferSize() {
return bufferSize;
}
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public String getReplayHeader() {
return replayHeader;
}
public void setReplayHeader(String replayHeader) {
this.replayHeader = ChatColor.translateAlternateColorCodes('&', replayHeader);
}
public String getReplayFooter() {
return replayFooter;
}
public void setReplayFooter(String replayFooter) {
this.replayFooter = ChatColor.translateAlternateColorCodes('&', replayFooter);
}
public String getReplayMsgFormat() {
return replayMsgFormat;
}
public void setReplayMsgFormat(String replayMsgFormat) {
this.replayMsgFormat = ChatColor.translateAlternateColorCodes('&', replayMsgFormat);
}
public String getReplayMsgHover() {
return replayMsgHover;
}
public void setReplayMsgHover(String replayMsgHover) {
this.replayMsgHover = ChatColor.translateAlternateColorCodes('&', replayMsgHover);
}
} |
package com.tectonica.gae;
import java.util.HashMap;
import java.util.Map;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
/**
* Servlet-listener for intercepting REST requests and pass them through Guice before Jersey. To use it you need to extend this class and
* generate a constructor that would offer your own subclass of {@link GuiceRestModule}, reflect your configuration. At the minimum, this
* subclass needs to implement {@link GuiceRestModule#getRootPackage()} or {@link GuiceRestModule#bindJaxrsResources()}. For example:
*
* <pre>
* public class RestConfig extends GuiceRestListener
* {
* public RestConfig()
* {
* super(new GuiceRestModule()
* {
* {@literal @}Override
* protected String getServingUrl()
* {
* return ...;
* }
*
* {@literal @}Override
* protected String getRootPackage()
* {
* return ...;
* }
* });
* }
* }
* </pre>
*
* Once implemented, register your listener with {@code web.xml}:
*
* <pre>
* <listener>
* <listener-class>com.example.api.RestConfig</listener-class>
* </listener>
* </pre>
*
* @author Zach Melamed
*/
public class GuiceRestListener extends GuiceServletContextListener
{
protected final GuiceRestModule module;
protected static Injector injector;
protected GuiceRestListener(GuiceRestModule customModule)
{
module = customModule;
}
@Override
protected Injector getInjector()
{
injector = Guice.createInjector(module);
return injector;
}
/**
* given a class, generates an injected instance. Useful when an API call is needed internally.
*/
public static <T> T getInstance(Class<T> type)
{
return injector.getInstance(type);
}
/**
* given an injectable instance, injects its dependencies
*/
public static void injectMembers(Object instance)
{
injector.injectMembers(instance);
}
public static class GuiceRestModule extends ServletModule
{
@Override
protected void configureServlets()
{
doCustomBinds();
bindJaxrsResources();
// add support for the @PostConstruct annotation for Guice-injected objects
// if you choose to remove it, also modify GuiceJsfInjector.invokePostConstruct()
bindListener(Matchers.any(), new PostConstructTypeListener(null));
// configure Jersey: use Jackson + CORS-filter
Map<String, String> initParams = new HashMap<>();
if (isUseJackson())
initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
String reponseFilters = getResponseFilters();
if (reponseFilters != null)
initParams.put("com.sun.jersey.spi.container.ContainerResponseFilters", reponseFilters);
doCustomJerseyParameters(initParams);
// route all requests through Guice
serve(getServingUrl()).with(GuiceContainer.class, initParams);
doCustomServing();
}
/**
* override this to specify the URL-pattern of the REST service
*/
protected String getServingUrl()
{
/**
* override this to specify a root-package under which all your JAX-RS annotated class are located
*/
protected String getRootPackage()
{
return null;
}
/**
* bind JAX-RS annotated classes to be served through Guice. based on a recursive class scanning that starts from the package
* returned by {@link #getRootPackage()}. override this if you wish to avoid the scanning and bind your classes explicitly
*/
protected void bindJaxrsResources()
{
String rootPackage = getRootPackage();
if (rootPackage == null)
throw new NullPointerException(
"to scan for JAX-RS annotated classes, either override getRootPackage() or bindJaxrsResources()");
ResourceConfig rc = new PackagesResourceConfig(rootPackage);
for (Class<?> resource : rc.getClasses())
bind(resource);
}
/**
* override this to return a (comma-delimited) list of Jersey's ContainerResponseFilters. By default returns the {@link CorsFilter}.
*/
protected String getResponseFilters()
{
return CorsFilter.class.getName();
}
/**
* override this to avoid usage of Jackson
*/
protected boolean isUseJackson()
{
return true;
}
/**
* override to perform application-logic bindings, typically between interfaces and concrete implementations. For example:
*
* <pre>
* bind(MyIntf.class).to(MyImpl.class);
* </per>
*/
protected void doCustomBinds()
{}
* serve("/my/*").with(MyServlet.class);
* </pre>
*/
protected void doCustomServing()
{}
/**
* override to change the context-parameters passed to Jersey's servlet. For example:
*
* <pre>
* initParams.put("com.sun.jersey.config.feature.Trace", "true");
* </Per>
*/
protected void doCustomJerseyParameters(Map<String, String> initParams)
{}
}
} |
package com.toomasr.sgf4j.board;
import javafx.geometry.Pos;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class BoardSquare extends StackPane {
private static final Image blackStoneImage = new Image(BoardSquare.class.getResourceAsStream("/black-stone.svg"));
private static final Image blackStoneHighlightedImage = new Image(BoardSquare.class.getResourceAsStream("/black-stone-highlighted.svg"));
private static final Image whiteStoneImage = new Image(BoardSquare.class.getResourceAsStream("/white-stone.svg"));;
private static final Image whiteStoneHighlightedImage = new Image(BoardSquare.class.getResourceAsStream("/white-stone-highlighted.svg"));
public static int width = 29;
private static final double FONT_MULTIPLIER = 1.8125;
private final int x;
private final int y;
private StoneState squareState = StoneState.EMPTY;
private Text text;
private Line lineH;
private Line lineV;
private Circle starPoint;
private ImageView stoneImage;
public BoardSquare(int x, int y) {
super();
this.x = x;
this.y = y;
setStyle("-fx-background-color: #ffffff");
addTheBgIntersection();
}
private void addTheBgIntersection() {
if (lineH != null) {
getChildren().remove(lineH);
}
lineH = new Line(0, width / 2, width, width / 2);
if (x == 1) {
// the + 1 is to compensate for the stroke width overflow
lineH = new Line(width / 2 + 1, width / 2, width, width / 2);
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER_RIGHT);
} else if (x == 19) {
lineH = new Line(width / 2, width / 2, width - 1, width / 2);
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER_LEFT);
} else {
getChildren().add(lineH);
setAlignment(lineH, Pos.CENTER);
}
if (lineV != null) {
getChildren().remove(lineV);
}
lineV = new Line(width / 2, 0, width / 2, width);
if (y == 1) {
// the -1 is compensate for the stroke width overflow
lineV = new Line(width / 2, width / 2 - 1, width / 2, 0);
getChildren().add(lineV);
setAlignment(lineV, Pos.BOTTOM_CENTER);
} else if (y == 19) {
lineV = new Line(width / 2, width / 2, width / 2, width - 1);
getChildren().add(lineV);
setAlignment(lineV, Pos.TOP_CENTER);
} else {
getChildren().add(lineV);
setAlignment(lineV, Pos.CENTER);
}
if (starPoint != null) {
getChildren().remove(starPoint);
}
if ((x == 4 && y == 4) || (x == 16 && y == 4) || (x == 4 && y == 16) || (x == 16 && y == 16) || (x == 10 && y == 4)
|| (x == 10 && y == 16) || (x == 4 && y == 10) || (x == 16 && y == 10) || (x == 10 && y == 10)) {
starPoint = new Circle(3, 3, 3);
starPoint.setStroke(Color.BLACK);
getChildren().add(starPoint);
}
}
public void removeStone() {
squareState = StoneState.EMPTY;
getChildren().remove(stoneImage);
}
public void addOverlayText(String str) {
// there are SGF files that place multiple labels
// on a single square - right now won't support that
// and always showing the latest one
removeOverlayText();
text = new Text(str);
Font font = Font.font(Font.getDefault().getName(), FontWeight.MEDIUM, width / FONT_MULTIPLIER);
text.setFont(font);
text.setStroke(Color.SADDLEBROWN);
text.setFill(Color.SADDLEBROWN);
setAlignment(text, Pos.CENTER);
getChildren().add(text);
lineH.setVisible(false);
lineV.setVisible(false);
if (starPoint != null) {
starPoint.setVisible(false);
}
}
public void removeOverlayText() {
if (getChildren().contains(text)) {
getChildren().remove(text);
}
lineH.setVisible(true);
lineV.setVisible(true);
if (starPoint != null) {
starPoint.setVisible(true);
}
}
public void placeStone(StoneState stoneState) {
this.squareState = stoneState;
getChildren().remove(stoneImage);
stoneImage = getImageView(blackStoneImage);
if (stoneState.equals(StoneState.WHITE)) {
stoneImage = getImageView(whiteStoneImage);
}
getChildren().add(stoneImage);
}
private ImageView getImageView(Image stoneImage) {
ImageView rtrn = new ImageView(stoneImage);
rtrn.setFitWidth(width);
rtrn.setFitHeight(width);
return rtrn;
}
public void highLightStone() {
getChildren().remove(stoneImage);
stoneImage = getImageView(blackStoneHighlightedImage);
if (squareState.equals(StoneState.WHITE)) {
stoneImage = getImageView(whiteStoneHighlightedImage);
}
getChildren().add(stoneImage);
}
public void deHighLightStone() {
getChildren().remove(stoneImage);
stoneImage = getImageView(blackStoneImage);
if (squareState.equals(StoneState.WHITE)) {
stoneImage = getImageView(whiteStoneImage);
}
getChildren().add(stoneImage);
}
public int getSize() {
return width;
}
public void resizeTo(int newSize) {
BoardSquare.width = newSize;
addTheBgIntersection();
if (getChildren().contains(stoneImage)) {
getChildren().remove(stoneImage);
stoneImage = getImageView(stoneImage.getImage());
getChildren().add(stoneImage);
}
if (getChildren().contains(text)) {
String str = text.getText();
removeOverlayText();
addOverlayText(str);
}
}
public void reset() {
squareState = StoneState.EMPTY;
getChildren().clear();
addTheBgIntersection();
}
@Override
public String toString() {
return "BoardStone [x=" + x + ", y=" + y + ", squareState=" + squareState + "]";
}
} |
package com.typesafe.netty;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.TypeParameterMatcher;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import static com.typesafe.netty.HandlerPublisher.State.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Publisher for a Netty Handler.
*
* This publisher supports only one subscriber.
*
* All interactions with the subscriber are done from the handlers executor, hence, they provide the same happens before
* semantics that Netty provides.
*
* The handler publishes all messages that match the type as specified by the passed in class. Any non matching messages
* are forwarded to the next handler.
*
* The publisher will signal complete if it receives a channel inactive event.
*
* The publisher will release any messages that it drops (for example, messages that are buffered when the subscriber
* cancels), but other than that, it does not release any messages. It is up to the subscriber to release messages.
*
* If the subscriber cancels, the publisher will send a disconnect event up the channel pipeline.
*
* All errors will short circuit the buffer, and cause publisher to immediately call the subscribers onError method,
* dropping the buffer.
*
* The publisher can be subscribed to or placed in a handler chain in any order.
*/
public class HandlerPublisher<T> extends ChannelDuplexHandler implements Publisher<T> {
private final TypeParameterMatcher matcher;
/**
* Create a handler publisher.
*
* @param subscriberMessageType The type of message this publisher accepts.
*/
public HandlerPublisher(Class<? extends T> subscriberMessageType) {
this.matcher = TypeParameterMatcher.get(subscriberMessageType);
}
/**
* Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
*/
protected boolean acceptInboundMessage(Object msg) throws Exception {
return matcher.match(msg);
}
enum State {
/**
* Initial state. There's no subscriber, and no context.
*/
NO_SUBSCRIBER_OR_CONTEXT,
/**
* A subscriber has been provided, but no context has been provided.
*/
NO_CONTEXT,
/**
* A context has been provided, but no subscriber has been provided.
*/
NO_SUBSCRIBER,
/**
* An error has been received, but there's no subscriber to receive it.
*/
NO_SUBSCRIBER_ERROR,
/**
* There is no demand, and we have nothing buffered.
*/
IDLE,
/**
* There is no demand, and we're buffering elements.
*/
BUFFERING,
/**
* We have nothing buffered, but there is demand.
*/
DEMANDING,
/**
* The stream is complete, however there are still elements buffered for which no demand has come from the subscriber.
*/
DRAINING,
/**
* We're done, in the terminal state.
*/
DONE
}
private final Queue<Object> buffer = new LinkedList<>();
/**
* Whether a subscriber has been provided. This is used to detect whether two subscribers are subscribing
* simultaneously.
*/
private final AtomicBoolean hasSubscriber = new AtomicBoolean();
/**
* This is used before a context is provided - once a context is provided, it's not needed, since every event is
* submitted to the contexts executor to be run on the handlers thread.
*
* It only has five possible states, NO_SUBSCRIBER_OR_CONTEXT, NO_SUBSCRIBER, NO_SUBSCRIBER_ERROR, NO_CONTEXT,
* or DONE.
*/
private final AtomicReference<State> subscriberContextState = new AtomicReference<>(State.NO_SUBSCRIBER_OR_CONTEXT);
private State state = NO_SUBSCRIBER_OR_CONTEXT;
private volatile ChannelHandlerContext ctx;
private volatile Subscriber<? super T> subscriber;
private long outstandingDemand = 0;
private Throwable noSubscriberError;
@Override
public void subscribe(final Subscriber<? super T> subscriber) {
if (subscriber == null) {
throw new NullPointerException("Null subscriber");
}
if (!hasSubscriber.compareAndSet(false, true)) {
// Must call onSubscribe first.
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
});
subscriber.onError(new IllegalStateException("This publisher only supports one subscriber"));
} else {
switch(subscriberContextState.get()) {
case NO_SUBSCRIBER_OR_CONTEXT:
this.subscriber = subscriber;
if (subscriberContextState.compareAndSet(NO_SUBSCRIBER_OR_CONTEXT, NO_CONTEXT)) {
// It's set
break;
}
// Otherwise, a context was supplied since initially checking the state, so let it fall through to
// the no subscriber behaviour, which is done on the context executor.
case NO_SUBSCRIBER:
case NO_SUBSCRIBER_ERROR:
ctx.executor().execute(new Runnable() {
@Override
public void run() {
provideSubscriber(subscriber);
}
});
break;
}
}
}
private void provideSubscriber(Subscriber<? super T> subscriber) {
// Subscriber is provided, so set subscriber state to done
subscriberContextState.set(DONE);
this.subscriber = subscriber;
switch (state) {
case NO_SUBSCRIBER:
if (buffer.isEmpty()) {
state = IDLE;
} else {
state = BUFFERING;
}
subscriber.onSubscribe(new ChannelSubscription());
break;
case DRAINING:
subscriber.onSubscribe(new ChannelSubscription());
break;
case NO_SUBSCRIBER_ERROR:
cleanup();
state = DONE;
subscriber.onSubscribe(new ChannelSubscription());
subscriber.onError(noSubscriberError);
break;
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
switch(subscriberContextState.get()) {
case NO_SUBSCRIBER_OR_CONTEXT:
this.ctx = ctx;
if (subscriberContextState.compareAndSet(NO_SUBSCRIBER_OR_CONTEXT, NO_SUBSCRIBER)) {
// It's set, we don't have a subscriber
state = NO_SUBSCRIBER;
break;
}
// We now have a subscriber, let it fall through to the NO_CONTEXT behaviour
case NO_CONTEXT:
subscriberContextState.set(DONE);
this.ctx = ctx;
state = IDLE;
subscriber.onSubscribe(new ChannelSubscription());
break;
default:
throw new IllegalStateException("This handler has already been placed in a handler pipeline");
}
}
private void receivedDemand(long demand) {
switch (state) {
case BUFFERING:
case DRAINING:
if (addDemand(demand)) {
flushBuffer();
}
break;
case DEMANDING:
addDemand(demand);
break;
case IDLE:
if (addDemand(demand)) {
ctx.read();
state = DEMANDING;
}
break;
}
}
private boolean addDemand(long demand) {
if (demand <= 0) {
illegalDemand();
return false;
} else {
if (outstandingDemand < Long.MAX_VALUE) {
outstandingDemand += demand;
if (outstandingDemand < 0) {
outstandingDemand = Long.MAX_VALUE;
}
}
return true;
}
}
private void illegalDemand() {
cleanup();
subscriber.onError(new IllegalArgumentException("Request for 0 or negative elements in violation of Section 3.9 of the Reactive Streams specification"));
ctx.disconnect();
state = DONE;
}
private void flushBuffer() {
while (!buffer.isEmpty() && (outstandingDemand > 0 || outstandingDemand == Long.MAX_VALUE)) {
publishMessage(buffer.remove());
}
if (buffer.isEmpty()) {
if (outstandingDemand > 0) {
if (state == BUFFERING) {
state = DEMANDING;
} // otherwise we're draining
ctx.read();
} else if (state == BUFFERING) {
state = IDLE;
}
}
}
private void receivedCancel() {
switch (state) {
case BUFFERING:
case DEMANDING:
case IDLE:
ctx.disconnect();
case DRAINING:
state = DONE;
break;
}
cleanup();
subscriber = null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
if (acceptInboundMessage(message)) {
switch (state) {
case IDLE:
buffer.add(message);
state = BUFFERING;
break;
case NO_SUBSCRIBER:
case BUFFERING:
buffer.add(message);
break;
case DEMANDING:
publishMessage(message);
break;
case DRAINING:
case DONE:
ReferenceCountUtil.release(message);
break;
case NO_CONTEXT:
case NO_SUBSCRIBER_OR_CONTEXT:
throw new IllegalStateException("Message received before added to the channel context");
}
} else {
ctx.fireChannelRead(message);
}
}
private void publishMessage(Object message) {
if (COMPLETE.equals(message)) {
subscriber.onComplete();
state = DONE;
} else {
@SuppressWarnings("unchecked")
T next = (T) message;
subscriber.onNext(next);
if (outstandingDemand < Long.MAX_VALUE) {
outstandingDemand
if (outstandingDemand == 0 && state != DRAINING) {
if (buffer.isEmpty()) {
state = IDLE;
} else {
state = BUFFERING;
}
}
}
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (state == DEMANDING) {
ctx.read();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
switch (state) {
case NO_SUBSCRIBER:
case NO_SUBSCRIBER_ERROR:
case BUFFERING:
buffer.add(COMPLETE);
state = DRAINING;
break;
case DEMANDING:
case IDLE:
subscriber.onComplete();
state = DONE;
break;
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
switch (state) {
case NO_SUBSCRIBER:
noSubscriberError = cause;
state = NO_SUBSCRIBER_ERROR;
cleanup();
break;
case BUFFERING:
case DEMANDING:
case IDLE:
case DRAINING:
state = DONE;
cleanup();
subscriber.onError(cause);
break;
}
}
/**
* Release all elements from the buffer.
*/
private void cleanup() {
while (!buffer.isEmpty()) {
ReferenceCountUtil.release(buffer.remove());
}
}
private class ChannelSubscription implements Subscription {
@Override
public void request(final long demand) {
ctx.executor().execute(new Runnable() {
@Override
public void run() {
receivedDemand(demand);
}
});
}
@Override
public void cancel() {
ctx.executor().execute(new Runnable() {
@Override
public void run() {
receivedCancel();
}
});
}
}
/**
* Used for buffering a completion signal.
*/
private static final Object COMPLETE = new Object();
} |
package com.ubervu.river.github;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonStreamParser;
import org.apache.commons.codec.digest.DigestUtils;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.river.AbstractRiverComponent;
import org.elasticsearch.river.River;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
public class GitHubRiver extends AbstractRiverComponent implements River {
private final Client client;
private final String index;
private final String repository;
private final String owner;
private final String endpoint;
private final int interval;
private String password;
private String username;
private DataStream dataStream;
@SuppressWarnings({"unchecked"})
@Inject
public GitHubRiver(RiverName riverName, RiverSettings settings, Client client) {
super(riverName, settings);
this.client = client;
if (!settings.settings().containsKey("github")) {
throw new IllegalArgumentException("Need river settings - owner and repository.");
}
// get settings
Map<String, Object> githubSettings = (Map<String, Object>) settings.settings().get("github");
owner = XContentMapValues.nodeStringValue(githubSettings.get("owner"), null);
repository = XContentMapValues.nodeStringValue(githubSettings.get("repository"), null);
index = String.format("%s&%s", owner, repository);
interval = XContentMapValues.nodeIntegerValue(githubSettings.get("interval"), 3600);
// auth (optional)
username = null;
password = null;
if (githubSettings.containsKey("authentication")) {
Map<String, Object> auth = (Map<String, Object>) githubSettings.get("authentication");
username = XContentMapValues.nodeStringValue(auth.get("username"), null);
password = XContentMapValues.nodeStringValue(auth.get("password"), null);
}
// endpoint (optional - default to github.com)
endpoint = XContentMapValues.nodeStringValue(githubSettings.get("endpoint"), "https://api.github.com");
logger.info("Created GitHub river.");
}
@Override
public void start() {
// create the index explicitly so we can use the whitespace tokenizer
// because there are usernames like "user-name" and we want those
// to be treated as just one term
try {
Settings indexSettings = ImmutableSettings.settingsBuilder().put("analysis.analyzer.default.tokenizer", "whitespace").build();
client.admin().indices().prepareCreate(index).setSettings(indexSettings).execute().actionGet();
logger.info("Created index.");
} catch (IndexAlreadyExistsException e) {
;
} catch (Exception e) {
logger.error("Exception creating index.", e);
}
dataStream = new DataStream();
dataStream.start();
logger.info("Started GitHub river.");
}
@Override
public void close() {
dataStream.setRunning(false);
logger.info("Stopped GitHub river.");
}
private class DataStream extends Thread {
private volatile boolean isRunning;
@Inject
public DataStream() {
super("DataStream thread");
isRunning = true;
}
private void indexResponse(URLConnection conn, String type) {
InputStream input = null;
try {
input = conn.getInputStream();
} catch (IOException e) {
logger.info("API rate reached, will try later.");
return;
}
JsonStreamParser jsp = new JsonStreamParser(new InputStreamReader(input));
JsonArray array = (JsonArray) jsp.next();
BulkProcessor bp = BulkProcessor.builder(client, new BulkProcessor.Listener() {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
}
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
}
}).build();
IndexRequest req = null;
for (JsonElement e: array) {
if (type.equals("event")) {
req = indexEvent(e);
} else if (type.equals("issue")) {
req = indexOther(e, "IssueData", true);
} else if (type.equals("pullreq")) {
req = indexOther(e, "PullRequestData");
} else if (type.equals("milestone")) {
req = indexOther(e, "MilestoneData");
} else if (type.equals("label")) {
req = indexOther(e, "LabelData");
} else if (type.equals("collaborator")) {
req = indexOther(e, "CollaboratorData");
}
bp.add(req);
}
bp.close();
try {
input.close();
} catch (IOException e) {}
}
private IndexRequest indexEvent(JsonElement e) {
JsonObject obj = e.getAsJsonObject();
String type = obj.get("type").getAsString();
String id = obj.get("id").getAsString();
IndexRequest req = new IndexRequest(index)
.type(type)
.id(id).create(false) // we want to overwrite old items
.source(e.toString());
return req;
}
private IndexRequest indexOther(JsonElement e, String type, boolean overwrite) {
JsonObject obj = e.getAsJsonObject();
// handle objects that don't have IDs (i.e. labels)
// set the ID to the MD5 hash of the string representation
String id;
if (obj.has("id")) {
id = obj.get("id").getAsString();
} else {
id = DigestUtils.md5Hex(e.toString());
}
IndexRequest req = new IndexRequest(index)
.type(type)
.id(id).create(!overwrite)
.source(e.toString());
return req;
}
private IndexRequest indexOther(JsonElement e, String type) {
return indexOther(e, type, false);
}
private HashMap<String, String> parseHeader(String header) {
// inspired from https://github.com/uberVU/elasticboard/blob/4ccdfd8c8e772c1dda49a29a7487d14b8d820762/data_processor/github.py#L73
Pattern p = Pattern.compile("\\<([a-z/0-9:\\.\\?_&=]+page=([0-9]+))\\>;\\s*rel=\\\"([a-z]+)\\\".*");
Matcher m = p.matcher(header);
if (!m.matches()) {
return null;
}
HashMap<String, String> data = new HashMap<String, String>();
data.put("url", m.group(1));
data.put("page", m.group(2));
data.put("rel", m.group(3));
return data;
}
private boolean morePagesAvailable(URLConnection response) {
String link = response.getHeaderField("link");
if (link == null || link.length() == 0) {
return false;
}
HashMap<String, String> headerData = parseHeader(response.getHeaderField("link"));
if (headerData == null) {
return false;
}
String rel = headerData.get("rel");
return rel.equals("next");
}
private String nextPageURL(URLConnection response) {
HashMap<String, String> headerData = parseHeader(response.getHeaderField("link"));
if (headerData == null) {
return null;
}
return headerData.get("url");
}
private void addAuthHeader(URLConnection request) {
if (username == null || password == null) {
return;
}
String auth = String.format("%s:%s", username, password);
String encoded = Base64.encodeBytes(auth.getBytes());
request.setRequestProperty("Authorization", "Basic " + encoded);
}
private void getData(String fmt, String type) {
try {
URL url = new URL(String.format(fmt, owner, repository));
URLConnection response = url.openConnection();
addAuthHeader(response);
indexResponse(response, type);
while (morePagesAvailable(response)) {
url = new URL(nextPageURL(response));
response = url.openConnection();
addAuthHeader(response);
indexResponse(response, type);
}
} catch (Exception e) {
logger.error("Exception in getData", e);
}
}
private void deleteByType(String type) {
DeleteByQueryResponse response = client.prepareDeleteByQuery(index)
.setQuery(termQuery("_type", type))
.execute()
.actionGet();
}
@Override
public void run() {
while (isRunning) {
getData("https://api.github.com/repos/%s/%s/events?per_page=1000", "event");
getData("https://api.github.com/repos/%s/%s/issues?per_page=1000", "issue");
getData("https://api.github.com/repos/%s/%s/issues?state=closed&per_page=1000", "issue");
// delete pull req data - we are only storing open pull reqs
// and when a pull request is closed we have no way of knowing;
// this is why we have to delete them and reindex "fresh" ones
deleteByType("PullRequestData");
getData("https://api.github.com/repos/%s/%s/pulls", "pullreq");
// same for milestones
deleteByType("MilestoneData");
getData("https://api.github.com/repos/%s/%s/milestones?per_page=1000", "milestone");
// collaborators
deleteByType("CollaboratorData");
getData("https://api.github.com/repos/%s/%s/collaborators?per_page=1000", "collaborator");
// and for labels - they have IDs based on the MD5 of the contents, so
// if a property changes, we get a "new" document
deleteByType("LabelData");
getData("https://api.github.com/repos/%s/%s/labels?per_page=1000", "label");
try {
Thread.sleep(interval * 1000); // needs milliseconds
} catch (InterruptedException e) {}
}
}
public void setRunning(boolean running) {
isRunning = running;
}
}
} |
package com.vzome.core.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.OutputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.vzome.core.algebra.AlgebraicField;
import com.vzome.core.algebra.AlgebraicNumber;
import com.vzome.core.algebra.AlgebraicVector;
import com.vzome.core.algebra.PentagonField;
import com.vzome.core.commands.AbstractCommand;
import com.vzome.core.commands.Command;
import com.vzome.core.commands.XmlSaveFormat;
import com.vzome.core.construction.Construction;
import com.vzome.core.construction.FreePoint;
import com.vzome.core.construction.Point;
import com.vzome.core.construction.Polygon;
import com.vzome.core.construction.Segment;
import com.vzome.core.construction.SegmentCrossProduct;
import com.vzome.core.construction.SegmentJoiningPoints;
import com.vzome.core.editor.Snapshot.SnapshotAction;
import com.vzome.core.exporters.Exporter3d;
import com.vzome.core.exporters.OpenGLExporter;
import com.vzome.core.exporters.POVRayExporter;
import com.vzome.core.exporters.PartGeometryExporter;
import com.vzome.core.math.DomUtils;
import com.vzome.core.math.Projection;
import com.vzome.core.math.RealVector;
import com.vzome.core.math.symmetry.Axis;
import com.vzome.core.math.symmetry.Direction;
import com.vzome.core.math.symmetry.IcosahedralSymmetry;
import com.vzome.core.math.symmetry.OrbitSet;
import com.vzome.core.math.symmetry.QuaternionicSymmetry;
import com.vzome.core.math.symmetry.Symmetry;
import com.vzome.core.model.Connector;
import com.vzome.core.model.Exporter;
import com.vzome.core.model.Manifestation;
import com.vzome.core.model.ManifestationChanges;
import com.vzome.core.model.Panel;
import com.vzome.core.model.RealizedModel;
import com.vzome.core.model.Strut;
import com.vzome.core.model.VefModelExporter;
import com.vzome.core.render.Color;
import com.vzome.core.render.Colors;
import com.vzome.core.render.RenderedModel;
import com.vzome.core.render.RenderedModel.OrbitSource;
import com.vzome.core.viewing.Camera;
import com.vzome.core.viewing.Lights;
public class DocumentModel implements Snapshot .Recorder, UndoableEdit .Context, Tool .Registry
{
private final RealizedModel mRealizedModel;
private final Point originPoint;
private final Selection mSelection;
private final EditorModel mEditorModel;
private SymmetrySystem symmetrySystem;
private final EditHistory mHistory;
private final LessonModel lesson = new LessonModel();
private final AlgebraicField mField;
private final Map<String, Tool> tools = new LinkedHashMap<>();
private final Command.FailureChannel failures;
private int changes = 0;
private boolean migrated = false;
private final Element mXML;
private RenderedModel renderedModel;
private Camera defaultView;
private final String coreVersion;
private static final Logger logger = Logger .getLogger( "com.vzome.core.editor" );
private static final Logger thumbnailLogger = Logger.getLogger( "com.vzome.core.thumbnails" );
// 2013-05-26
// I thought about leaving these two in EditorModel, but reconsidered. Although they are in-memory
// state only, not saved in the file, they are still necessary for non-interactive use such as lesson export.
private RenderedModel[] snapshots = new RenderedModel[8];
private int numSnapshots = 0;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport( this );
private final Map<String, Object> commands; // TODO: DJH: Don't allow non-Command objects in this Map.
private final Map<String,SymmetrySystem> symmetrySystems = new HashMap<>();
private final Lights sceneLighting;
public void addPropertyChangeListener( PropertyChangeListener listener )
{
propertyChangeSupport .addPropertyChangeListener( listener );
}
public void removePropertyChangeListener( PropertyChangeListener listener )
{
propertyChangeSupport .removePropertyChangeListener( listener );
}
protected void firePropertyChange( String propertyName, Object oldValue, Object newValue )
{
propertyChangeSupport .firePropertyChange( propertyName, oldValue, newValue );
}
protected void firePropertyChange( String propertyName, int oldValue, int newValue )
{
propertyChangeSupport .firePropertyChange( propertyName, oldValue, newValue );
}
public DocumentModel( final AlgebraicField field, Command.FailureChannel failures, Element xml, final Application app )
{
super();
this .mField = field;
AlgebraicVector origin = field .origin( 3 );
this .originPoint = new FreePoint( origin );
this .failures = failures;
this .mXML = xml;
this .commands = app .getCommands();
this .sceneLighting = app .getLights();
this .coreVersion = app .getCoreVersion();
this .mRealizedModel = new RealizedModel( field, new Projection.Default( field ) );
this .mSelection = new Selection();
Symmetry[] symms = field .getSymmetries();
for (Symmetry symm : symms) {
SymmetrySystem osm = new SymmetrySystem( null, symm, app .getColors(), app .getGeometries( symm ), true );
// one of these will be overwritten below, if we are loading from a file that has it set
this .symmetrySystems .put( osm .getName(), osm );
try {
String name = symm .getName();
makeTool( name + ".builtin/" + name + " around origin", name, this, symm ) .perform();
} catch ( Command.Failure e ) {
logger .severe( "Failed to create " + symm .getName() + " tool." );
}
}
if ( xml != null ) {
NodeList nl = xml .getElementsByTagName( "SymmetrySystem" );
if ( nl .getLength() != 0 )
xml = (Element) nl .item( 0 );
else
xml = null;
}
String symmName = ( xml != null )? xml .getAttribute( "name" ) : symms[ 0 ] .getName();
Symmetry symmetry = field .getSymmetry( symmName );
this .symmetrySystem = new SymmetrySystem( xml, symmetry, app .getColors(), app .getGeometries( symmetry ), true );
this .symmetrySystems .put( symmName, this .symmetrySystem );
try {
makeTool( "tetrahedral.builtin/tetrahedral around origin", "tetrahedral", this, symmetry ) .perform();
makeTool( "point reflection.builtin/reflection through origin", "point reflection", this, symmetry ) .perform();
makeTool( "scaling.builtin/scale up", "scale up", this, symmetry ) .perform();
makeTool( "scaling.builtin/scale down", "scale down", this, symmetry ) .perform();
makeTool( "translation.builtin/move right", "translation", this, symmetry ) .perform();
makeTool( "mirror.builtin/reflection through XY plane", "mirror", this, symmetry ) .perform();
makeTool( "bookmark.builtin/ball at origin", "bookmark", this, symmetry ) .perform();
if ( symmetry instanceof IcosahedralSymmetry ) {
makeTool( "rotation.builtin/rotate around red through origin", "axial symmetry", this, symmetry ) .perform();
makeTool( "axial symmetry.builtin/symmetry around red through origin", "axial symmetry", this, symmetry ) .perform();
}
} catch ( Command.Failure e ) {
logger .severe( "Failed to create built-in tools." );
}
this .renderedModel = new RenderedModel( field, this .symmetrySystem );
this .mRealizedModel .addListener( this .renderedModel ); // just setting the default
// the renderedModel must either be disabled, or have shapes here, so the origin ball gets rendered
this .mEditorModel = new EditorModel( this .mRealizedModel, this .mSelection, /*oldGroups*/ false, originPoint );
this .defaultView = new Camera();
Element views = ( this .mXML == null )? null : (Element) this .mXML .getElementsByTagName( "Viewing" ) .item( 0 );
if ( views != null ) {
NodeList nodes = views .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node node = nodes .item( i );
if ( node instanceof Element ) {
Element viewElem = (Element) node;
String name = viewElem .getAttribute( "name" );
if ( ( name == null || name .isEmpty() )
|| ( "default" .equals( name ) ) )
{
this .defaultView = new Camera( viewElem );
}
}
}
}
mHistory = new EditHistory();
mHistory .setListener( new EditHistory.Listener() {
@Override
public void showCommand( Element xml, int editNumber )
{
String str = editNumber + ": " + DomUtils .toString( xml );
DocumentModel.this .firePropertyChange( "current.edit.xml", null, str );
}
});
lesson .addPropertyChangeListener( new PropertyChangeListener()
{
@Override
public void propertyChange( PropertyChangeEvent change )
{
if ( "currentSnapshot" .equals( change .getPropertyName() ) )
{
int id = ((Integer) change .getNewValue());
RenderedModel newSnapshot = snapshots[ id ];
firePropertyChange( "currentSnapshot", null, newSnapshot );
}
else if ( "currentView" .equals( change .getPropertyName() ) )
{
// forward to doc listeners
firePropertyChange( "currentView", change .getOldValue(), change .getNewValue() );
}
else if ( "thumbnailChanged" .equals( change .getPropertyName() ) )
{
// forward to doc listeners
firePropertyChange( "thumbnailChanged", change .getOldValue(), change .getNewValue() );
}
}
} );
}
public int getChangeCount()
{
return this .changes;
}
public boolean isMigrated()
{
return this .migrated;
}
public void setRenderedModel( RenderedModel renderedModel )
{
this .mRealizedModel .removeListener( this .renderedModel );
this .renderedModel = renderedModel;
this .mRealizedModel .addListener( renderedModel );
// "re-render" the origin
Manifestation m = this .mRealizedModel .findConstruction( originPoint );
m .setRenderedObject( null );
this .mRealizedModel .show( m );
}
@Override
public UndoableEdit createEdit( Element xml, boolean groupInSelection )
{
UndoableEdit edit = null;
String name = xml .getLocalName();
if ( "Snapshot" .equals( name ) )
edit = new Snapshot( -1, this );
else if ( "Branch" .equals( name ) )
edit = new Branch( this );
else if ( "Delete" .equals( name ) )
edit = new Delete( this.mSelection, this.mRealizedModel );
else if ( "ShowPoint".equals( name ) )
edit = new ShowPoint( null, this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "setItemColor".equals( name ) )
edit = new ColorManifestations( this.mSelection, this.mRealizedModel, null, groupInSelection );
else if ( "ShowHidden".equals( name ) )
edit = new ShowHidden( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "CrossProduct".equals( name ) )
edit = new CrossProduct( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "AffinePentagon".equals( name ) )
edit = new AffinePentagon( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "AffineTransformAll".equals( name ) )
edit = new AffineTransformAll( this.mSelection, this.mRealizedModel, this.mEditorModel.getCenterPoint(), groupInSelection );
else if ( "HeptagonSubdivision".equals( name ) )
edit = new HeptagonSubdivision( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "DodecagonSymmetry".equals( name ) )
edit = new DodecagonSymmetry( this.mSelection, this.mRealizedModel, this.mEditorModel.getCenterPoint(), groupInSelection );
else if ( "GhostSymmetry24Cell".equals( name ) )
edit = new GhostSymmetry24Cell( this.mSelection, this.mRealizedModel, this.mEditorModel.getSymmetrySegment(),
groupInSelection );
else if ( "StrutCreation".equals( name ) )
edit = new StrutCreation( null, null, null, this.mRealizedModel );
else if ( "BnPolyope".equals( name ) || "B4Polytope".equals( name ) )
edit = new B4Polytope( this.mSelection, this.mRealizedModel, this .mField, null, 0, groupInSelection );
else if ( "Polytope4d".equals( name ) )
edit = new Polytope4d( this.mSelection, this.mRealizedModel, null, 0, null, groupInSelection );
else if ( "LoadVEF".equals( name ) )
edit = new LoadVEF( this.mSelection, this.mRealizedModel, null, null, null );
else if ( "GroupSelection".equals( name ) )
edit = new GroupSelection( this.mSelection, false );
else if ( "BeginBlock".equals( name ) )
edit = new BeginBlock();
else if ( "EndBlock".equals( name ) )
edit = new EndBlock();
else if ( "InvertSelection".equals( name ) )
edit = new InvertSelection( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "JoinPoints".equals( name ) )
edit = new JoinPoints( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "NewCentroid" .equals( name ) )
edit = new Centroid( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "StrutIntersection".equals( name ) )
edit = new StrutIntersection( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "LinePlaneIntersect".equals( name ) )
edit = new LinePlaneIntersect( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "SelectAll".equals( name ) )
edit = new SelectAll( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "DeselectAll".equals( name ) )
edit = new DeselectAll( this.mSelection, groupInSelection );
else if ( "DeselectByClass".equals( name ) )
edit = new DeselectByClass( this.mSelection, false );
else if ( "SelectManifestation".equals( name ) )
edit = new SelectManifestation( null, false, this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "SelectNeighbors".equals( name ) )
edit = new SelectNeighbors( this.mSelection, this.mRealizedModel, groupInSelection );
else if ( "SelectSimilarSize".equals( name ) )
{
/*
The normal pattern is to have the edits deserialize their own parameters from the XML in setXmlAttributes()
but in the case of persisting the symmetry, it must be read here and passed into the c'tor
since this is where the map from a name to an actual SymmetrySystem is maintained.
These edits are still responsible for saving the symmetry name to XML in getXmlAttributes().
Also see the comments of commit # 8c8cb08a1e4d71f91f24669b203fef0378230b19 on 3/8/2015
*/
SymmetrySystem symmetry = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectSimilarSizeStruts( symmetry, null, null, this .mSelection, this .mRealizedModel );
}
else if ( "SelectParallelStruts".equals( name ) )
{
// See the note above about deserializing symmetry from XML.
SymmetrySystem symmetry = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectParallelStruts( symmetry, this .mSelection, this .mRealizedModel );
}
else if ( "SelectAutomaticStruts".equals( name ) )
{
// See the note above about deserializing symmetry from XML.
SymmetrySystem symmetry = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectAutomaticStruts( symmetry, this .mSelection, this .mRealizedModel );
}
else if ( "SelectCollinear".equals( name ) )
{
edit = new SelectCollinear( this .mSelection, this .mRealizedModel );
}
else if ( "ValidateSelection".equals( name ) )
edit = new ValidateSelection( this.mSelection );
else if ( "SymmetryCenterChange".equals( name ) )
edit = new SymmetryCenterChange( this.mEditorModel, null );
else if ( "SymmetryAxisChange".equals( name ) )
edit = new SymmetryAxisChange( this.mEditorModel, null );
else if ( "RunZomicScript".equals( name ) )
edit = new RunZomicScript( this.mSelection, this.mRealizedModel, null, mEditorModel.getCenterPoint() );
else if ( "RunPythonScript".equals( name ) )
edit = new RunPythonScript( this.mSelection, this.mRealizedModel, null, mEditorModel.getCenterPoint() );
else if ( "BookmarkTool".equals( name ) )
edit = new BookmarkTool( name, this.mSelection, this.mRealizedModel, this );
else if ( "ModuleTool" .equals( name ) )
edit = new ModuleTool( null, mSelection, mRealizedModel, this );
else if ( "PlaneSelectionTool" .equals( name ) )
edit = new PlaneSelectionTool( null, mSelection, mField, this );
else if ( "SymmetryTool".equals( name ) )
edit = new SymmetryTool( null, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "ScalingTool".equals( name ) )
edit = new ScalingTool( name, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "RotationTool".equals( name ) )
edit = new RotationTool( name, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "InversionTool".equals( name ) )
edit = new InversionTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "MirrorTool".equals( name ) )
edit = new MirrorTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "TranslationTool".equals( name ) )
edit = new TranslationTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
else if ( "LinearMapTool".equals( name ) )
edit = new LinearMapTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint, true );
else if ( "AxialStretchTool".equals( name ) ) {
IcosahedralSymmetry symmetry = (IcosahedralSymmetry) mField .getSymmetry( "icosahedral" );
edit = new AxialStretchTool( name, symmetry, mSelection, mRealizedModel, this, false, true, false );
}
else if ( "LinearTransformTool".equals( name ) )
edit = new LinearMapTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint, false );
else if ( "ToolApplied".equals( name ) )
edit = new ApplyTool( this.mSelection, this.mRealizedModel, this, false );
else if ( "ApplyTool".equals( name ) )
edit = new ApplyTool( this.mSelection, this.mRealizedModel, this, true );
else if ( RealizeMetaParts.NAME .equals( name ) )
edit = new RealizeMetaParts( mSelection, mRealizedModel );
else if ( ShowVertices.NAME .equals( name ) )
edit = new ShowVertices( mSelection, mRealizedModel );
else if ( "Symmetry4d".equals( name ) ) {
QuaternionicSymmetry h4symm = this .mField .getQuaternionSymmetry( "H_4" );
edit = new Symmetry4d( this.mSelection, this.mRealizedModel, h4symm, h4symm );
}
if ( edit == null )
// any command unknown (i.e. from a newer version of vZome) becomes a CommandEdit
edit = new CommandEdit( null, mEditorModel, groupInSelection );
return edit;
}
public String copySelectionVEF()
{
StringWriter out = new StringWriter();
Exporter exporter = new VefModelExporter( out, mField );
for (Manifestation man : mSelection) {
exporter .exportManifestation( man );
}
exporter .finish();
return out .toString();
}
public void pasteVEF( String vefContent )
{
if( vefContent != null && vefContent.startsWith("vZome VEF" )) {
// Although older VEF formats don't all include the header and could possibly be successfully pasted here,
// we're going to limit it to at least something that includes a valid VEF header.
// We won't check the version number so we can still paste formats older than VERSION_W_FIRST
// as long as they at least include the minimal header.
UndoableEdit edit = new LoadVEF( this.mSelection, this.mRealizedModel, vefContent, null, null );
performAndRecord( edit );
}
}
public void applyTool( Tool tool, Tool.Registry registry, int modes )
{
UndoableEdit edit = new ApplyTool( this.mSelection, this.mRealizedModel, tool, registry, modes, true );
performAndRecord( edit );
}
public void selectToolParameters( TransformationTool tool )
{
UndoableEdit edit = new SelectToolParameters( this.mSelection, this.mRealizedModel, this, tool );
performAndRecord( edit );
}
public void applyQuaternionSymmetry( QuaternionicSymmetry left, QuaternionicSymmetry right )
{
UndoableEdit edit = new Symmetry4d( this.mSelection, this.mRealizedModel, left, right );
performAndRecord( edit );
}
public boolean doEdit( String action )
{
// TODO break all these cases out as dedicated DocumentModel methods
if ( this .mEditorModel .mSelection .isEmpty() && action .equals( "hideball" ) ) {
action = "showHidden";
}
Command command = (Command) commands .get( action );
if ( command != null )
{
CommandEdit edit = new CommandEdit( (AbstractCommand) command, mEditorModel, false );
this .performAndRecord( edit );
return true;
}
UndoableEdit edit = null;
if ( action.equals( "selectAll" ) )
edit = mEditorModel.selectAll();
else if ( action.equals( "unselectAll" ) )
edit = mEditorModel.unselectAll();
else if ( action.equals( "unselectBalls" ) )
edit = mEditorModel.unselectConnectors();
else if ( action.equals( "unselectStruts" ) )
edit = mEditorModel.unselectStruts();
else if ( action.equals( "selectNeighbors" ) )
edit = mEditorModel.selectNeighbors();
else if ( action.equals( "SelectAutomaticStruts" ) )
edit = mEditorModel.selectAutomaticStruts(symmetrySystem);
else if ( action.equals( "SelectCollinear" ) )
edit = mEditorModel.selectCollinear();
else if ( action.equals( "SelectParallelStruts" ) )
edit = mEditorModel.selectParallelStruts(symmetrySystem);
else if ( action.equals( "invertSelection" ) )
edit = mEditorModel.invertSelection();
else if ( action.equals( "group" ) )
edit = mEditorModel.groupSelection();
else if ( action.equals( "ungroup" ) )
edit = mEditorModel.ungroupSelection();
else if ( action.equals( "assertSelection" ) )
edit = new ValidateSelection( mSelection );
else if ( action.equals( "delete" ) )
edit = new Delete( mSelection, mRealizedModel );
// else if ( action.equals( "sixLattice" ) )
// edit = new SixLattice( mSelection, mRealizedModel, mDerivationModel );
// not supported currently, so I don't have to deal with the mTargetManifestation problem
// else if ( action .equals( "reversePanel" ) )
// edit = new ReversePanel( mTargetManifestation, mSelection, mRealizedModel, mDerivationModel );
else if ( action.equals( "createStrut" ) )
edit = new StrutCreation( null, null, null, mRealizedModel );
else if ( action.startsWith( "setItemColor/" ) )
{
String value = action .substring( "setItemColor/" .length() );
edit = new ColorManifestations( mSelection, mRealizedModel, new Color( value ), false );
}
else if ( action.equals( "joinballs" ) )
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.CLOSED_LOOP );
else if ( action .toLowerCase() .equals( "chainballs" ) )
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.CHAIN_BALLS );
else if ( action.equals( "joinBallsAllToFirst" ) )
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_TO_FIRST );
else if ( action.equals( "joinBallsAllToLast" ) )
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_TO_LAST );
else if ( action.equals( "joinBallsAllPossible" ) )
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_POSSIBLE );
else if ( ShowVertices.NAME .toLowerCase() .equals( action .toLowerCase() ) )
edit = new ShowVertices( mSelection, mRealizedModel );
else if ( action.equals( "ballAtOrigin" ) )
edit = new ShowPoint( originPoint, mSelection, mRealizedModel, false );
else if ( action.equals( "ballAtSymmCenter" ) )
edit = new ShowPoint( mEditorModel.getCenterPoint(), mSelection, mRealizedModel, false );
else if ( action.equals( "linePlaneIntersect" ) )
edit = new LinePlaneIntersect( mSelection, mRealizedModel, false );
else if ( action.equals( "lineLineIntersect" ) )
edit = new StrutIntersection( mSelection, mRealizedModel, false );
else if ( action.equals( "heptagonDivide" ) )
edit = new HeptagonSubdivision( mSelection, mRealizedModel, false );
else if ( action.equals( "crossProduct" ) )
edit = new CrossProduct( mSelection, mRealizedModel, false );
else if ( action.equals( "centroid" ) )
edit = new Centroid( mSelection, mRealizedModel, false );
else if ( action.equals( "showHidden" ) )
edit = new ShowHidden( mSelection, mRealizedModel, false );
else if ( action.equals( RealizeMetaParts.NAME ) )
edit = new RealizeMetaParts( mSelection, mRealizedModel );
else if ( action.equals( "affinePentagon" ) )
edit = new AffinePentagon( mSelection, mRealizedModel, false );
else if ( action.equals( "affineTransformAll" ) )
edit = new AffineTransformAll( mSelection, mRealizedModel, mEditorModel.getCenterPoint(), false );
else if ( action.equals( "dodecagonsymm" ) )
edit = new DodecagonSymmetry( mSelection, mRealizedModel, mEditorModel.getCenterPoint(), false );
else if ( action.equals( "ghostsymm24cell" ) )
edit = new GhostSymmetry24Cell( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(), false );
else if ( action.equals( "apiProxy" ) )
edit = new ApiEdit( this .mSelection, this .mRealizedModel, this .originPoint );
else if ( action.startsWith( "polytope_" ) )
{
int beginIndex = "polytope_".length();
String group = action.substring( beginIndex, beginIndex + 2 );
String suffix = action.substring( beginIndex + 2 );
System.out.println( "computing " + group + " " + suffix );
int index = Integer.parseInt( suffix, 2 );
edit = new Polytope4d( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(),
index, group, false );
}
if ( edit == null )
{
logger .warning( "no DocumentModel action for : " + action );
return false;
}
this .performAndRecord( edit );
return true;
}
@Override
public void performAndRecord( UndoableEdit edit )
{
if ( edit == null )
return;
if ( edit instanceof NoOp )
return;
try {
synchronized ( this .mHistory ) {
edit .perform();
this .mHistory .mergeSelectionChanges();
this .mHistory .addEdit( edit, DocumentModel.this );
}
}
catch ( RuntimeException re )
{
Throwable cause = re.getCause();
if ( cause instanceof Command.Failure )
this .failures .reportFailure( (Command.Failure) cause );
else if ( cause != null )
this .failures .reportFailure( new Command.Failure( cause ) );
else
this .failures .reportFailure( new Command.Failure( re ) );
}
catch ( Command.Failure failure )
{
this .failures .reportFailure( failure );
}
this .changes++;
}
public void setParameter( Construction singleConstruction, String paramName ) throws Command.Failure
{
UndoableEdit edit = null;
if ( "ball" .equals( paramName ) )
edit = mEditorModel .setSymmetryCenter( singleConstruction );
else if ( "strut" .equals( paramName ) )
edit = mEditorModel .setSymmetryAxis( (Segment) singleConstruction );
if ( edit != null )
this .performAndRecord( edit );
}
public RealVector getLocation( Construction target )
{
if ( target instanceof Point)
return ( (Point) target ).getLocation() .toRealVector();
else if ( target instanceof Segment )
return ( (Segment) target ).getStart() .toRealVector();
else if ( target instanceof Polygon )
return ( (Polygon) target ).getVertices()[ 0 ] .toRealVector();
else
return new RealVector( 0, 0, 0 );
}
public RealVector getParamLocation( String string )
{
if ( "ball" .equals( string ) )
{
Point ball = mEditorModel .getCenterPoint();
return ball .getLocation() .toRealVector();
}
return new RealVector( 0, 0, 0 );
}
public void selectCollinear( Strut strut )
{
UndoableEdit edit = new SelectCollinear( mSelection, mRealizedModel, strut );
this .performAndRecord( edit );
}
public void selectParallelStruts( Strut strut )
{
UndoableEdit edit = new SelectParallelStruts( this.symmetrySystem, mSelection, mRealizedModel, strut );
this .performAndRecord( edit );
}
public void selectSimilarStruts( Direction orbit, AlgebraicNumber length )
{
UndoableEdit edit = new SelectSimilarSizeStruts( this.symmetrySystem, orbit, length, mSelection, mRealizedModel );
this .performAndRecord( edit );
}
public Color getSelectionColor()
{
Manifestation last = null;
for (Manifestation man : mSelection) {
last = man;
}
return last == null ? null : last .getRenderedObject() .getColor();
}
public void finishLoading( boolean openUndone, boolean asTemplate ) throws Command.Failure
{
if ( mXML == null )
return;
// TODO: record the edition, version, and revision on the format, so we can report a nice
// error if we fail to understand some command in the history. If the revision is
// greater than Version .SVN_REVISION:
// "This document was created using $file.edition $file.version, and contains commands that
// $Version.edition does not understand. You may need a newer version of
// $Version.edition, or a copy of $file.edition $file.version."
// (Adjust that if $Version.edition == $file.edition, to avoid confusion.)
String tns = mXML .getNamespaceURI();
XmlSaveFormat format = XmlSaveFormat.getFormat( tns );
if ( format == null )
return; // already checked and reported version compatibility,
// up in the constructor
int scale = 0;
String scaleStr = mXML .getAttribute( "scale" );
if ( ! scaleStr .isEmpty() )
scale = Integer.parseInt( scaleStr );
OrbitSet.Field orbitSetField = new OrbitSet.Field()
{
@Override
public OrbitSet getGroup( String name )
{
SymmetrySystem system = symmetrySystems .get( name );
return system .getOrbits();
}
@Override
public QuaternionicSymmetry getQuaternionSet( String name )
{
return mField .getQuaternionSymmetry( name);
}
};
String writerVersion = mXML .getAttribute( "version" );
String buildNum = mXML .getAttribute( "buildNumber" );
if ( buildNum != null )
writerVersion += " build " + buildNum;
format .initialize( mField, orbitSetField, scale, writerVersion, new Properties() );
Element hist = (Element) mXML .getElementsByTagName( "EditHistory" ) .item( 0 );
if ( hist == null )
hist = (Element) mXML .getElementsByTagName( "editHistory" ) .item( 0 );
int editNum = Integer.parseInt( hist .getAttribute( "editNumber" ) );
List<Integer> implicitSnapshots = new ArrayList<>();
// if we're opening a template document, we don't want to inherit its lesson or saved views
if ( !asTemplate )
{
Map<String, Camera> viewPages = new HashMap<>();
Element views = (Element) mXML .getElementsByTagName( "Viewing" ) .item( 0 );
if ( views != null ) {
// make a notes page for each saved view
// ("edited" property change will be fired, to trigger migration semantics)
// migrate saved views to notes pages
NodeList nodes = views .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node node = nodes .item( i );
if ( node instanceof Element ) {
Element viewElem = (Element) node;
String name = viewElem .getAttribute( "name" );
if ( name != null && ! name .isEmpty() && ! "default" .equals( name ) )
{
Camera view = new Camera( viewElem );
viewPages .put( name, view ); // named view to migrate to a lesson page
}
}
}
}
Element notesXml = (Element) mXML .getElementsByTagName( "notes" ) .item( 0 );
if ( notesXml != null )
lesson .setXml( notesXml, editNum, this .defaultView );
// add migrated views to the end of the lesson
for (Entry<String, Camera> namedView : viewPages .entrySet()) {
lesson .addPage( namedView .getKey(), "This page was a saved view created by an older version of vZome.", namedView .getValue(), -editNum );
}
for (PageModel page : lesson) {
int snapshot = page .getSnapshot();
if ( ( snapshot < 0 ) && ( ! implicitSnapshots .contains(-snapshot) ) )
implicitSnapshots .add(-snapshot);
}
Collections .sort( implicitSnapshots );
for (PageModel page : lesson) {
int snapshot = page .getSnapshot();
if ( snapshot < 0 )
page .setSnapshot( implicitSnapshots .indexOf(-snapshot) );
}
}
UndoableEdit[] explicitSnapshots = null;
if ( ! implicitSnapshots .isEmpty() )
{
Integer highest = implicitSnapshots .get( implicitSnapshots .size() - 1 );
explicitSnapshots = new UndoableEdit[ highest + 1 ];
for (int i = 0; i < implicitSnapshots .size(); i++)
{
Integer editNumInt = implicitSnapshots .get( i );
explicitSnapshots[ editNumInt ] = new Snapshot( i, this );
}
}
try {
int lastDoneEdit = openUndone? 0 : Integer.parseInt( hist .getAttribute( "editNumber" ) );
String lseStr = hist .getAttribute( "lastStickyEdit" );
int lastStickyEdit = ( ( lseStr == null ) || lseStr .isEmpty() )? -1 : Integer .parseInt( lseStr );
NodeList nodes = hist .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node kid = nodes .item( i );
if ( kid instanceof Element ) {
Element editElem = (Element) kid;
mHistory .loadEdit( format, editElem, this );
}
}
mHistory .synchronize( lastDoneEdit, lastStickyEdit, explicitSnapshots );
} catch ( Throwable t )
{
String fileVersion = mXML .getAttribute( "coreVersion" );
if ( this .fileIsTooNew( fileVersion ) ) {
String message = "This file was authored with a newer version, " + format .getToolVersion( mXML );
throw new Command.Failure( message, t );
} else {
String message = "There was a problem opening this file. Please send the file to bugs@vzome.com.";
throw new Command.Failure( message, t );
}
}
this .migrated = openUndone || format.isMigration() || ! implicitSnapshots .isEmpty();
}
boolean fileIsTooNew( String fileVersion )
{
if ( fileVersion == null || "" .equals( fileVersion ) )
return false;
String[] fvTokens = fileVersion .split( "\\." );
String[] cvTokens = this .coreVersion .split( "\\." );
for (int i = 0; i < cvTokens.length; i++) {
try {
int codepart = Integer .parseInt( cvTokens[ i ] );
int filepart = Integer .parseInt( fvTokens[ i ] );
if ( filepart > codepart )
return true;
} catch ( NumberFormatException e ) {
return false;
}
}
return false;
}
public Element getDetailsXml( Document doc )
{
Element vZomeRoot = doc .createElementNS( XmlSaveFormat.CURRENT_FORMAT, "vzome:vZome" );
vZomeRoot .setAttribute( "xmlns:vzome", XmlSaveFormat.CURRENT_FORMAT );
vZomeRoot .setAttribute( "field", mField.getName() );
Element result = mHistory .getDetailXml( doc );
vZomeRoot .appendChild( result );
return vZomeRoot;
}
/**
* For backward-compatibility
* @param out
* @throws Exception
*/
public void serialize( OutputStream out ) throws Exception
{
Properties props = new Properties();
props .setProperty( "edition", "vZome" );
props .setProperty( "version", "5.0" );
this .serialize( out, props );
}
public void serialize( OutputStream out, Properties editorProps ) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance();
factory .setNamespaceAware( true );
DocumentBuilder builder = factory .newDocumentBuilder();
Document doc = builder .newDocument();
Element vZomeRoot = doc .createElementNS( XmlSaveFormat.CURRENT_FORMAT, "vzome:vZome" );
vZomeRoot .setAttribute( "xmlns:vzome", XmlSaveFormat.CURRENT_FORMAT );
String value = editorProps .getProperty( "edition" );
if ( value != null )
vZomeRoot .setAttribute( "edition", value );
value = editorProps .getProperty( "version" );
if ( value != null )
vZomeRoot .setAttribute( "version", value );
value = editorProps .getProperty( "buildNumber" );
if ( value != null )
vZomeRoot .setAttribute( "buildNumber", value );
vZomeRoot .setAttribute( "coreVersion", this .coreVersion );
vZomeRoot .setAttribute( "field", mField.getName() );
Element childElement;
{
childElement = mHistory .getXml( doc );
int edits = 0, lastStickyEdit=-1;
for (UndoableEdit undoable : mHistory) {
childElement .appendChild( undoable .getXml( doc ) );
++ edits;
if ( undoable .isSticky() )
lastStickyEdit = edits;
}
childElement .setAttribute( "lastStickyEdit", Integer .toString( lastStickyEdit ) );
}
vZomeRoot .appendChild( childElement );
doc .appendChild( vZomeRoot );
childElement = lesson .getXml( doc );
vZomeRoot .appendChild( childElement );
childElement = sceneLighting .getXml( doc );
vZomeRoot .appendChild( childElement );
childElement = doc .createElement( "Viewing" );
Element viewXml = this .defaultView .getXML( doc );
childElement .appendChild( viewXml );
vZomeRoot .appendChild( childElement );
childElement = this .symmetrySystem .getXml( doc );
vZomeRoot .appendChild( childElement );
DomUtils .serialize( doc, out );
}
public void doScriptAction( String command, String script )
{
UndoableEdit edit = null;
if ( command.equals( "runZomicScript" ) || command.equals( "zomic" ) )
{
edit = new RunZomicScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint() );
this .performAndRecord( edit );
}
else if ( command.equals( "runPythonScript" ) || command.equals( "py" ) )
{
edit = new RunPythonScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint() );
this .performAndRecord( edit );
}
// else if ( command.equals( "import.zomod" ) )
// edit = new RunZomodScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint(), mField .getSymmetry( "icosahedral" ) );
else if ( command.equals( "import.vef" ) || command.equals( "vef" ) )
{
Segment symmAxis = mEditorModel .getSymmetrySegment();
AlgebraicVector quat = ( symmAxis == null ) ? null : symmAxis.getOffset();
if ( quat != null )
quat = quat .scale( mField .createPower( - 5 ) );
AlgebraicNumber scale = mField .createPower( 5 );
edit = new LoadVEF( mSelection, mRealizedModel, script, quat, scale );
this .performAndRecord( edit );
}
}
@Override
public void addTool( Tool tool )
{
String name = tool .getName();
tools .put( name, tool );
firePropertyChange( "tool.instances", null, name );
}
@Override
public Tool findEquivalent( Tool tool )
{
for ( Map.Entry<String, Tool> entry : tools .entrySet() )
{
if ( entry .getValue() .equals( tool ) )
return entry .getValue();
}
return null;
}
@Override
public Tool getTool( String toolName )
{
return tools .get( toolName );
}
public AlgebraicField getField()
{
return this .mField;
}
public void addSelectionListener( ManifestationChanges listener )
{
this .mSelection .addListener( listener );
}
private static final NumberFormat FORMAT = NumberFormat .getNumberInstance( Locale .US );
/**
* @deprecated As of 8/11/2016:
* This code will continue to function properly,
* but its functionality has been replicated in vzome-desktop.
*
* Formatting such information for display should not be a function of vzome-core.
*
* When all references to this method have been replaced,
* then it should be removed from vzome-core.
*/
@Deprecated
public String getManifestationProperties( Manifestation man, OrbitSource symmetry )
{
if ( man instanceof Connector )
{
StringBuffer buf;
AlgebraicVector loc = man .getLocation();
System .out .println( loc .getVectorExpression( AlgebraicField.EXPRESSION_FORMAT ) );
System .out .println( loc .getVectorExpression( AlgebraicField.ZOMIC_FORMAT ) );
System .out .println( loc .getVectorExpression( AlgebraicField.VEF_FORMAT ) );
buf = new StringBuffer();
buf .append( "location: " );
loc .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
return buf.toString();
}
else if ( man instanceof Strut ) {
StringBuffer buf = new StringBuffer();
buf.append( "start: " );
Strut strut = Strut.class.cast(man);
strut .getLocation() .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( "\n\noffset: " );
AlgebraicVector offset = strut .getOffset();
System .out .println( offset .getVectorExpression( AlgebraicField.EXPRESSION_FORMAT ) );
System .out .println( offset .getVectorExpression( AlgebraicField.ZOMIC_FORMAT ) );
System .out .println( offset .getVectorExpression( AlgebraicField.VEF_FORMAT ) );
offset .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( "\n\nnorm squared: " );
AlgebraicNumber normSquared = offset .dot( offset );
double norm2d = normSquared .evaluate();
normSquared .getNumberExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( " = " );
buf.append( FORMAT.format( norm2d ) );
if ( offset .isOrigin() )
return "zero length!";
Axis zone = symmetry .getAxis( offset );
AlgebraicNumber len = zone .getLength( offset );
len = zone .getOrbit() .getLengthInUnits( len );
buf.append( "\n\nlength in orbit units: " );
len .getNumberExpression( buf, AlgebraicField.DEFAULT_FORMAT );
if ( mField instanceof PentagonField)
{
buf.append( "\n\nlength in Zome b1 struts: " );
if (FORMAT instanceof DecimalFormat) {
((DecimalFormat) FORMAT) .applyPattern( "0.0000" );
}
buf.append( FORMAT.format( Math.sqrt( norm2d ) / PentagonField.B1_LENGTH ) );
}
return buf .toString();
}
else if ( man instanceof Panel ) {
Panel panel = Panel.class.cast(man);
StringBuffer buf = new StringBuffer();
buf .append( "vertices: " );
buf .append( panel.getVertexCount() );
String delim = "";
for( AlgebraicVector vertex : panel) {
buf.append(delim);
buf.append("\n ");
vertex .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
delim = ",";
}
AlgebraicVector normal = panel .getNormal();
buf .append( "\n\nnormal: " );
normal .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append("\n\nnorm squared: ");
AlgebraicNumber normSquared = normal.dot(normal);
double norm2d = normSquared.evaluate();
normSquared.getNumberExpression(buf, AlgebraicField.DEFAULT_FORMAT);
buf.append(" = ");
buf.append(FORMAT.format(norm2d));
Axis zone = symmetry .getAxis( normal );
Direction direction = zone.getDirection();
buf.append( "\n\ndirection: " );
if( direction.isAutomatic() ) {
buf.append( "Automatic " );
}
buf.append( direction.getName() );
return buf.toString();
}
return man.getClass().getSimpleName();
}
public void undo( boolean useBlocks )
{
mHistory .undo( useBlocks );
}
public void redo( boolean useBlocks ) throws Command.Failure
{
mHistory .redo( useBlocks );
}
public void undo()
{
mHistory .undo();
}
public void redo() throws Command.Failure
{
mHistory .redo();
}
public void undoToBreakpoint()
{
mHistory .undoToBreakpoint();
}
public void undoToManifestation( Manifestation man )
{
mHistory .undoToManifestation( man );
}
public void redoToBreakpoint() throws Command.Failure
{
mHistory .redoToBreakpoint();
}
public void setBreakpoint()
{
mHistory .setBreakpoint();
}
public void undoAll()
{
mHistory .undoAll();
}
public void redoAll( int i ) throws Command .Failure
{
mHistory .redoAll( i );
}
public UndoableEdit deselectAll()
{
return mEditorModel .unselectAll();
}
public UndoableEdit selectManifestation( Manifestation target, boolean replace )
{
return mEditorModel .selectManifestation( target, replace );
}
public void createStrut( Point point, Axis zone, AlgebraicNumber length )
{
UndoableEdit edit = new StrutCreation( point, zone, length, this .mRealizedModel );
this .performAndRecord( edit );
}
public boolean isToolEnabled( String group, Symmetry symmetry )
{
Tool tool = (Tool) makeTool( group + ".0/UNUSED", group, null, symmetry ); // TODO: get rid of isAutomatic() and isTetrahedral() silliness, so the string won't get parsed
return tool != null && tool .isValidForSelection();
}
public void createTool( String name, String group, Tool.Registry tools, Symmetry symmetry )
{
UndoableEdit edit = makeTool( name, group, tools, symmetry );
performAndRecord( edit );
}
private UndoableEdit makeTool( String name, String group, Tool.Registry tools, Symmetry symmetry )
{
UndoableEdit edit = null;
switch (group) {
case "bookmark":
edit = new BookmarkTool( name, mSelection, mRealizedModel, tools );
break;
case "point reflection":
edit = new InversionTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "mirror":
edit = new MirrorTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "translation":
edit = new TranslationTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "linear map":
edit = new LinearMapTool( name, mSelection, mRealizedModel, tools, originPoint, false );
break;
case "rotation":
edit = new RotationTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint, false );
break;
case "axial symmetry":
edit = new RotationTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint, true );
break;
case "scaling":
edit = new ScalingTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
case "scale up":
edit = new ScalingTool( name, tools, getField() .createPower( 1 ), originPoint );
break;
case "scale down":
edit = new ScalingTool( name, tools, getField() .createPower( -1 ), originPoint );
break;
case "tetrahedral":
edit = new SymmetryTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
case "module":
edit = new ModuleTool( name, mSelection, mRealizedModel, tools );
break;
case "plane":
edit = new PlaneSelectionTool( name, mSelection, mField, tools );
break;
case "yellowstretch":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, false, false );
break;
case "yellowsquash":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, false, false );
break;
case "redstretch1":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, true, true );
break;
case "redsquash1":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, true, true );
break;
case "redstretch2":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, true, false );
break;
case "redsquash2":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, true, false );
break;
default:
edit = new SymmetryTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
}
return edit;
}
public Exporter3d getNaiveExporter( String format, Camera view, Colors colors, Lights lights, RenderedModel currentSnapshot )
{
Exporter3d exporter = null;
if ( format.equals( "pov" ) )
exporter = new POVRayExporter( view, colors, lights, currentSnapshot );
else if ( format.equals( "opengl" ) )
exporter = new OpenGLExporter( view, colors, lights, currentSnapshot );
boolean inArticleMode = (renderedModel != currentSnapshot);
if(exporter != null && exporter.needsManifestations() && inArticleMode ) {
throw new IllegalStateException("The " + format + " exporter can only operate on the current model, not article pages.");
}
return exporter;
}
/*
* These exporters fall in two categories: rendering and geometry. The ones that support the currentSnapshot
* (the current article page, or the main model) can do rendering export, and can work with just a rendered
* model (a snapshot), which has lost its attached Manifestation objects.
*
* The ones that require mRenderedModel need access to the RealizedModel objects hanging from it (the
* Manifestations). These are the geometry exporters. They can be aware of the structure of field elements,
* as well as the orbits and zones.
*
* POV-Ray is a bit of a special case, but only because the .pov language supports coordinate values as expressions,
* and supports enough modeling that the different strut shapes can be defined, and so on.
* OpenGL and WebGL (Web3d/json) could as well, since I can control how the data is stored and rendered.
*
* The POV-Ray export reuses shapes, etc. just as vZome does, so really works just with the RenderedManifestations
* (except when the Manifestation is available for structured coordinate expressions). Again, any rendering exporter
* could apply the same reuse tricks, working just with RenderedManifestations, so the current limitations to
* mRenderedModel for many of these is spurious.
*
* The base Exporter3d class now has a boolean needsManifestations() method which subclasses should override
* if they don't rely on Manifestations and therefore can operate on article pages.
*/
// TODO move all the parameters inside this object!
public Exporter3d getStructuredExporter( String format, Camera view, Colors colors, Lights lights, RenderedModel mRenderedModel )
{
if ( format.equals( "partgeom" ) )
return new PartGeometryExporter( view, colors, lights, mRenderedModel, mSelection );
else
return null;
}
public LessonModel getLesson()
{
return lesson;
}
@Override
public void recordSnapshot( int id )
{
RenderedModel snapshot = ( renderedModel == null )? null : renderedModel .snapshot();
if ( thumbnailLogger .isLoggable( Level.FINER ) )
thumbnailLogger .finer( "recordSnapshot: " + id );
numSnapshots = Math .max( numSnapshots, id + 1 );
if ( id >= snapshots.length )
{
int newLength = Math .max( 2 * snapshots .length, numSnapshots );
snapshots = Arrays .copyOf( snapshots, newLength );
}
snapshots[ id ] = snapshot;
}
@Override
public void actOnSnapshot( int id, SnapshotAction action )
{
RenderedModel snapshot = snapshots[ id ];
action .actOnSnapshot( snapshot );
}
public void addSnapshotPage( Camera view )
{
int id = numSnapshots;
this .performAndRecord( new Snapshot( id, this ) );
lesson .newSnapshotPage( id, view );
}
public RenderedModel getRenderedModel()
{
return this .renderedModel;
}
public Camera getViewModel()
{
return this .defaultView;
}
public void generatePolytope( String group, String renderGroup, int index, int edgesToRender, AlgebraicVector quaternion, AlgebraicNumber[] edgeScales )
{
UndoableEdit edit = new Polytope4d( mSelection, mRealizedModel, quaternion, index, group, edgesToRender, edgeScales, renderGroup );
this .performAndRecord( edit );
}
public void generatePolytope( String group, String renderGroup, int index, int edgesToRender, AlgebraicNumber[] edgeScales )
{
UndoableEdit edit = new Polytope4d( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(), index, group, edgesToRender, edgeScales, renderGroup );
this .performAndRecord( edit );
}
public Segment getSelectedSegment()
{
return (Segment) mEditorModel .getSelectedConstruction( Segment.class );
}
public Segment getSymmetryAxis()
{
return mEditorModel .getSymmetrySegment();
}
public Segment getPlaneAxis( Polygon panel )
{
AlgebraicVector[] vertices = panel.getVertices();
FreePoint p0 = new FreePoint( vertices[ 0 ] );
FreePoint p1 = new FreePoint( vertices[ 1 ] );
FreePoint p2 = new FreePoint( vertices[ 2 ] );
Segment s1 = new SegmentJoiningPoints( p0, p1 );
Segment s2 = new SegmentJoiningPoints( p1, p2 );
return new SegmentCrossProduct( s1, s2 );
}
public RealizedModel getRealizedModel()
{
return this .mRealizedModel;
}
public Iterable<Tool> getTools()
{
return this .tools .values();
}
public SymmetrySystem getSymmetrySystem()
{
return this .symmetrySystem;
}
public SymmetrySystem getSymmetrySystem( String name )
{
return this .symmetrySystems .get( name );
}
public void setSymmetrySystem( String name )
{
this .symmetrySystem = this .symmetrySystems .get( name );
}
} |
package controller;
import handler.ConfigHandler;
import handler.StatisticsHandler;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import misc.Job;
import misc.Logger;
import model.JobSetupDialogModel;
import org.apache.commons.lang3.exception.ExceptionUtils;
import view.JobSetupDialogView;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
public class JobSetupDialogController extends Stage implements EventHandler {
// todo JavaDoc
private final JobSetupDialogView view;
// todo JavaDoc
private final JobSetupDialogModel model;
/** The object that handles settings for encoding, decoding, compression, and a number of other features. */
private final ConfigHandler configHandler;
// todo JavaDoc
private final StatisticsHandler statisticsHandler;
/**
* Construct a new job setup dialog controller.
* @param primaryStage todo JavaDoc
* @param configHandler The object that handles settings for encoding, decoding, compression, and a number of other features.
* @param statisticsHandler todo JavaDoc
*/
public JobSetupDialogController(final Stage primaryStage, final ConfigHandler configHandler, final StatisticsHandler statisticsHandler) {
this.configHandler = configHandler;
this.statisticsHandler = statisticsHandler;
view = new JobSetupDialogView(primaryStage, this, configHandler);
model = new JobSetupDialogModel();
// Setup Stage:
final Scene scene = new Scene(view);
scene.getStylesheets().add("global.css");
scene.getRoot().getStyleClass().add("main-root");
this.initModality(Modality.APPLICATION_MODAL);
this.setTitle("Job Creator");
this.getIcons().add(new Image("icon.png"));
this.setScene(scene);
}
@Override
public void handle(Event event) {
final Object source = event.getSource();
// The button to open the handler selection dialog.
if(source.equals(view.getButton_addFiles())) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Job File Selection");
final List<File> selectedFiles = fileChooser.showOpenMultipleDialog(this);
if(selectedFiles != null) {
model.getList_files().addAll(selectedFiles);
// Add all of the files to the list:
for(final File f : selectedFiles) {
view.getListView_selectedFiles().getItems().add(f.getAbsolutePath());
}
}
updateEstimatedDurationLabel();
}
// The button to remove all files that are currently selected on the scrollpane_selectedFiles.
if(source.equals(view.getButton_removeSelectedFiles())) {
// If a copy of the observable list is not made, then errors can occur.
// These errors are caused by the ObservableList updating as items are being removed.
// This causes items that shouldn't be removed to be removed.
final ObservableList<String> copy = FXCollections.observableArrayList(view.getListView_selectedFiles().getSelectionModel().getSelectedItems());
view.getListView_selectedFiles().getItems().removeAll(copy);
// Remove Jobs from the Model while updating
// the IDs of all Jobs.
final Iterator<File> it = model.getList_files().iterator();
while(it.hasNext()) {
final File f = it.next();
if(view.getListView_selectedFiles().getItems().contains(f.getAbsolutePath()) == false) {
it.remove();
}
}
view.getListView_selectedFiles().getSelectionModel().clearSelection();
updateEstimatedDurationLabel();
}
// The button to remove all files from the list.
if(source.equals(view.getButton_clearAllFiles())) {
model.getList_files().clear();
view.getListView_selectedFiles().getItems().clear();
view.getListView_selectedFiles().getSelectionModel().clearSelection();
updateEstimatedDurationLabel();
}
// The radio button that says that each of the currently selected files should be archived as a single archive before encoding.
if(source.equals(view.getRadioButton_singleArchive_yes())) {
// Ensure that both the single and individual archive options aren't
// selected at the same time.
view.getRadioButton_individualArchives_no().setSelected(true);
}
// The radio button that says that each handler should be archived individually before encoding each of them individually.
if(source.equals(view.getRadioButton_individualArchives_yes())) {
// Ensure that both the single and individual archive options aren't
// selected at the same time.
view.getRadioButton_singleArchive_no().setSelected(true);
}
// The button to select the folder to output the archive to if the "Yes" radio button is selected.
if(source.equals(view.getButton_selectOutputDirectory())) {
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setDragEnabled(false);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("Directory Slection");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setApproveButtonText("Accept");
fileChooser.setApproveButtonToolTipText("Accept the selected directory.");
try {
int returnVal = fileChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
view.getTextField_outputDirectory().setText(fileChooser.getSelectedFile().getPath() + "/");
}
} catch(final HeadlessException e) {
Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_WARNING);
}
}
// The button to close the JobCreationDialog without creating a Job.
if(source.equals(view.getButton_accept())) {
if(areSettingsCorrect() == false) {
final String name = view.getField_jobName().getText();
final String description = view.getTextArea_jobDescription().getText();
final String outputDirectory = view.getTextField_outputDirectory().getText();
final List<File> files = model.getList_files();
final boolean isEncodeJob = view.getIsEncodeJob();
final boolean combineAllFilesIntoSingleArchive = view.getRadioButton_singleArchive_yes().isSelected();
final boolean combineIntoIndividualArchives = view.getRadioButton_individualArchives_yes().isSelected();
final Job job = new Job(name, description, outputDirectory, files, isEncodeJob, combineAllFilesIntoSingleArchive, combineIntoIndividualArchives);
model.setJob(job);
this.close();
}
}
// The button to close the JobCreationDialog while creating a Job.
if(source.equals(view.getButton_cancel())) {
model.setJob(null);
this.close();
}
}
// todo Javadoc
public boolean areSettingsCorrect() {
boolean wasErrorFound = false;
// Reset the error states and tooltips of any components
// that can have an error state set.
// Set the password fields back to their normal look:
view.getField_jobName().getStylesheets().remove("field_error.css");
view.getField_jobName().getStylesheets().add("global.css");
view.getField_jobName().setTooltip(null);
view.getTextField_outputDirectory().getStylesheets().remove("field_error.css");
view.getTextField_outputDirectory().getStylesheets().add("global.css");
view.getTextField_outputDirectory().setTooltip(new Tooltip("The directory in which to place the en/decoded file(s)."));
// Check to see that the Job has been given a name.
if(view.getField_jobName().getText().isEmpty()) {
view.getField_jobName().getStylesheets().remove("global.css");
view.getField_jobName().getStylesheets().add("field_error.css");
final String errorText = "Error - You need to enter a name for the Job.";
view.getField_jobName().setTooltip(new Tooltip(errorText));
wasErrorFound = true;
}
// Check to see that the output directory exists:
if(view.getTextField_outputDirectory().getText().isEmpty() || Files.exists(Paths.get(view.getTextField_outputDirectory().getText())) == false) {
view.getTextField_outputDirectory().getStylesheets().remove("global.css");
view.getTextField_outputDirectory().getStylesheets().add("field_error.css");
final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip();
final String errorText = "Error - You need to set an output directory for the Job.";
view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText));
wasErrorFound = true;
}
if(Files.isDirectory(Paths.get(view.getTextField_outputDirectory().getText())) == false) {
view.getTextField_outputDirectory().getStylesheets().remove("global.css");
view.getTextField_outputDirectory().getStylesheets().add("field_error.css");
final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip();
final String errorText = "Error - You need to set a valid output directory for the Job.";
view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText));
wasErrorFound = true;
}
return wasErrorFound;
}
/**
* Either updates the estimated duration label with the estimated duration, in minutes,
* that the Job will take, or "unknown" if there is insufficent data to estimate.
*/
public void updateEstimatedDurationLabel() {
// Determine if the time can be estimated.
boolean canTimeBeEstimated = true;
canTimeBeEstimated &= model.getList_files().size() > 0;
canTimeBeEstimated &= (view.getIsEncodeJob() ? statisticsHandler.getBytesEncodedPerMinute() > 0 : statisticsHandler.getBytesDecodedPerMinute() > 0);
// If the time can be estimated, then do so, else show unknown.
if(canTimeBeEstimated) {
view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - " + statisticsHandler.estimateProcessingDuration(view.getIsEncodeJob(), model.getList_files()) + " Minutes");
} else {
view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - Unknown");
}
}
////////////////////////////////////////////////////////// Getters
// todo JavaDoc
public JobSetupDialogView getView() {
return view;
}
// todo JavaDoc
public JobSetupDialogModel getModel() {
return model;
}
} |
package de.ddb.pdc.metadata;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
/**
* Implementation of the {@link MetaFetcher} interface.
*/
public class MetaFetcherImpl implements MetaFetcher {
private static final String URL =
"https:
private static final String APIURL =
"https://api.deutsche-digitale-bibliothek.de";
private static final String SEARCH = "/search?";
private static final String AUTH = "oauth_consumer_key=";
private static final String SORTROWS = "&sort=RELEVANCE&rows=";
private static final String QUERY = "&query=";
private static final String ITEM = "/items/";
private static final String AIP = "/aip?";
private RestTemplate restTemplate;
private String authKey;
/**
* Creates a new MetaFetcherImpl.
*
* @param restTemplate RestTemplate to use for issuing requests
* @param authKey authentication Key for the DDB API
*/
public MetaFetcherImpl(RestTemplate restTemplate, String authKey) {
this.restTemplate = restTemplate;
this.authKey = authKey;
}
/**
* {@inheritDoc}
*/
public DDBItem[] searchForItems(String query, int maxCount)
throws RestClientException {
String modifiedQuery = query.replace(" ", "+");
String url = APIURL + SEARCH + AUTH + authKey + SORTROWS + maxCount + QUERY
+ modifiedQuery;
ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class);
return getDDBItems(roj);
}
/**
* {@inheritDoc}
*/
public void fetchMetadata(DDBItem ddbItem) throws RestClientException {
String url = APIURL + ITEM + ddbItem.getId() + AIP + AUTH + authKey;
ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class);
fillDDBItemMetadataFromDDB(ddbItem, roj);
}
/**
* @param ddbItem filled with information
* @param roj store information of the ddb aip request
*/
private void fillDDBItemMetadataFromDDB(DDBItem ddbItem, ResultsOfJSON roj) {
RDFItem rdfitem = roj.getEdm().getRdf();
String publishedYear = (String) rdfitem.getProvidedCHO().get("issued");
int year = 8000;
try {
if (publishedYear != null) {
year = Integer.parseInt(publishedYear.split(",")[0]);
}
} catch (NumberFormatException e) {
year = 8000;
}
ddbItem.setPublishedYear(year);
// some Agent input are represented at ArrayList or LinkedHashMap
if (rdfitem.getAgent() instanceof ArrayList<?>) {
ArrayList<LinkedHashMap> alAgent = (ArrayList) rdfitem.getAgent();
for (int idx = 0; idx < alAgent.size(); idx++) {
String about = (String) alAgent.get(idx).get("@about");
if (about.startsWith("http")) {
String authorid = alAgent.get(idx).get("@about").toString()
.replace("http://d-nb.info/gnd/", "");
Author author = new Author(authorid);
ddbItem.setAuthor(author);
}
}
}
// till now no testdata where author in LinkedHashMap
if (rdfitem.getAgent() instanceof LinkedHashMap<?,?>) {
//LinkedHashMap lhmAgent = (LinkedHashMap) rdf.get("Agent");
}
ddbItem.setInstitute((String) rdfitem.getAggregation().get("provider"));
}
/**
* @param roj results of the ddb search query
* @return a list of ddbitems from roj
*/
private DDBItem[] getDDBItems(ResultsOfJSON roj) {
int maxResults = roj.getResults().size();
DDBItem[] ddbItems = new DDBItem[maxResults];
int idx = 0;
for (SearchResultItem rsi : roj.getResults()) {
DDBItem ddbItem = new DDBItem(rsi.getId());
ddbItem.setTitle(deleteMatchTags(rsi.getTitle()));
ddbItem.setSubtitle(deleteMatchTags(rsi.getSubtitle()));
ddbItem.setImageUrl(URL + rsi.getThumbnail());
ddbItem.setCategory(rsi.getCategory());
ddbItem.setMedia(rsi.getMedia());
ddbItem.setType(rsi.getType());
ddbItems[idx] = ddbItem;
idx++;
}
return ddbItems;
}
/**
* Deletes the "<match>...</match>" markers in metadata values of search
* result items. These are added by the DDB API to simplify highlighting
* of matching substrings, but we don't need or want them.
*/
public static String deleteMatchTags(String string) {
return string.replace("<match>", "").replace("</match>", "");
}
} |
package org.lla_private.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Hilfsobjekt, Macht aus einem String ein JSON Objekt
*
*/
public class ObjectMapperService implements IObjectMapperService {
private static Logger LOGGER = LoggerFactory.getLogger(ObjectMapperService.class);
private final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public String createJsonString(final Object list) {
String jsonString = "";
try {
jsonString = OBJECT_MAPPER.writer().writeValueAsString(list);
return jsonString;
}
catch (final JsonProcessingException e) {
LOGGER.warn("Could not serialize bean into JSON string", e);
}
return "";
}
} |
package edu.clemson.cs.r2jt;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import edu.clemson.cs.r2jt.compilereport.CompileReport;
import edu.clemson.cs.r2jt.data.MetaFile;
import edu.clemson.cs.r2jt.data.ModuleKind;
import edu.clemson.cs.r2jt.proving.Prover;
import edu.clemson.cs.r2jt.utilities.Flag;
import edu.clemson.cs.r2jt.utilities.FlagDependencies;
// import webui.utils.WebSocketWriter;
public class ResolveCompiler {
private static final String FLAG_SECTION_NAME = "Output";
private static final String FLAG_DESC_WEB =
"Change the output to be more web-friendly for the Web Interface.";
private static final String FLAG_DESC_ERRORS_ON_STD_OUT =
"Change the output to be more web-friendly for the Web Interface.";
private static final String FLAG_DESC_NO_DEBUG =
"Remove debugging statements from the compiler output.";
private static final String FLAG_DESC_XML_OUT =
"Changes the compiler output files to XML";
private static final String FLAG_DESC_EXPORT_AST =
"exports the AST for the target file as a .dot file that can be viewed in Graphviz";
/**
* <p>The main web interface flag. Tells the compiler to modify
* some of the output to be more user-friendly for the web.</p>
*/
public static final Flag FLAG_WEB =
new Flag(FLAG_SECTION_NAME, "webinterface", FLAG_DESC_WEB,
Flag.Type.HIDDEN);
/**
* <p>Tells the compiler to send error messages to std_out instead
* of std_err.</p>
*/
public static final Flag FLAG_ERRORS_ON_STD_OUT =
new Flag(FLAG_SECTION_NAME, "errorsOnStdOut",
FLAG_DESC_ERRORS_ON_STD_OUT, Flag.Type.HIDDEN);
/**
* <p>Tells the compiler to remove debugging messages from the compiler
* output.</p>
*/
public static final Flag FLAG_NO_DEBUG =
new Flag(FLAG_SECTION_NAME, "nodebug", FLAG_DESC_NO_DEBUG);
/**
* <p>Tells the compiler to remove debugging messages from the compiler
* output.</p>
*/
public static final Flag FLAG_XML_OUT =
new Flag(FLAG_SECTION_NAME, "XMLout", FLAG_DESC_XML_OUT);
/**
* <p>The main web interface flag. Tells the compiler to modify
* some of the output to be more user-friendly for the web.</p>
*/
public static final Flag FLAG_EXPORT_AST =
new Flag(FLAG_SECTION_NAME, "exportAST", FLAG_DESC_EXPORT_AST,
Flag.Type.HIDDEN);
//private String myTargetSource = null;
//private String myTargetFileName = null;
private HashMap<String, MetaFile> myUserFileMap;
private CompileReport myCompileReport;
private MetaFile myInputFile;
//private WebSocketWriter myWsWriter = null;
public ResolveCompiler(String[] args, MetaFile inputFile,
String customFacilityName, HashMap<String, MetaFile> userFileMap) {
myCompileReport = new CompileReport();
myCompileReport.setFacilityName(customFacilityName);
myInputFile = inputFile;
myUserFileMap = userFileMap;
//myTargetFileName = fileName;
//System.out.println(fileName);
//Main.main(args);
}
public ResolveCompiler(String[] args, MetaFile inputFile,
HashMap<String, MetaFile> userFileMap) {
myCompileReport = new CompileReport();
myCompileReport.setFacilityName(inputFile.getMyFileName());
//myTargetFileName = fileArray[0];
//myTargetSource = fileArray[3];
myInputFile = inputFile;
myUserFileMap = userFileMap;
//System.out.println(fileName);
//Main.main(args);
}
public ResolveCompiler(String[] args) {
myCompileReport = new CompileReport();
//myCompileReport.setFacilityName(inputFile.getMyFileName());
//myTargetFileName = fileArray[0];
//myTargetSource = fileArray[3];
myUserFileMap = new HashMap<String, MetaFile>();
//System.out.println(fileName);
//Main.main(args);
}
public ResolveCompiler(String[] args, HashMap<String, MetaFile> userFileMap) {
myCompileReport = new CompileReport();
//myCompileReport.setFacilityName(inputFile.getMyFileName());
//myTargetFileName = fileArray[0];
//myTargetSource = fileArray[3];
//myUserFileMap = userFileMap;
myUserFileMap = new HashMap<String, MetaFile>();
//System.out.println(fileName);
//Main.main(args);
}
public void createMeta(String fileName, String assocConcept, String pkg,
String fileSource, String modKind) {
//String fileName, String assocConcept, String pkg, String fileSource, ModuleKind kind
ModuleKind kind = null;
if (modKind.equals("CONCEPT"))
kind = ModuleKind.CONCEPT;
else if (modKind.equals("ENHANCEMENT"))
kind = ModuleKind.ENHANCEMENT;
else if (modKind.equals("FACILITY"))
kind = ModuleKind.FACILITY;
else if (modKind.equals("REALIZATION"))
kind = ModuleKind.REALIZATION;
else if (modKind.equals("THEORY"))
kind = ModuleKind.THEORY;
else
kind = ModuleKind.UNDEFINED;
myInputFile =
new MetaFile(fileName, assocConcept, pkg, fileSource, kind);
String key = pkg + "." + fileName;
myUserFileMap.put(key, myInputFile);
}
public void compile(String[] args) {
//System.out.println("using testing compiler");
Main.runMain(args, myCompileReport, myInputFile, myUserFileMap);
}
/*public void wsCompile(String[] args, WebSocketWriter writer){
myWsWriter = writer;
//myCompileReport.setWsWriter(writer);
Main.runMain(args, myCompileReport, myInputFile, myUserFileMap);
}*/
/*public void setFacilityName(String facName){
myReport.setFacilityName(facName);
}*/
public CompileReport getReport() {
return myCompileReport;
}
public void resetReport() {
myCompileReport.resetReport();
}
public boolean proved() {
//boolean proved = Prover.allProved;
boolean proved = myCompileReport.proveSuccess();
//Prover.allProved = false;
return proved;
}
public boolean archived() {
//CompileReport myReport = CompileReport.getInstance();
boolean archived = myCompileReport.jarSuccess();
return archived;
}
public boolean hasError() {
//CompileReport myReport = CompileReport.getInstance();
boolean error = myCompileReport.hasError();
return error;
}
public static String webEncode(String s) {
String encoded = null;
try {
encoded = URLEncoder.encode(s.replaceAll(" ", "%20"), "UTF-8");
}
catch (UnsupportedEncodingException ex) {
}
return encoded;
}
public static final void setUpFlags() {
FlagDependencies.addRequires(FLAG_ERRORS_ON_STD_OUT, FLAG_WEB);
FlagDependencies.addImplies(FLAG_WEB, FLAG_ERRORS_ON_STD_OUT);
FlagDependencies.addImplies(FLAG_WEB, FLAG_NO_DEBUG);
FlagDependencies.addImplies(FLAG_WEB, FLAG_XML_OUT);
FlagDependencies.addImplies(FLAG_WEB, Prover.FLAG_NOGUI);
}
} |
package pluginlib;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.jar.JarFile;
public class Plugin {
private File file;
private String mainClass;
private Class<?> clazz;
private Object instance;
/**
* Tries to load main class from plugin.txt if found
* @param file
* @throws MainClassNotFoundException
* @throws IOException
*/
public Plugin(File file) throws Exception, MainClassNotFoundException, IOException {
this(file, JarUtils.getMainClassFromInfo(new JarFile(file)));
}
/**
* Adds file to classpath
* @param file
* @param mainClass
* @throws Exception
*/
public Plugin(File file, String mainClass) throws Exception {
this.file = file;
Classpath.addToClassPath(file);
}
public void load() throws Exception {
load(null, null);
}
public void load(Class<?>[] classes, Object[] arguments) throws Exception {
clazz = Class.forName(mainClass, true, getClass().getClassLoader());
Constructor<?> ctor = clazz.getDeclaredConstructor(classes);
ctor.setAccessible(true);
instance = ctor.newInstance(arguments);
}
/**
* Invokes method without arguments
* @param m
* @return
* @throws Exception
*/
public Object invoke(String m) throws Exception {
return invoke(m, null, null);
}
/**
* Invokes method with arguments
* @param m
* @param classes argument classes
* @param arguments argument objects
* @return
* @throws Exception
*/
public Object invoke(String m, Class<?>[] classes, Object[] arguments) throws Exception {
Method method = clazz.getMethod(m, classes);
return method.invoke(instance, arguments);
}
public String getMainClass() {
return mainClass;
}
public void setMainClass(String mainClass) {
this.mainClass = mainClass;
}
public File getFile() {
return file;
}
} |
package edu.uib.info310.search;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.transform.TransformerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP;
import edu.uib.info310.exception.ArtistNotFoundException;
import edu.uib.info310.exception.MasterNotFoundException;
import edu.uib.info310.model.Artist;
import edu.uib.info310.model.Event;
import edu.uib.info310.model.Record;
import edu.uib.info310.model.Track;
import edu.uib.info310.model.factory.ModelFactory;
import edu.uib.info310.search.builder.OntologyBuilder;
import edu.uib.info310.search.builder.ontology.DiscogOntology;
@Component
public class SearcherImpl implements Searcher {
private static final Logger LOGGER = LoggerFactory
.getLogger(SearcherImpl.class);
@Autowired
private OntologyBuilder builder;
@Autowired
private ModelFactory modelFactory;
@Autowired
private DiscogOntology discog;
private Model model;
private Artist artist;
private Record record;
public Artist searchArtist(String search_string)
throws ArtistNotFoundException {
this.artist = modelFactory.createArtist();
this.model = builder.createArtistOntology(search_string);
LOGGER.debug("Size of infered model: " + model.size());
setArtistIdAndName();
setSimilarArtist();
setArtistEvents();
setArtistDiscography();
setArtistInfo();
setArtistOntology();
return this.artist;
}
private void setArtistOntology() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
model.write(out);
try {
this.artist.setModel(out.toString("UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Failed to write to string with UTF-8 encoding: " + e);
}
}
public List<Record> searchRecords(String albumName) {
List<Record> records = new LinkedList<Record>();
String safe_search = "";
try {
safe_search = URLEncoder.encode(albumName, "UTF-8");
} catch (UnsupportedEncodingException e) {/* ignore */
}
String prefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "PREFIX dc: <http://purl.org/dc/elements/1.1/>"
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
+ "PREFIX mo: <http://purl.org/ontology/mo/>"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema
+ "PREFIX dc: <http://purl.org/dc/terms/>"
+ "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema
String albums = "SELECT ?artistName ?albumName ?year "
+ " WHERE { ?record dc:title \"" + safe_search + "\" ;"
+ "rdf:type mo:Record ;" + "foaf:maker ?artist ;"
+ "mo:discogs ?discogs ;" + "dc:issued ?year ;"
+ "dc:title ?albumName." + "?artist foaf:name ?artistName}"
+ "ORDER BY ?year";
Query query = QueryFactory.create(prefix + albums);
QueryEngineHTTP queryExecution = QueryExecutionFactory
.createServiceRequest(
"http://api.kasabi.com/dataset/discogs/apis/sparql",
query);
queryExecution.addParam("apikey",
"fe29b8c58180640f6db16b9cd3bce37c872c2036");
ResultSet recordResults = queryExecution.execSelect();
while (recordResults.hasNext()) {
List<Artist> artists = new LinkedList<Artist>();
Record record = modelFactory.createRecord();
QuerySolution querySol = recordResults.next();
record.setName(querySol.get("albumName").toString());
Artist artist = modelFactory.createArtist();
artist.setName(querySol.get("artistName").toString());
artists.add(artist);
record.setArtist(artists);
record.setYear(querySol.get("year").toString().substring(0, 4));
if (!records.contains(record)) {
records.add(record);
}
}
return records;
}
private void setArtistIdAndName() {
String getIdStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns
QueryExecution execution = QueryExecutionFactory
.create(getIdStr, model);
ResultSet similarResults = execution.execSelect();
if (similarResults.hasNext()) {
QuerySolution solution = similarResults.next();
this.artist.setId(solution.get("id").toString());
this.artist.setName(solution.get("name").toString());
}
LOGGER.debug("Artist id set to: " + this.artist.getId()
+ ", Artist name set to: " + this.artist.getName());
}
private void setArtistDiscography() {
List<Record> discog = new LinkedList<Record>();
Map<String, Record> uniqueRecord = new HashMap<String, Record>();
String getDiscographyStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
+ "PREFIX mo: <http://purl.org/ontology/mo/> "
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema
+ "PREFIX dc: <http://purl.org/dc/terms/> "
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "SELECT DISTINCT "
+ " ?artistId ?albumId ?release ?title ?image ?year ?labelId ?labelName ?track ?artist "
+ " WHERE { " + "?artistId foaf:made ?albumId. "
+ "?albumId dc:title ?title."
+ "OPTIONAL {?albumId mo:publisher ?labelId. } "
+ "OPTIONAL {?albumId dc:issued ?year. }"
+ "OPTIONAL {?albumId foaf:depiction ?image. }" + "}";
LOGGER.debug("Search for albums for artist with name: "
+ this.artist.getName() + ", with query:" + getDiscographyStr);
QueryExecution execution = QueryExecutionFactory.create(
getDiscographyStr, model);
ResultSet albums = execution.execSelect();
LOGGER.debug("Found records? " + albums.hasNext());
while (albums.hasNext()) {
Record recordResult = modelFactory.createRecord();
QuerySolution queryAlbum = albums.next();
recordResult.setId(queryAlbum.get("albumId").toString());
recordResult.setName(queryAlbum.get("title").toString());
if (queryAlbum.get("image") != null) {
recordResult.setImage(queryAlbum.get("image").toString());
}
if (queryAlbum.get("year") != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyy",
Locale.US);
recordResult.setYear(format.format(makeDate(queryAlbum.get(
"year").toString())));
}
if (recordResult.getImage() != null) {
uniqueRecord.put(recordResult.getName(), recordResult);
}
}
for (Record record : uniqueRecord.values()) {
discog.add(record);
}
this.artist.setDiscography(discog);
LOGGER.debug("Found " + artist.getDiscography().size()
+ " artist records");
}
private void setSimilarArtist() {
List<Artist> similar = new LinkedList<Artist>();
String similarStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "PREFIX mo:<http://purl.org/ontology/mo/> "
+ "PREFIX foaf:<http://xmlns.com/foaf/0.1/> "
+ "SELECT ?name ?id ?image "
+ " WHERE { <"
+ this.artist.getId()
+ "> mo:similar-to ?id . "
+ "?id foaf:name ?name; " + " mo:image ?image } ";
QueryExecution execution = QueryExecutionFactory.create(similarStr,
model);
ResultSet similarResults = execution.execSelect();
while (similarResults.hasNext()) {
Artist similarArtist = modelFactory.createArtist();
QuerySolution queryArtist = similarResults.next();
similarArtist.setName(queryArtist.get("name").toString());
similarArtist.setId(queryArtist.get("id").toString());
similarArtist.setImage(queryArtist.get("image").toString());
similar.add(similarArtist);
}
artist.setSimilar(similar);
LOGGER.debug("Found " + this.artist.getSimilar().size()
+ " similar artists");
}
private void setArtistEvents() {
List<Event> events = new LinkedList<Event>();
String getArtistEventsStr = " PREFIX foaf:<http://xmlns.com/foaf/0.1/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "SELECT ?venueId ?venueName ?date ?lng ?lat ?location ?preformance "
+ " WHERE {?preformance foaf:hasAgent <"
+ this.artist.getId()
+ ">; event:place ?venueId; event:time ?date. ?venueId v:organisation-name ?venueName; geo:lat ?lat; geo:long ?lng; v:locality ?location}";
QueryExecution execution = QueryExecutionFactory.create(
getArtistEventsStr, model);
ResultSet eventResults = execution.execSelect();
while (eventResults.hasNext()) {
Event event = modelFactory.createEvent();
QuerySolution queryEvent = eventResults.next();
event.setId(queryEvent.get("venueId").toString());
event.setVenue(queryEvent.get("venueName").toString());
event.setLat(queryEvent.get("lat").toString());
event.setLng(queryEvent.get("lng").toString());
String dateString = queryEvent.get("date").toString();
Date date = new Date();
SimpleDateFormat stf = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss", Locale.US);
try {
date = stf.parse(dateString);
} catch (ParseException e) {
LOGGER.error("Couldnt parse date");
}
event.setDate(date);
event.setLocation(queryEvent.get("location").toString());
event.setWebsite(queryEvent.get("preformance").toString());
events.add(event);
}
this.artist.setEvents(events);
LOGGER.debug("Found " + artist.getEvents().size() + " artist events");
}
private void setArtistInfo() {
String id = "<" + artist.getId() + ">";
LOGGER.debug("Artisturi " + artist.getName());
String getArtistInfoStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
+ "PREFIX mo: <http://purl.org/ontology/mo/> "
+ "PREFIX dbpedia: <http://dbpedia.org/property/> "
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
+ "PREFIX owl: <http://www.w3.org/2002/07/owl
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
+ "PREFIX dbont: <http://dbpedia.org/ontology/> "
+ "SELECT DISTINCT * WHERE {" + "OPTIONAL { "
+ id
+ " mo:fanpage ?sFanpage. BIND(str(?sFanpage) AS ?fanpage)} "
+ "OPTIONAL { "
+ id
+ " mo:imdb ?imdb. }"
+ "OPTIONAL { "
+ id
+ " foaf:name ?name. }"
+ "OPTIONAL { "
+ id
+ " mo:myspace ?myspace. } "
+ "OPTIONAL { "
+ id
+ " mo:homepage ?homepage. } "
+ "OPTIONAL { "
+ id
+ " rdfs:comment ?sShortDesc. BIND(str(?sShortDesc) AS ?shortDesc)} "
+ "OPTIONAL { "
+ id
+ " mo:image ?image}"
+ "OPTIONAL { "
+ id
+ " mo:biography ?sBio. BIND(str(?sBio) AS ?bio) } "
+ "OPTIONAL { "
+ id
+ " dbont:birthname ?birthname} "
+ "OPTIONAL { "
+ id
+ " dbont:hometown ?hometown. } "
+ "OPTIONAL { "
+ id
+ " mo:origin ?sOrigin. BIND(str(?sOrigin) AS ?origin)} "
+ "OPTIONAL { "
+ id
+ " mo:activity_start ?start. } "
+ "OPTIONAL { "
+ id
+ " mo:activity_end ?end. } "
+ "OPTIONAL { "
+ id
+ " dbont:birthDate ?birthdate. } "
+ "OPTIONAL { "
+ id
+ " dbont:deathDate ?deathdate. } "
+ "OPTIONAL { "
+ id
+ " mo:wikipedia ?wikipedia. } "
+ "OPTIONAL { "
+ id
+ " foaf:page ?bbcpage. }"
+ "OPTIONAL { "
+ id
+ " dbont:bandMember ?memberOf. ?memberOf rdfs:label ?sName1. BIND(str(?sName1) AS ?name1)}"
+ "OPTIONAL { "
+ id
+ " dbont:formerBandMember ?pastMemberOf. ?pastMemberOf rdfs:label ?sName2. BIND(str(?sName2) AS ?name2) }"
+ "OPTIONAL { "
+ id
+ " dbpedia:currentMembers ?currentMembers. ?currentMembers rdfs:label ?sName3. BIND(str(?sName3) AS ?name3) }"
+ "OPTIONAL { "
+ id
+ " dbpedia:pastMembers ?pastMembers. ?pastMembers rdfs:label ?sName4. BIND(str(?sName4) AS ?name4) }}";
QueryExecution ex = QueryExecutionFactory.create(getArtistInfoStr,
model);
ResultSet results = ex.execSelect();
HashMap<String, Object> metaMap = new HashMap<String, Object>();
List<String> fanpages = new LinkedList<String>();
List<String> bands = new LinkedList<String>();
List<String> formerBands = new LinkedList<String>();
List<String> currentMembers = new LinkedList<String>();
List<String> pastMembers = new LinkedList<String>();
while (results.hasNext()) {
QuerySolution query = results.next();
if (query.get("name") != null) {
LOGGER.debug("Artistname " + query.get("name").toString());
}
if (query.get("image") != null) {
artist.setImage(query.get("image").toString());
}
if (query.get("fanpage") != null) {
String fanpage = "<a href=\"" + query.get("fanpage").toString()
+ "\">" + query.get("fanpage").toString() + "</a>";
if (!fanpages.contains(fanpage)) {
fanpages.add(fanpage);
}
}
if (query.get("memberOf") != null) {
String test2 = query.get("name1").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("UnsupportedEncodingException" + e.getLocalizedMessage());
}
String memberOf = "<a href=\"artist?q=" + test + "\">" + test2
+ "</a>";
if (!bands.contains(memberOf)) {
bands.add(memberOf);
}
}
if (query.get("pastMemberOf") != null) {
String test2 = query.get("name2").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("UnsupportedEncodingException" + e.getLocalizedMessage());
}
String pastMemberOf = "<a href=\"artist?q=" + test + "\">"
+ test2 + "</a>";
if (!formerBands.contains(pastMemberOf)) {
formerBands.add(pastMemberOf);
}
}
if (query.get("currentMembers") != null) {
String test2 = query.get("name3").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("UnsupportedEncodingException" + e.getLocalizedMessage());
}
String currentMember = "<a href=\"artist?q=" + test + "\">"
+ test2 + "</a>";
if (!currentMembers.contains(currentMember)) {
currentMembers.add(currentMember);
}
}
if (query.get("pastMembers") != null) {
String test2 = query.get("name4").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("UnsupportedEncodingException" + e.getLocalizedMessage());
}
String pastMember = "<a href=\"artist?q=" + test + "\">"
+ test2 + "</a>";
if (!pastMembers.contains(pastMember)) {
pastMembers.add(pastMember);
}
}
if (query.get("bio") != null) {
artist.setBio(query.get("bio").toString());
}
if (query.get("wikipedia") != null) {
metaMap.put("Wikipedia", ("<a href=\""
+ query.get("wikipedia").toString() + "\">"
+ query.get("wikipedia").toString() + "</a>"));
}
if (query.get("bbcpage") != null) {
metaMap.put("BBC Music",
("<a href=\"" + query.get("bbcpage").toString() + "\">"
+ query.get("bbcpage").toString() + "</a>"));
}
if (query.get("birthdate") != null) {
SimpleDateFormat format = new SimpleDateFormat(
"EEE dd. MMM yyyy", Locale.US);
metaMap.put("Born", (format.format(makeDate(query.get(
"birthdate").toString()))));
}
if (query.get("homepage") != null) {
metaMap.put(
"Homepage",
("<a href=\"" + query.get("homepage").toString()
+ "\">" + query.get("homepage").toString() + "</a>"));
}
if (query.get("imdb") != null) {
metaMap.put("IMDB",
("<a href=\"" + query.get("imdb").toString() + "\">"
+ query.get("imdb").toString() + "</a>"));
}
if (query.get("myspace") != null) {
metaMap.put("MySpace",
("<a href=\"" + query.get("myspace").toString() + "\">"
+ query.get("myspace").toString() + "</a>"));
}
if (query.get("shortDesc") != null) {
artist.setShortDescription(query.get("shortDesc").toString());
}
if (query.get("birthname") != null) {
metaMap.put("Name", (query.get("birthname").toString()));
}
if (query.get("deathdate") != null) {
SimpleDateFormat format = new SimpleDateFormat(
"EEE dd. MMM yyyy", Locale.US);
metaMap.put("Died", (format.format(makeDate(query.get(
"deathdate").toString()))));
}
if (query.get("origin") != null) {
metaMap.put("From", (query.get("origin").toString()));
}
if (query.get("hometown") != null) {
metaMap.put("Living", (query.get("hometown").toString()));
}
if (query.get("start") != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyy",
Locale.US);
String activityStart = format.format(makeDate(query
.get("start").toString()));
if (query.get("end") != null) {
activityStart += "-"
+ format.format(makeDate(query.get("end")
.toString()));
}
metaMap.put("Active", activityStart);
}
}
if (!fanpages.isEmpty()) {
metaMap.put("Fanpages", fanpages.toString());
}
if (!bands.isEmpty()) {
metaMap.put("Bandmembers", bands);
}
if (!formerBands.isEmpty()) {
metaMap.put("Former bandmembers", formerBands);
}
if (!currentMembers.isEmpty()) {
metaMap.put("Member of", currentMembers);
}
if (!pastMembers.isEmpty()) {
metaMap.put("Past member of", pastMembers);
}
artist.setMeta(metaMap);
LOGGER.debug("Found " + artist.getMeta().size() + " fun facts.");
}
public Record searchRecord(String record_name, String artist_name)
throws MasterNotFoundException {
this.record = modelFactory.createRecord();
String release = discog.getRecordReleaseId(record_name, artist_name);
this.model = builder.createRecordOntology(release, record_name,
artist_name);
try {
setRecordInfo(release);
} catch (MasterNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
setRecordOntology();
return record;
}
private void setRecordOntology() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
model.write(out, "RDF/XML");
try {
record.setModel(out.toString("UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Failed to write to string with UTF-8 encoding: " + e);
}
}
public void setRecordInfo(String search_string)
throws MasterNotFoundException, TransformerException {
String release = "<http://api.discogs.com/release/" + search_string
+ ">";
LOGGER.debug("This is the search_string " + release);
String albumStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
+ "PREFIX mo: <http://purl.org/ontology/mo/> "
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
+ "PREFIX dc: <http://purl.org/dc/terms/> "
+ "PREFIX time: <http://www.w3.org/2006/time
+ "SELECT DISTINCT * WHERE { "
+ "?discogs mo:discogs ?id."
+ "OPTIONAL { ?discogs foaf:name ?name.}"
+ "OPTIONAL { ?discogs rdfs:comment ?comment. }"
+ "OPTIONAL { ?discogs foaf:hasAgent ?artist. }"
+ "OPTIONAL { ?discogs mo:genre ?genre. }"
+ "OPTIONAL { ?discogs mo:catalogue_number ?catalogueNumber. }"
+ "OPTIONAL { ?discogs mo:label ?publisher . }"
+ "OPTIONAL { ?discogs mo:image ?image . }"
+ "OPTIONAL { ?discogs dc:issued ?year. }"
+ "OPTIONAL { ?trackid foaf:name ?trackName. }"
+ "OPTIONAL { ?trackid mo:track_number ?trackNumber. }"
+ "OPTIONAL { ?trackid mo:preview ?preview. } "
+ "OPTIONAL { ?trackid time:duration ?trackDuration. }" + "}";
QueryExecution execution = QueryExecutionFactory
.create(albumStr, model);
ResultSet albumResults = execution.execSelect();
HashMap<String, String> genre = new HashMap<String, String>();
HashMap<String, Object> meta = new HashMap<String, Object>();
HashMap<String, Track> tracks = new HashMap<String, Track>();
HashMap<String, Artist> artists = new HashMap<String, Artist>();
while (albumResults.hasNext()) {
QuerySolution queryAlbum = albumResults.next();
// LOGGER.debug(queryAlbum.get("label").toString());
// LOGGER.debug(queryAlbum.get("comment").toString());
// LOGGER.debug(queryAlbum.get("genre").toString());
// LOGGER.debug(queryAlbum.get("year").toString());
record.setId(release);
if (queryAlbum.get("name") != null)
record.setName(queryAlbum.get("name").toString());
if (queryAlbum.get("image") != null)
record.setImage(queryAlbum.get("image").toString());
Track track = modelFactory.createTrack();
if (queryAlbum.get("trackName") != null) {
track.setName(queryAlbum.get("trackName").toString());
}
if (queryAlbum.get("trackNumber") != null)
track.setTrackNr(queryAlbum.get("trackNumber").toString());
if (queryAlbum.get("preview") != null)
track.setPreview(queryAlbum.get("preview").toString());
if (queryAlbum.get("trackDuration") != null) {
track.setLength(queryAlbum.get("trackDuration").toString());
}
if (queryAlbum.get("trackNumber") != null)
tracks.put(queryAlbum.get("trackNumber").toString(), track);
Artist artist = modelFactory.createArtist();
if (queryAlbum.get("artist") != null)
artist.setName(queryAlbum.get("artist").toString());
if (queryAlbum.get("artist") != null)
artists.put(queryAlbum.get("artist").toString(), artist);
if (queryAlbum.get("genre") != null)
genre.put(queryAlbum.get("genre").toString(),
queryAlbum.get("genre").toString());
if (queryAlbum.get("year") != null)
meta.put("Released", queryAlbum.get("year").toString());
if (queryAlbum.get("catalogueNumber").toString() != "none") {
meta.put("Catalogue Number", queryAlbum.get("catalogueNumber")
.toString());
}
if (queryAlbum.get("publisher") != null)
meta.put("Label", queryAlbum.get("publisher").toString());
if (queryAlbum.get("year") != null)
record.setYear(queryAlbum.get("year").toString());
if (queryAlbum.get("comment") != null)
record.setDescription(queryAlbum.get("comment").toString());
}
record.setGenres(genre);
record.setTracks(new LinkedList<Track>(tracks.values()));
record.setArtist(new LinkedList<Artist>(artists.values()));
record.setMeta(meta);
}
private Date makeDate(String dateString) {
Date date = new Date();
SimpleDateFormat stf = new SimpleDateFormat("yyyy-mm-dd", Locale.US);
try {
date = stf.parse(dateString);
} catch (ParseException e) {
LOGGER.error("Couldnt parse date");
}
return date;
}
} |
package edu.uw.zookeeper.client;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import org.apache.zookeeper.KeeperException;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import edu.uw.zookeeper.common.AbstractActor;
import edu.uw.zookeeper.common.FutureQueue;
import edu.uw.zookeeper.common.Pair;
import edu.uw.zookeeper.common.Promise;
import edu.uw.zookeeper.common.PromiseTask;
import edu.uw.zookeeper.common.SettableFuturePromise;
import edu.uw.zookeeper.data.Operations;
import edu.uw.zookeeper.data.ZNodeLabel;
import edu.uw.zookeeper.protocol.Operation;
import edu.uw.zookeeper.protocol.proto.OpCode;
import edu.uw.zookeeper.protocol.proto.Records;
public class TreeFetcher<T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> implements AsyncFunction<ZNodeLabel.Path, V> {
public static class Parameters {
public static Parameters of(Set<OpCode> operations, boolean watch) {
boolean getData = operations.contains(OpCode.GET_DATA);
boolean getAcl = operations.contains(OpCode.GET_ACL);
boolean getStat = operations.contains(OpCode.EXISTS)
|| operations.contains(OpCode.GET_CHILDREN2);
return new Parameters(watch, getData, getAcl, getStat);
}
protected final boolean watch;
protected final boolean getData;
protected final boolean getAcl;
protected final boolean getStat;
public Parameters(boolean watch, boolean getData, boolean getAcl,
boolean getStat) {
super();
this.watch = watch;
this.getData = getData;
this.getAcl = getAcl;
this.getStat = getStat;
}
public boolean getWatch() {
return watch;
}
public boolean getData() {
return getData;
}
public boolean getAcl() {
return getAcl;
}
public boolean getStat() {
return getStat;
}
}
public static class Builder<T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> {
public static <T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> Builder<T,U,V> create() {
return new Builder<T,U,V>();
}
public static <V> Callable<V> nullResult() {
return new Callable<V>() {
@Override
public V call() throws Exception {
return null;
}
};
}
protected volatile ClientExecutor<? super Records.Request, T, U> client;
protected volatile Executor executor;
protected volatile Set<OpCode> operations;
protected volatile boolean watch;
protected volatile Callable<V> result;
public Builder() {
this(null,
MoreExecutors.sameThreadExecutor(),
EnumSet.noneOf(OpCode.class),
false,
Builder.<V>nullResult());
}
public Builder(
ClientExecutor<? super Records.Request, T, U> client,
Executor executor,
Set<OpCode> operations,
boolean watch,
Callable<V> result) {
this.client = client;
this.watch = watch;
this.operations = Collections.synchronizedSet(operations);
this.result = result;
}
public ClientExecutor<? super Records.Request, T, U> getClient() {
return client;
}
public Builder<T,U,V> setClient(ClientExecutor<? super Records.Request, T, U> client) {
this.client = client;
return this;
}
public Executor getExecutor() {
return executor;
}
public Builder<T,U,V> setExecutor(Executor executor) {
this.executor = executor;
return this;
}
public boolean getStat() {
OpCode[] ops = { OpCode.EXISTS, OpCode.GET_CHILDREN2 };
for (OpCode op: ops) {
if (operations.contains(op)) {
return true;
}
}
return false;
}
public Builder<T,U,V> setStat(boolean getStat) {
OpCode[] ops = { OpCode.EXISTS, OpCode.GET_CHILDREN2 };
if (getStat) {
for (OpCode op: ops) {
operations.add(op);
}
} else {
for (OpCode op: ops) {
operations.remove(op);
}
}
return this;
}
public boolean getData() {
OpCode op = OpCode.GET_DATA;
return operations.contains(op);
}
public Builder<T,U,V> setData(boolean getData) {
OpCode op = OpCode.GET_DATA;
if (getData) {
operations.add(op);
} else {
operations.remove(op);
}
return this;
}
public boolean getAcl() {
OpCode op = OpCode.GET_ACL;
return operations.contains(op);
}
public Builder<T,U,V> setAcl(boolean getAcl) {
OpCode op = OpCode.GET_ACL;
if (getAcl) {
operations.add(op);
} else {
operations.remove(op);
}
return this;
}
public boolean getWatch() {
return watch;
}
public Builder<T,U,V> setWatch(boolean watch) {
this.watch = watch;
return this;
}
public Callable<V> getResult() {
return result;
}
public Builder<T,U,V> setResult(Callable<V> result) {
this.result = result;
return this;
}
public TreeFetcher<T,U,V> build() {
Parameters parameters = Parameters.of(operations, watch);
return TreeFetcher.newInstance(parameters, client, executor, result);
}
}
public static <T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> TreeFetcher<T,U,V> newInstance(
Parameters parameters,
ClientExecutor<? super Records.Request, T, U> client,
Executor executor,
Callable<V> result) {
return new TreeFetcher<T,U,V>(
parameters,
client,
result,
executor);
}
protected final Executor executor;
protected final ClientExecutor<? super Records.Request, T, U> client;
protected final Parameters parameters;
protected final Callable<V> result;
protected TreeFetcher(
Parameters parameters,
ClientExecutor<? super Records.Request, T, U> client,
Callable<V> result,
Executor executor) {
this.parameters = checkNotNull(parameters);
this.client = checkNotNull(client);
this.result = checkNotNull(result);
this.executor = checkNotNull(executor);
}
@Override
public ListenableFuture<V> apply(ZNodeLabel.Path root) {
TreeFetcherActor<T,U,V> actor = newActor();
actor.send(root);
return actor.future();
}
protected TreeFetcherActor<T,U,V> newActor() {
Promise<V> promise = SettableFuturePromise.create();
return TreeFetcherActor.newInstance(parameters, client, result, executor, promise);
}
public static class TreeFetcherActor<T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> extends AbstractActor<ZNodeLabel.Path> {
public static <T extends Operation.ProtocolRequest<Records.Request>, U extends Operation.ProtocolResponse<Records.Response>, V> TreeFetcherActor<T,U,V> newInstance(
Parameters parameters,
ClientExecutor<? super Records.Request, T, U> client,
Callable<V> result,
Executor executor,
Promise<V> promise) {
return new TreeFetcherActor<T,U,V>(
promise,
parameters,
client,
result,
executor);
}
protected final ClientExecutor<? super Records.Request, T, U> client;
protected final FutureQueue<ListenableFuture<Pair<T,U>>> pending;
protected final Task task;
protected final Operations.Requests.GetChildren getChildrenBuilder;
protected final Operations.Requests.GetData getDataBuilder;
protected final Operations.Requests.GetAcl getAclBuilder;
protected TreeFetcherActor(
Promise<V> promise,
Parameters parameters,
ClientExecutor<? super Records.Request, T, U> client,
Callable<V> result,
Executor executor) {
super(executor, AbstractActor.<ZNodeLabel.Path>newQueue(), AbstractActor.newState());
this.client = checkNotNull(client);
this.task = new Task(result, promise);
this.pending = FutureQueue.create();
this.getChildrenBuilder =
Operations.Requests.getChildren().setWatch(parameters.getWatch()).setStat(parameters.getStat());
this.getDataBuilder = parameters.getData()
? Operations.Requests.getData().setWatch(parameters.getWatch())
: null;
this.getAclBuilder = parameters.getAcl()
? Operations.Requests.getAcl()
: null;
}
public ListenableFuture<V> future() {
return task;
}
@Override
protected boolean runEnter() {
if (State.WAITING == state.get()) {
schedule();
return false;
} else {
return super.runEnter();
}
}
@Override
protected void doRun() throws Exception {
doPending();
super.doRun();
}
protected void doPending() throws Exception {
ListenableFuture<Pair<T,U>> future;
while ((future = pending.poll()) != null) {
Pair<T,U> result;
try {
result = future.get();
} catch (Exception e) {
task.setException(e);
stop();
return;
}
applyPendingResult(result);
}
}
protected void applyPendingResult(Pair<T,U> result) throws Exception {
Records.Request request = result.first().getRecord();
Records.Response response = result.second().getRecord();
Operations.maybeError(response, KeeperException.Code.NONODE, request.toString());
if (response instanceof Records.ChildrenGetter) {
ZNodeLabel.Path path = ZNodeLabel.Path.of(((Records.PathGetter) request).getPath());
for (String child: ((Records.ChildrenGetter) response).getChildren()) {
send(ZNodeLabel.Path.of(path, ZNodeLabel.Component.of(child)));
}
}
}
@Override
protected boolean apply(ZNodeLabel.Path input) throws Exception {
ListenableFuture<Pair<T,U>> future =
client.submit(getChildrenBuilder.setPath(input).build());
pending.add(future);
future.addListener(this, executor);
if (getDataBuilder != null) {
future = client.submit(
getDataBuilder.setPath(input).build());
pending.add(future);
future.addListener(this, executor);
}
if (getAclBuilder != null) {
future = client.submit(
getAclBuilder.setPath(input).build());
pending.add(future);
future.addListener(this, executor);
}
return true;
}
@Override
protected void runExit() {
if (state.compareAndSet(State.RUNNING, State.WAITING)) {
if (!mailbox.isEmpty() || !pending.isEmpty()) {
schedule();
} else if (pending.delegate().isEmpty()) {
// We're done!
stop();
}
}
}
@Override
protected void doStop() {
super.doStop();
pending.clear();
task.complete();
}
protected class Task extends PromiseTask<Callable<V>, V> {
protected Task(Callable<V> task, Promise<V> delegate) {
super(task, delegate);
}
protected boolean complete() {
boolean doComplete = ! isDone();
if (doComplete) {
try {
doComplete = set(task().call());
} catch (Throwable t) {
doComplete = setException(t);
}
}
return doComplete;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
boolean canceled = super.cancel(mayInterruptIfRunning);
if (canceled) {
stop();
}
return canceled;
}
}
}
} |
package de.dakror.vloxlands.game.world;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
import de.dakror.vloxlands.Vloxlands;
import de.dakror.vloxlands.game.Game;
import de.dakror.vloxlands.game.entity.Entity;
import de.dakror.vloxlands.game.entity.StaticEntity;
import de.dakror.vloxlands.game.entity.creature.Creature;
import de.dakror.vloxlands.game.entity.creature.Human;
import de.dakror.vloxlands.game.entity.structure.Structure;
import de.dakror.vloxlands.game.item.Item;
import de.dakror.vloxlands.game.item.ItemStack;
import de.dakror.vloxlands.game.item.inv.Inventory;
import de.dakror.vloxlands.game.item.inv.ResourceList;
import de.dakror.vloxlands.game.query.VoxelPos;
import de.dakror.vloxlands.game.voxel.Voxel;
import de.dakror.vloxlands.generate.biome.BiomeType;
import de.dakror.vloxlands.util.Direction;
import de.dakror.vloxlands.util.event.InventoryListener;
import de.dakror.vloxlands.util.event.SelectionListener;
import de.dakror.vloxlands.util.interf.Savable;
import de.dakror.vloxlands.util.interf.Tickable;
import de.dakror.vloxlands.util.math.Bits;
/**
* @author Dakror
*/
public class Island implements RenderableProvider, Tickable, Savable, InventoryListener
{
public static final int CHUNKS = 8;
public static final int SIZE = CHUNKS * Chunk.SIZE;
public FrameBuffer fbo;
public Vector3 index, pos;
public Chunk[] chunks;
public ResourceList availableResources;
public int visibleChunks;
public int loadedChunks;
public float initBalance = 0;
public boolean initFBO;
CopyOnWriteArrayList<Entity> entities = new CopyOnWriteArrayList<Entity>();
BiomeType biome;
float weight, uplift;
int tick;
boolean minimapMode;
boolean inFrustum;
boolean resourceListUpdateRequested;
public Island(BiomeType biome)
{
this.biome = biome;
chunks = new Chunk[CHUNKS * CHUNKS * CHUNKS];
initFBO = false;
minimapMode = false;
index = new Vector3();
pos = new Vector3();
availableResources = new ResourceList();
}
public void setPos(Vector3 pos)
{
this.pos = pos;
}
public BiomeType getBiome()
{
return biome;
}
public void calculateInitBalance()
{
recalculate();
initBalance = (uplift * World.calculateRelativeUplift(pos.y) - weight) / 100000f;
}
public void calculateWeight()
{
weight = 0;
for (Chunk c : chunks)
{
if (c == null) continue;
c.calculateWeight();
weight += c.weight;
}
for (Entity s : entities)
weight += s.getWeight();
}
public void calculateUplift()
{
uplift = 0;
for (Chunk c : chunks)
{
if (c == null) continue;
c.calculateUplift();
uplift += c.uplift;
}
for (Entity s : entities)
uplift += s.getUplift();
}
public void recalculate()
{
calculateUplift();
calculateWeight();
}
@Override
public void tick(int tick)
{
this.tick = tick;
float delta = getDelta();
if (Game.instance.activeIsland == this && delta != 0)
{
Game.camera.position.y += delta;
Game.instance.controller.target.y += delta;
Game.camera.update();
}
pos.y += delta;
for (Chunk c : chunks)
if (c != null) c.tick(tick);
for (Entity e : entities)
{
if (e.isMarkedForRemoval())
{
e.selected = false;
if (e instanceof Structure)
{
for (SelectionListener sl : Game.instance.listeners)
sl.onStructureSelection(null, true);
availableResources.remove(Item.get("BUILDINGS"), 1);
}
else if (e instanceof Creature)
{
for (SelectionListener sl : Game.instance.listeners)
sl.onCreatureSelection(null, true);
if (e instanceof Human) availableResources.remove(Item.get("PEOPLE"), 1);
}
e.dispose();
entities.remove(e);
}
else if (e.isSpawned())
{
e.tick(tick);
if (delta != 0) e.getTransform().translate(0, delta, 0);
}
}
inFrustum = Game.camera.frustum.boundsInFrustum(pos.x + SIZE / 2, pos.y + SIZE / 2, pos.z + SIZE / 2, SIZE / 2, SIZE / 2, SIZE / 2);
}
public void update(float delta)
{
for (Entity e : entities)
if (e.isSpawned() && !e.isMarkedForRemoval()) e.update(delta);
}
public float getDelta()
{
return (int) (((uplift * World.calculateRelativeUplift(pos.y) - weight) / 100000f - initBalance) * 100f) / 100f;
}
public float getDeltaPerSecond()
{
return getDelta() * 60f;
}
public void addEntity(Entity s, boolean user, boolean clearArea)
{
s.setIsland(this);
if (s instanceof Structure) ((Structure) s).getInnerInventory().addListener(this);
s.getTransform().translate(pos);
entities.add(s);
s.onSpawn();
if (s instanceof Structure) availableResources.add(Item.get("BUILDINGS"), 1);
if (s instanceof Human) availableResources.add(Item.get("PEOPLE"), 1);
if (!user && clearArea && (s instanceof Structure))
{
byte air = Voxel.get("AIR").getId();
Vector3 vp = ((Structure) s).getVoxelPos();
for (int i = -1; i < Math.ceil(s.getBoundingBox().getDimensions().x) + 1; i++)
for (int j = 0; j < Math.ceil(s.getBoundingBox().getDimensions().y); j++)
for (int k = -1; k < Math.ceil(s.getBoundingBox().getDimensions().z) + 1; k++)
set(i + vp.x, j + vp.y + 1, k + vp.z, air);
grassify();
}
if (s instanceof Structure || s.getWeight() != 0 || s.getUplift() != 0) recalculate();
}
public byte get(float x, float y, float z)
{
int chunkX = (int) (x / Chunk.SIZE);
if (chunkX < 0 || chunkX >= CHUNKS) return 0;
int chunkY = (int) (y / Chunk.SIZE);
if (chunkY < 0 || chunkY >= CHUNKS) return 0;
int chunkZ = (int) (z / Chunk.SIZE);
if (chunkZ < 0 || chunkZ >= CHUNKS) return 0;
ensureChunkExists(chunkX, chunkY, chunkZ);
return chunks[chunkZ + chunkY * CHUNKS + chunkX * CHUNKS * CHUNKS].get((int) x % Chunk.SIZE, (int) y % Chunk.SIZE, (int) z % Chunk.SIZE);
}
public void add(float x, float y, float z, byte id)
{
set(x, y, z, id, false, true);
}
public void set(float x, float y, float z, byte id)
{
set(x, y, z, id, true, true);
}
public void set(float x, float y, float z, byte id, boolean force, boolean notify)
{
int chunkX = (int) (x / Chunk.SIZE);
if (chunkX < 0 || chunkX >= CHUNKS) return;
int chunkY = (int) (y / Chunk.SIZE);
if (chunkY < 0 || chunkY >= CHUNKS) return;
int chunkZ = (int) (z / Chunk.SIZE);
if (chunkZ < 0 || chunkZ >= CHUNKS) return;
int x1 = (int) x % Chunk.SIZE;
int y1 = (int) y % Chunk.SIZE;
int z1 = (int) z % Chunk.SIZE;
ensureChunkExists(chunkX, chunkY, chunkZ);
if (chunks[chunkZ + chunkY * CHUNKS + chunkX * CHUNKS * CHUNKS].set(x1, y1, z1, id, force))
{
if (Game.instance.activeIsland == this && id == Voxel.get("AIR").getId() && x == Game.instance.selectedVoxel.x && y == Game.instance.selectedVoxel.y && z == Game.instance.selectedVoxel.z)
{
Game.instance.selectedVoxel.set(-1, 0, 0);
}
if (notify) notifySurroundingChunks(chunkX, chunkY, chunkZ);
}
}
public byte getMeta(float x, float y, float z)
{
int chunkX = (int) (x / Chunk.SIZE);
if (chunkX < 0 || chunkX >= CHUNKS) return 0;
int chunkY = (int) (y / Chunk.SIZE);
if (chunkY < 0 || chunkY >= CHUNKS) return 0;
int chunkZ = (int) (z / Chunk.SIZE);
if (chunkZ < 0 || chunkZ >= CHUNKS) return 0;
ensureChunkExists(chunkX, chunkY, chunkZ);
return chunks[chunkZ + chunkY * CHUNKS + chunkX * CHUNKS * CHUNKS].getMeta((int) x % Chunk.SIZE, (int) y % Chunk.SIZE, (int) z % Chunk.SIZE);
}
public void addMeta(float x, float y, float z, byte id)
{
setMeta(x, y, z, id, false);
}
public void setMeta(float x, float y, float z, byte id)
{
setMeta(x, y, z, id, true);
}
public void setMeta(float x, float y, float z, byte id, boolean force)
{
int chunkX = (int) (x / Chunk.SIZE);
if (chunkX < 0 || chunkX >= CHUNKS) return;
int chunkY = (int) (y / Chunk.SIZE);
if (chunkY < 0 || chunkY >= CHUNKS) return;
int chunkZ = (int) (z / Chunk.SIZE);
if (chunkZ < 0 || chunkZ >= CHUNKS) return;
int x1 = (int) x % Chunk.SIZE;
int y1 = (int) y % Chunk.SIZE;
int z1 = (int) z % Chunk.SIZE;
ensureChunkExists(chunkX, chunkY, chunkZ);
chunks[chunkZ + chunkY * CHUNKS + chunkX * CHUNKS * CHUNKS].setMeta(x1, y1, z1, id, force);
}
public void ensureChunkExists(int x, int y, int z)
{
int index = z + y * CHUNKS + x * CHUNKS * CHUNKS;
if (chunks[index] == null) chunks[index] = new Chunk(x, y, z, this);
}
public void notifySurroundingChunks(int cx, int cy, int cz)
{
for (Direction d : Direction.values())
{
try
{
int index = (int) ((cz + d.dir.z) + (cy + d.dir.y) * CHUNKS + (cx + d.dir.x) * CHUNKS * CHUNKS);
if (chunks[index] != null) chunks[index].forceUpdate();
}
catch (IndexOutOfBoundsException e)
{
continue;
}
}
}
public float getWeight()
{
return weight;
}
public float getUplift()
{
return uplift;
}
public Chunk[] getChunks()
{
return chunks;
}
public Chunk getChunk(float x, float y, float z)
{
return getChunk((int) (x * CHUNKS * CHUNKS + y * CHUNKS + z));
}
public Chunk getChunk(int i)
{
return chunks[i];
}
public int getStructureCount()
{
return entities.size();
}
public CopyOnWriteArrayList<Entity> getEntities()
{
return entities;
}
public void grassify()
{
for (Chunk c : chunks)
if (c != null) c.spread(0, false);
}
protected void renderEntities(ModelBatch batch, Environment environment, boolean minimapMode)
{
for (Entity s : entities)
{
if (minimapMode && !(s instanceof StaticEntity)) continue;
if (s.inFrustum || minimapMode)
{
s.render(batch, environment, minimapMode);
if (!minimapMode) Game.world.visibleEntities++;
}
}
}
public void render(ModelBatch batch, Environment environment)
{
renderEntities(batch, environment, false);
if (Game.instance.activeIsland == this && Game.instance.selectedVoxel.x > -1)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Game.shapeRenderer.setProjectionMatrix(Game.camera.combined);
Game.shapeRenderer.identity();
Game.shapeRenderer.translate(pos.x + Game.instance.selectedVoxel.x, pos.y + Game.instance.selectedVoxel.y, pos.z + Game.instance.selectedVoxel.z + 1);
Game.shapeRenderer.begin(ShapeType.Line);
Game.shapeRenderer.setColor(Color.WHITE);
Game.shapeRenderer.box(-World.gap / 2, -World.gap / 2, -World.gap / 2, 1 + World.gap, 1 + World.gap, 1 + World.gap);
Game.shapeRenderer.end();
}
if (((tick % 60 == 0 && Game.instance.activeIsland == this) || !initFBO || fbo.getWidth() != Gdx.graphics.getWidth() || fbo.getHeight() != Gdx.graphics.getHeight()) && environment != null)
{
if (fbo == null || fbo.getWidth() != Gdx.graphics.getWidth() || fbo.getHeight() != Gdx.graphics.getHeight()) fbo = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
fbo.begin();
Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Game.instance.minimapCamera.position.set(pos);
((OrthographicCamera) Game.instance.minimapCamera).zoom = 0.05f * Math.max(0.5f, Island.SIZE / 32f) / (Gdx.graphics.getWidth() / 1920f);
Game.instance.minimapCamera.translate(0, SIZE, 0);
Game.instance.minimapCamera.lookAt(pos.x + SIZE / 2, pos.y + SIZE / 2, pos.z + SIZE / 2);
Game.instance.minimapCamera.translate(0, 5, 0);
Game.instance.minimapCamera.update();
minimapMode = true;
Game.instance.minimapBatch.begin(Game.instance.minimapCamera);
Game.instance.minimapBatch.render(this, Game.instance.minimapEnv);
renderEntities(Game.instance.minimapBatch, Game.instance.minimapEnv, true);
Game.instance.minimapBatch.end();
fbo.end();
initFBO = wasDrawnOnce();
minimapMode = false;
Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 1);
}
}
public boolean wasDrawnOnce()
{
for (Chunk c : chunks)
if (c != null && !c.isEmpty() && !c.drawn) return false;
return true;
}
public boolean isFullyLoaded()
{
for (Chunk c : chunks)
if (c != null && !c.isEmpty() && !c.loaded) return false;
return true;
}
@Override
public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool)
{
if (!minimapMode)
{
visibleChunks = 0;
loadedChunks = 0;
}
int hs = Chunk.SIZE / 2;
if (!minimapMode && !inFrustum) return;
for (int i = 0; i < chunks.length; i++)
{
Chunk chunk = chunks[i];
if (chunk == null) continue;
if (chunk.isEmpty()) continue;
if (!chunk.onceLoaded) chunk.load();
if (minimapMode || (chunk.inFrustum = Game.camera.frustum.boundsInFrustum(pos.x + chunk.pos.x + hs, pos.y + chunk.pos.y + hs, pos.z + chunk.pos.z + hs, hs, hs, hs)))
{
if (!chunk.loaded && !minimapMode) chunk.load();
if (chunk.updateMeshes() && !minimapMode) visibleChunks++;
if (chunk.loaded && (chunk.opaqueVerts > 0 || chunk.transpVerts > 0))
{
if (minimapMode) chunk.drawn = true;
Renderable opaque = pool.obtain();
opaque.worldTransform.setToTranslation(pos.x, pos.y, pos.z);
opaque.material = minimapMode ? Game.world.getDefOpaque() : Game.world.getOpaque();
opaque.mesh = chunk.getOpaqueMesh();
opaque.meshPartOffset = 0;
opaque.meshPartSize = chunk.opaqueVerts;
opaque.primitiveType = GL20.GL_TRIANGLES;
if (chunk.opaqueVerts > 0 && (minimapMode || !Vloxlands.wireframe)) renderables.add(opaque);
Renderable transp = pool.obtain();
transp.worldTransform.setToTranslation(pos.x, pos.y, pos.z);
transp.material = minimapMode ? Game.world.getDefTransp() : Game.world.getTransp();
transp.mesh = chunk.getTransparentMesh();
transp.meshPartOffset = 0;
transp.meshPartSize = chunk.transpVerts;
transp.primitiveType = GL20.GL_TRIANGLES;
if (chunk.transpVerts > 0 && (minimapMode || !Vloxlands.wireframe)) renderables.add(transp);
if (Vloxlands.wireframe && !minimapMode)
{
Renderable opaque1 = pool.obtain();
opaque1.worldTransform.setToTranslation(pos.x, pos.y, pos.z);
opaque1.material = World.highlight;
opaque1.mesh = chunk.getOpaqueMesh();
opaque1.meshPartOffset = 0;
opaque1.meshPartSize = chunk.opaqueVerts;
opaque1.primitiveType = GL20.GL_LINES;
if (chunk.opaqueVerts > 0) renderables.add(opaque1);
Renderable transp1 = pool.obtain();
transp1.worldTransform.setToTranslation(pos.x, pos.y, pos.z);
transp1.material = World.highlight;
transp1.mesh = chunk.getTransparentMesh();
transp1.meshPartOffset = 0;
transp1.meshPartSize = chunk.transpVerts;
transp1.primitiveType = GL20.GL_LINES;
if (chunk.transpVerts > 0) renderables.add(transp1);
}
}
}
if (chunk.loaded && !minimapMode) loadedChunks++;
}
}
@Override
public void onItemAdded(int countBefore, Item item, Inventory inventory)
{
if (item != null)
{
int delta = inventory.getCount() - countBefore;
availableResources.add(item, delta);
}
else Gdx.app.error("Island.onItemAdded", "item = null, not handled!");
}
@Override
public void onItemRemoved(int countBefore, Item item, Inventory inventory)
{
if (item != null)
{
int delta = countBefore - inventory.getCount();
availableResources.remove(item, delta);
}
else Gdx.app.error("Island.onItemRemoved", "item = null, not handled!");
}
public boolean takeItemsIslandWide(ItemStack stack)
{
return takeItemsIslandWide(stack.getItem(), stack.getAmount());
}
public boolean takeItemsIslandWide(Item item, int amount)
{
if (availableResources.get(item) < amount) return false;
for (Entity e : entities)
{
if (!(e instanceof Structure) || !((Structure) e).isBuilt()) continue;
if (((Structure) e).getInventory().get(item) > 0)
{
amount -= ((Structure) e).getInventory().take(item, amount).getAmount();
}
if (amount == 0) break;
}
return amount == 0;
}
// -- voxel queries -- //
public boolean isSurrounded(float x, float y, float z, boolean opaque)
{
for (Direction d : Direction.values())
{
Voxel v = Voxel.getForId(get(x + d.dir.x, y + d.dir.y, z + d.dir.z));
if (v.isOpaque() != opaque || v.getId() == 0) return false;
}
return true;
}
/**
* Has atleast one air voxel adjacent
*/
public boolean isTargetable(float x, float y, float z)
{
byte air = Voxel.get("AIR").getId();
for (Direction d : Direction.values())
{
byte b = get(x + d.dir.x, y + d.dir.y, z + d.dir.z);
if (b == air) return true;
}
return false;
}
/**
* Is solid and has air above
*/
public boolean isWalkable(float x, float y, float z)
{
byte air = Voxel.get("AIR").getId();
byte above = get(x, y + 1, z);
return get(x, y, z) != air && (above == air || above == 0);
}
public boolean isSpaceAbove(float x, float y, float z, int height)
{
byte air = Voxel.get("AIR").getId();
for (int i = 0; i < height; i++)
{
byte b = get(x, y + i + 1, z);
if (b != 0 && b != air) return false;
}
return true;
}
public boolean isWrapped(float x, float y, float z, int height)
{
byte air = Voxel.get("AIR").getId();
Direction[] directions = { Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST };
for (Direction d : directions)
{
byte b = get(x + d.dir.x, y + d.dir.y, z + d.dir.z);
if (b == air || (b == air && isSpaceAbove(x + d.dir.x, y + d.dir.y, z + d.dir.z, height - (int) d.dir.y))) return false;
}
return true;
}
public boolean isWrapped(float x, float y, float z)
{
byte air = Voxel.get("AIR").getId();
Direction[] directions = { Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST };
for (Direction d : directions)
{
if (get(x + d.dir.x, y + d.dir.y, z + d.dir.z) == air) return false;
}
return true;
}
public boolean hasNeighbors(float x, float y, float z)
{
byte air = Voxel.get("AIR").getId();
Direction[] directions = { Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST };
for (Direction d : directions)
{
if (get(x + d.dir.x, y + d.dir.y, z + d.dir.z) != air) return true;
}
return false;
}
public VoxelPos getHighestVoxel(int x, int z)
{
byte air = Voxel.get("AIR").getId();
for (int y = SIZE - 1; y > -1; y
{
byte b;
if ((b = get(x, y, z)) != air) return new VoxelPos(x, y, z, b);
}
return new VoxelPos();
}
@Override
public void save(ByteArrayOutputStream baos) throws IOException
{
baos.write(biome.ordinal());
baos.write((int) index.x);
baos.write((int) index.z);
Bits.putFloat(baos, pos.y);
short i = 0;
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
for (Chunk c : chunks)
{
if (c == null) continue;
if (!c.isEmpty())
{
i++;
c.save(baos1);
}
}
Bits.putShort(baos, i);
baos.write(baos1.toByteArray());
Bits.putInt(baos, entities.size());
for (Entity e : entities)
e.save(baos);
}
} |
package hudson.slaves;
import hudson.model.*;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Callable;
import hudson.util.StreamTaskListener;
import hudson.util.NullStream;
import hudson.util.RingBufferLogHandler;
import hudson.util.Futures;
import hudson.FilePath;
import hudson.lifecycle.WindowsSlaveInstaller;
import hudson.Util;
import hudson.AbortException;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import java.security.Security;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
/**
* {@link Computer} for {@link Slave}s.
*
* @author Kohsuke Kawaguchi
*/
public class SlaveComputer extends Computer {
private volatile Channel channel;
private volatile transient boolean acceptingTasks = true;
private Charset defaultCharset;
private Boolean isUnix;
/**
* Effective {@link ComputerLauncher} that hides the details of
* how we launch a slave agent on this computer.
*
* <p>
* This is normally the same as {@link Slave#getLauncher()} but
* can be different. See {@link #grabLauncher(Node)}.
*/
private ComputerLauncher launcher;
/**
* Number of failed attempts to reconnect to this node
* (so that if we keep failing to reconnect, we can stop
* trying.)
*/
private transient int numRetryAttempt;
/**
* Tracks the status of the last launch operation, which is always asynchronous.
* This can be used to wait for the completion, or cancel the launch activity.
*/
private volatile Future<?> lastConnectActivity = null;
private Object constructed = new Object();
public SlaveComputer(Slave slave) {
super(slave);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAcceptingTasks() {
return acceptingTasks;
}
/**
* Allows a {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy} to
* suspend tasks being accepted by the slave computer.
*
* @param acceptingTasks {@code true} if the slave can accept tasks.
*/
public void setAcceptingTasks(boolean acceptingTasks) {
this.acceptingTasks = acceptingTasks;
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public Boolean isUnix() {
return isUnix;
}
public Slave getNode() {
return (Slave)super.getNode();
}
@Override
public String getIcon() {
Future<?> l = lastConnectActivity;
if(l!=null && !l.isDone())
return "computer-flash.gif";
return super.getIcon();
}
@Override
@Deprecated
public boolean isJnlpAgent() {
return launcher instanceof JNLPLauncher;
}
@Override
public boolean isLaunchSupported() {
return launcher.isLaunchSupported();
}
public ComputerLauncher getLauncher() {
return launcher;
}
public Future<?> connect(boolean forceReconnect) {
if(channel!=null) return Futures.precomputed(null);
if(!forceReconnect && lastConnectActivity!=null)
return lastConnectActivity;
if(forceReconnect && lastConnectActivity!=null)
logger.fine("Forcing a reconnect");
closeChannel();
return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() {
public Object call() throws Exception {
// do this on another thread so that the lengthy launch operation
// (which is typical) won't block UI thread.
TaskListener listener = new StreamTaskListener(openLogFile());
try {
launcher.launch(SlaveComputer.this, listener);
return null;
} catch (AbortException e) {
listener.error(e.getMessage());
throw e;
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
throw e;
} catch (InterruptedException e) {
e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
throw e;
}
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void taskAccepted(Executor executor, Queue.Task task) {
super.taskAccepted(executor, task);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskAccepted(executor, task);
}
if (getNode().getRetentionStrategy() instanceof ExecutorListener) {
((ExecutorListener)getNode().getRetentionStrategy()).taskAccepted(executor, task);
}
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
super.taskCompleted(executor, task, durationMS);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskCompleted(executor, task, durationMS);
}
if (getNode().getRetentionStrategy() instanceof ExecutorListener) {
((ExecutorListener)getNode().getRetentionStrategy()).taskCompleted(executor, task, durationMS);
}
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
super.taskCompletedWithProblems(executor, task, durationMS, problems);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems);
}
if (getNode().getRetentionStrategy() instanceof ExecutorListener) {
((ExecutorListener)getNode().getRetentionStrategy()).taskCompletedWithProblems(executor, task, durationMS,
problems);
}
}
@Override
public boolean isConnecting() {
Future<?> l = lastConnectActivity;
return isOffline() && l!=null && !l.isDone();
}
public OutputStream openLogFile() {
OutputStream os;
try {
os = new FileOutputStream(getLogFile());
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
os = new NullStream();
}
return os;
}
private final Object channelLock = new Object();
public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException {
setChannel(in,out,taskListener.getLogger(),listener);
}
/**
* Creates a {@link Channel} from the given stream and sets that to this slave.
*
* @param in
* Stream connected to the remote "slave.jar". It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param out
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param launchLog
* If non-null, receive the portion of data in <tt>is</tt> before
* the data goes into the "binary mode". This is useful
* when the established communication channel might include some data that might
* be useful for debugging/trouble-shooting.
* @param listener
* Gets a notification when the channel closes, to perform clean up. Can be null.
*/
public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
if(this.channel!=null)
throw new IllegalStateException("Already connected");
PrintWriter log = new PrintWriter(launchLog,true);
final TaskListener taskListener = new StreamTaskListener(log);
Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE,
in,out, launchLog);
channel.addListener(new Channel.Listener() {
public void onClosed(Channel c,IOException cause) {
SlaveComputer.this.channel = null;
launcher.afterDisconnect(SlaveComputer.this, taskListener);
}
});
if(listener!=null)
channel.addListener(listener);
boolean _isUnix = channel.call(new DetectOS());
log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave());
String defaultCharsetName = channel.call(new DetectDefaultCharset());
String remoteFs = getNode().getRemoteFS();
if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
FilePath root = new FilePath(channel,getNode().getRemoteFS());
channel.call(new SlaveInitializer());
channel.call(new WindowsSlaveInstaller(remoteFs));
for (ComputerListener cl : ComputerListener.all())
cl.preOnline(this,channel,root,taskListener);
// update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
synchronized(channelLock) {
if(this.channel!=null) {
// check again. we used to have this entire method in a big sycnhronization block,
// but Channel constructor blocks for an external process to do the connection
// if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
// so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
// we'll end up queuing the lot of threads in a pseudo deadlock.
// This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
channel.close();
throw new IllegalStateException("Already connected");
}
isUnix = _isUnix;
numRetryAttempt = 0;
this.channel = channel;
defaultCharset = Charset.forName(defaultCharsetName);
}
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(this,taskListener);
Hudson.getInstance().getQueue().scheduleMaintenance();
}
@Override
public VirtualChannel getChannel() {
return channel;
}
public Charset getDefaultCharset() {
return defaultCharset;
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
if(channel==null)
return Collections.emptyList();
else
return channel.call(new Callable<List<LogRecord>,RuntimeException>() {
public List<LogRecord> call() {
return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView());
}
});
}
public void doDoDisconnect(StaplerResponse rsp) throws IOException, ServletException {
checkPermission(Hudson.ADMINISTER);
disconnect();
rsp.sendRedirect(".");
}
@Override
public Future<?> disconnect() {
return Computer.threadPoolForRemoting.submit(new Runnable() {
public void run() {
// do this on another thread so that any lengthy disconnect operation
// (which could be typical) won't block UI thread.
TaskListener listener = new StreamTaskListener(openLogFile());
launcher.beforeDisconnect(SlaveComputer.this, listener);
closeChannel();
launcher.afterDisconnect(SlaveComputer.this, listener);
}
});
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(channel!=null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
connect(true);
// TODO: would be nice to redirect the user to "launching..." wait page,
// then spend a few seconds there and poll for the completion periodically.
rsp.sendRedirect("log");
}
public void tryReconnect() {
numRetryAttempt++;
if(numRetryAttempt<6 || (numRetryAttempt%12)==0) {
// initially retry several times quickly, and after that, do it infrequently.
logger.info("Attempting to reconnect "+nodeName);
connect(true);
}
}
/**
* Serves jar files for JNLP slave agents.
*
* @deprecated
* This URL binding is no longer used and moved up directly under to {@link Hudson},
* but it's left here for now just in case some old JNLP slave agents request it.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
@Override
protected void kill() {
super.kill();
closeChannel();
}
public RetentionStrategy getRetentionStrategy() {
return getNode().getRetentionStrategy();
}
/**
* If still connected, disconnect.
*/
private void closeChannel() {
// TODO: race condition between this and the setChannel method.
Channel c = channel;
channel = null;
isUnix = null;
if (c != null) {
try {
c.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e);
}
}
for (ComputerListener cl : ComputerListener.all())
cl.onOffline(this);
}
@Override
protected void setNode(Node node) {
super.setNode(node);
launcher = grabLauncher(node);
// maybe the configuration was changed to relaunch the slave, so try to re-launch now.
// "constructed==null" test is an ugly hack to avoid launching before the object is fully
// constructed.
if(constructed!=null)
connect(false);
}
/**
* Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}.
* The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation.
*
* <p>
* Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method.
* This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs
* additional pre-launch step (such as waiting for the provisioned node to become available)
* before the user specified launch step (like SSH connection) kicks in.
*
* @see ComputerLauncherFilter
*/
protected ComputerLauncher grabLauncher(Node node) {
return ((Slave)node).getLauncher();
}
private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName());
private static final class DetectOS implements Callable<Boolean,IOException> {
public Boolean call() throws IOException {
return File.pathSeparatorChar==':';
}
}
private static final class DetectDefaultCharset implements Callable<String,IOException> {
public String call() throws IOException {
return Charset.defaultCharset().name();
}
}
/**
* This field is used on each slave node to record log records on the slave.
*/
private static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler();
private static class SlaveInitializer implements Callable<Void,RuntimeException> {
public Void call() {
// avoid double installation of the handler
Logger logger = Logger.getLogger("hudson");
logger.removeHandler(SLAVE_LOG_HANDLER);
logger.addHandler(SLAVE_LOG_HANDLER);
try {
Security.removeProvider("SunPKCS11-Solaris");
} catch (SecurityException e) {
// ignore this error.
}
return null;
}
private static final long serialVersionUID = 1L;
}
} |
package io.grpc;
import com.google.common.base.Preconditions;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.concurrent.GuardedBy;
/**
* Executor ensuring that all {@link Runnable} tasks submitted are executed in order
* using the provided {@link Executor}, and serially such that no two will ever be
* running at the same time.
*/
// TODO(madongfly): figure out a way to not expose it or move it to transport package.
public final class SerializingExecutor implements Executor {
private static final Logger log =
Logger.getLogger(SerializingExecutor.class.getName());
/** Underlying executor that all submitted Runnable objects are run on. */
private final Executor executor;
/** A list of Runnables to be run in order. */
// Initial size set to 4 because it is a nice number and at least the size necessary for handling
// a unary response: onHeaders + onPayload + onClose
@GuardedBy("internalLock")
private final Queue<Runnable> waitQueue = new ArrayDeque<Runnable>(4);
/**
* We explicitly keep track of if the TaskRunner is currently scheduled to
* run. If it isn't, we start it. We can't just use
* waitQueue.isEmpty() as a proxy because we need to ensure that only one
* Runnable submitted is running at a time so even if waitQueue is empty
* the isThreadScheduled isn't set to false until after the Runnable is
* finished.
*/
@GuardedBy("internalLock")
private boolean isThreadScheduled = false;
/** The object that actually runs the Runnables submitted, reused. */
private final TaskRunner taskRunner = new TaskRunner();
/**
* Creates a SerializingExecutor, running tasks using {@code executor}.
*
* @param executor Executor in which tasks should be run. Must not be null.
*/
public SerializingExecutor(Executor executor) {
Preconditions.checkNotNull(executor, "'executor' must not be null.");
this.executor = executor;
}
private final Object internalLock = new Object() {
@Override public String toString() {
return "SerializingExecutor lock: " + super.toString();
}
};
/**
* Runs the given runnable strictly after all Runnables that were submitted
* before it, and using the {@code executor} passed to the constructor. .
*/
@Override
public void execute(Runnable r) {
Preconditions.checkNotNull(r, "'r' must not be null.");
boolean scheduleTaskRunner = false;
synchronized (internalLock) {
waitQueue.add(r);
if (!isThreadScheduled) {
isThreadScheduled = true;
scheduleTaskRunner = true;
}
}
if (scheduleTaskRunner) {
boolean threw = true;
try {
executor.execute(taskRunner);
threw = false;
} finally {
if (threw) {
synchronized (internalLock) {
// It is possible that at this point that there are still tasks in
// the queue, it would be nice to keep trying but the error may not
// be recoverable. So we update our state and propogate so that if
// our caller deems it recoverable we won't be stuck.
isThreadScheduled = false;
}
}
}
}
}
/**
* Task that actually runs the Runnables. It takes the Runnables off of the
* queue one by one and runs them. After it is done with all Runnables and
* there are no more to run, puts the SerializingExecutor in the state where
* isThreadScheduled = false and returns. This allows the current worker
* thread to return to the original pool.
*/
private class TaskRunner implements Runnable {
@Override
public void run() {
boolean stillRunning = true;
try {
while (true) {
Runnable nextToRun;
synchronized (internalLock) {
Preconditions.checkState(isThreadScheduled);
nextToRun = waitQueue.poll();
if (nextToRun == null) {
isThreadScheduled = false;
stillRunning = false;
break;
}
}
// Always run while not holding the lock, to avoid deadlocks.
try {
nextToRun.run();
} catch (RuntimeException e) {
// Log it and keep going.
log.log(Level.SEVERE, "Exception while executing runnable "
+ nextToRun, e);
}
}
} finally {
if (stillRunning) {
// An Error is bubbling up, we should mark ourselves as no longer
// running, that way if anyone tries to keep using us we won't be
// corrupted.
synchronized (internalLock) {
isThreadScheduled = false;
}
}
}
}
}
} |
package org.picojs;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MulticastEnabler {
public static final InetAddress mCastAddress =init();
public static final int port = 9223;
private static InetAddress init(){
try {
Runtime.getRuntime().exec("route add -net 224.0.0.0/24 -interface lo0".split(" "));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
return Inet4Address.getByAddress(new byte[]{(byte)224,1,2,(byte)251});
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
} |
package jenkins.install;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.FileUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import hudson.BulkChange;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.SecurityRealm;
import hudson.security.csrf.DefaultCrumbIssuer;
import hudson.util.HttpResponses;
import hudson.util.PluginServletFilter;
import jenkins.model.Jenkins;
import jenkins.security.s2m.AdminWhitelistRule;
/**
* A Jenkins instance used during first-run to provide a limited set of services while
* initial installation is in progress
*
* @since 2.0
*/
public class SetupWizard {
/**
* The security token parameter name
*/
public static String initialSetupAdminUserName = "admin";
private final Logger LOGGER = Logger.getLogger(SetupWizard.class.getName());
public SetupWizard(Jenkins j) throws IOException {
// Create an admin user by default with a
// difficult password
if(j.getSecurityRealm() == null || j.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION) { // this seems very fragile
BulkChange bc = new BulkChange(j);
HudsonPrivateSecurityRealm securityRealm = new HudsonPrivateSecurityRealm(false, false, null);
j.setSecurityRealm(securityRealm);
String randomUUID = UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ENGLISH);
// create an admin user
securityRealm.createAccount(SetupWizard.initialSetupAdminUserName, randomUUID);
// JENKINS-33599 - write to a file in the jenkins home directory
FileUtils.write(getInitialAdminPasswordFile(), randomUUID);
// Lock Jenkins down:
FullControlOnceLoggedInAuthorizationStrategy authStrategy = new FullControlOnceLoggedInAuthorizationStrategy();
authStrategy.setAllowAnonymousRead(false);
j.setAuthorizationStrategy(authStrategy);
// Shut down all the ports we can by default:
j.setSlaveAgentPort(-1); // -1 to disable
// require a crumb issuer
j.setCrumbIssuer(new DefaultCrumbIssuer(false));
// set master -> slave security:
j.getInjector().getInstance(AdminWhitelistRule.class)
.setMasterKillSwitch(false);
try{
j.save();
} finally {
bc.commit();
}
}
String setupKey = FileUtils.readFileToString(getInitialAdminPasswordFile());
LOGGER.info("\n\n*************************************************************\n"
+ "*************************************************************\n"
+ "*************************************************************\n"
+ "\n"
+ "Jenkins initial setup is required. An admin user has been created and"
+ "a password generated. \n"
+ "Please use the following password to proceed to installation: \n"
+ "\n"
+ "" + setupKey + "\n"
+ "\n"
+ "This may also be found at: " + getInitialAdminPasswordFile().getCanonicalPath() + "\n"
+ "\n"
+ "*************************************************************\n"
+ "*************************************************************\n"
+ "*************************************************************\n");
try {
PluginServletFilter.addFilter(FORCE_SETUP_WIZARD_FILTER);
} catch (ServletException e) {
throw new AssertionError(e);
}
}
/**
* Gets the file used to store the initial admin password
*/
public File getInitialAdminPasswordFile() {
return new File(Jenkins.getInstance().root, "initialAdminPassword");
}
/**
* Remove the setupWizard filter, ensure all updates are written to disk, etc
*/
public HttpResponse doCompleteInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Jenkins j = Jenkins.getInstance();
j.setInstallState(InstallState.INITIAL_SETUP_COMPLETED);
InstallUtil.saveLastExecVersion();
PluginServletFilter.removeFilter(FORCE_SETUP_WIZARD_FILTER);
// Also, clean up the setup wizard if it's completed
j.setSetupWizard(null);
return HttpResponses.okJSON();
}
/**
* This filter will validate that the security token is provided
*/
private final Filter FORCE_SETUP_WIZARD_FILTER = new Filter() {
@Override
public void init(FilterConfig cfg) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// As an extra measure of security, the install wizard generates a security token, and
// requires the user to enter it before proceeding through the installation. Once set
// we'll set a cookie so the subsequent operations succeed
if (request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
//if (!Pattern.compile(".*[.](css|ttf|gif|woff|eot|png|js)").matcher(req.getRequestURI()).matches()) {
// Allow js & css requests through
if((req.getContextPath() + "/").equals(req.getRequestURI())) {
chain.doFilter(new HttpServletRequestWrapper(req) {
public String getRequestURI() {
return getContextPath() + "/setupWizard/";
}
}, response);
return;
}
// fall through to handling the request normally
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
};
} |
package io.github.classgraph;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import nonapi.io.github.classgraph.reflection.ReflectionUtils;
import nonapi.io.github.classgraph.utils.JarUtils;
import nonapi.io.github.classgraph.utils.StringUtils;
/**
* Information on the module path. Note that this will only include module system parameters actually listed in
* commandline arguments -- in particular this does not include classpath elements from the traditional classpath,
* or system modules.
*/
public class ModulePathInfo {
/**
* The module path provided on the commandline by the {@code --module-path} or {@code -p} switch, as an ordered
* set of module names, in the order they were listed on the commandline.
*
* <p>
* Note that some modules (such as system modules) will not be in this set, as they are added to the module
* system automatically by the runtime. Call {@link ClassGraph#getModules()} or {@link ScanResult#getModules()}
* to get all modules visible at runtime.
*/
public final Set<String> modulePath = new LinkedHashSet<>();
public final Set<String> addModules = new LinkedHashSet<>();
/**
* The module patch directives listed on the commandline using the {@code --patch-module} switch, as an ordered
* set of strings in the format {@code <module>=<file>}, in the order they were listed on the commandline.
*/
public final Set<String> patchModules = new LinkedHashSet<>();
/**
* The module {@code exports} directives added on the commandline using the {@code --add-exports} switch, as an
* ordered set of strings in the format {@code <source-module>/<package>=<target-module>(,<target-module>)*}, in
* the order they were listed on the commandline. Additionally, if this {@link ModulePathInfo} object was
* obtained from {@link ScanResult#getModulePathInfo()} rather than {@link ClassGraph#getModulePathInfo()}, any
* additional {@code Add-Exports} entries found in manifest files during classpath scanning will be appended to
* this list, in the format {@code <source-module>/<package>=ALL-UNNAMED}.
*/
public final Set<String> addExports = new LinkedHashSet<>();
/**
* The module {@code opens} directives added on the commandline using the {@code --add-opens} switch, as an
* ordered set of strings in the format {@code <source-module>/<package>=<target-module>(,<target-module>)*}, in
* the order they were listed on the commandline. Additionally, if this {@link ModulePathInfo} object was
* obtained from {@link ScanResult#getModulePathInfo()} rather than {@link ClassGraph#getModulePathInfo()}, any
* additional {@code Add-Opens} entries found in manifest files during classpath scanning will be appended to
* this list, in the format {@code <source-module>/<package>=ALL-UNNAMED}.
*/
public final Set<String> addOpens = new LinkedHashSet<>();
/**
* The module {@code reads} directives added on the commandline using the {@code --add-reads} switch, as an
* ordered set of strings in the format {@code <source-module>=<target-module>}, in the order they were listed
* on the commandline.
*/
public final Set<String> addReads = new LinkedHashSet<>();
/** The fields. */
private final List<Set<String>> fields = Arrays.asList(
modulePath,
addModules,
patchModules,
addExports,
addOpens,
addReads
);
/** The module path commandline switches. */
private static final List<String> argSwitches = Arrays.asList(
"--module-path=",
"--add-modules=",
"--patch-module=",
"--add-exports=",
"--add-opens=",
"--add-reads="
);
/** The module path commandline switch value delimiters. */
private static final List<Character> argPartSeparatorChars = Arrays.asList(
File.pathSeparatorChar, // --module-path (delimited path format)
',', // --add-modules (comma-delimited)
'\0', // --patch-module (only one param per switch)
'\0', // --add-exports (only one param per switch)
'\0', // --add-opens (only one param per switch)
'\0' // --add-reads (only one param per switch)
);
/** Set to true once {@link #getRuntimeInfo()} is called. */
private final AtomicBoolean gotRuntimeInfo = new AtomicBoolean();
/** Fill in module info from VM commandline parameters. */
void getRuntimeInfo() {
// access warning on some JREs, e.g. Adopt JDK 11 (#605)
if (!gotRuntimeInfo.getAndSet(true)) {
// Read the raw commandline arguments to get the module path override parameters.
// If the java.management module is not present in the deployed runtime (for JDK 9+), or the runtime
// does not contain the java.lang.management package (e.g. the Android build system, which also does
// not support JPMS currently), then skip trying to read the commandline arguments (#404).
final Class<?> managementFactory = ReflectionUtils
.classForNameOrNull("java.lang.management.ManagementFactory");
final Object runtimeMXBean = managementFactory == null ? null
: ReflectionUtils.invokeStaticMethod(/* throwException = */ false, managementFactory,
"getRuntimeMXBean");
@SuppressWarnings("unchecked")
final List<String> commandlineArguments = runtimeMXBean == null ? null
: (List<String>) ReflectionUtils.invokeMethod(/* throwException = */ false, runtimeMXBean,
"getInputArguments");
if (commandlineArguments != null) {
for (final String arg : commandlineArguments) {
for (int i = 0; i < fields.size(); i++) {
final String argSwitch = argSwitches.get(i);
if (arg.startsWith(argSwitch)) {
final String argParam = arg.substring(argSwitch.length());
final Set<String> argField = fields.get(i);
final char sepChar = argPartSeparatorChars.get(i);
if (sepChar == '\0') {
// Only one param per switch
argField.add(argParam);
} else {
// Split arg param into parts
argField.addAll(Arrays
.asList(JarUtils.smartPathSplit(argParam, sepChar, /* scanSpec = */ null)));
}
}
}
}
}
}
}
/**
* Return the module path info in commandline format.
*
* @return the module path commandline string.
*/
@Override
public String toString() {
final StringBuilder buf = new StringBuilder(1024);
if (!modulePath.isEmpty()) {
buf.append("--module-path=");
buf.append(StringUtils.join(File.pathSeparator, modulePath));
}
if (!addModules.isEmpty()) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append("--add-modules=");
buf.append(StringUtils.join(",", addModules));
}
for (final String patchModulesEntry : patchModules) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append("--patch-module=");
buf.append(patchModulesEntry);
}
for (final String addExportsEntry : addExports) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append("--add-exports=");
buf.append(addExportsEntry);
}
for (final String addOpensEntry : addOpens) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append("--add-opens=");
buf.append(addOpensEntry);
}
for (final String addReadsEntry : addReads) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append("--add-reads=");
buf.append(addReadsEntry);
}
return buf.toString();
}
} |
package lucee.runtime.tag;
import static lucee.runtime.tag.util.FileUtil.NAMECONFLICT_ERROR;
import static lucee.runtime.tag.util.FileUtil.NAMECONFLICT_OVERWRITE;
import static lucee.runtime.tag.util.FileUtil.NAMECONFLICT_SKIP;
import static lucee.runtime.tag.util.FileUtil.NAMECONFLICT_UNDEFINED;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import lucee.commons.io.ModeUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.ResourceMetaData;
import lucee.commons.io.res.filter.AndResourceFilter;
import lucee.commons.io.res.filter.DirectoryResourceFilter;
import lucee.commons.io.res.filter.FileResourceFilter;
import lucee.commons.io.res.filter.NotResourceFilter;
import lucee.commons.io.res.filter.OrResourceFilter;
import lucee.commons.io.res.filter.ResourceFilter;
import lucee.commons.io.res.filter.ResourceNameFilter;
import lucee.commons.io.res.type.file.FileResource;
import lucee.commons.io.res.util.ModeObjectWrap;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.io.res.util.UDFFilter;
import lucee.commons.io.res.util.WildcardPatternFilter;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.runtime.PageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.function.BIF;
import lucee.runtime.ext.tag.TagImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.reflection.Reflector;
import lucee.runtime.security.SecurityManager;
import lucee.runtime.tag.util.FileUtil;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.Query;
import lucee.runtime.type.QueryImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.dt.DateTimeImpl;
import lucee.runtime.type.util.KeyConstants;
/**
* Handles interactions with directories.
**/
public final class Directory extends TagImpl {
public static final int TYPE_ALL = 0;
public static final int TYPE_FILE = 1;
public static final int TYPE_DIR = 2;
public static final ResourceFilter DIRECTORY_FILTER = new DirectoryResourceFilter();
public static final ResourceFilter FILE_FILTER = new FileResourceFilter();
private static final Key MODE = KeyConstants._mode;
private static final Key META = KeyConstants._meta;
private static final Key DATE_LAST_MODIFIED = KeyConstants._dateLastModified;
private static final Key ATTRIBUTES = KeyConstants._attributes;
private static final Key DIRECTORY = KeyConstants._directory;
public static final int LIST_INFO_QUERY_ALL = 1;
public static final int LIST_INFO_QUERY_NAME = 2;
public static final int LIST_INFO_ARRAY_NAME = 4;
public static final int LIST_INFO_ARRAY_PATH = 8;
public static final int NAMECONFLICT_DEFAULT = NAMECONFLICT_OVERWRITE; // default
/**
* Optional for action = "list". Ignored by all other actions. File extension filter applied to
** returned names. For example: *m. Only one mask filter can be applied at a time.
*/
// private final ResourceFilter filter=null;
// private ResourceAndResourceNameFilter nameFilter=null;
private ResourceFilter filter = null;
private String pattern;
private String patternDelimiters;
/** The name of the directory to perform the action against. */
private Resource directory;
/** Defines the action to be taken with directory(ies) specified in directory. */
private String action = "list";
/**
* Optional for action = "list". Ignored by all other actions. The query columns by which to sort
** the directory listing. Any combination of columns from query output can be specified in
* comma-separated list. You can specify ASC (ascending) or DESC (descending) as qualifiers for
* column names. ASC is the default
*/
private String sort;
private int mode = -1;
/**
* Required for action = "rename". Ignored by all other actions. The new name of the directory
** specified in the directory attribute.
*/
private String strNewdirectory;
/**
* Required for action = "list". Ignored by all other actions. Name of output query for directory
** listing.
*/
private String name = null;
private boolean recurse = false;
private String serverPassword;
private int type = TYPE_ALL;
// private boolean listOnlyNames;
private int listInfo = LIST_INFO_QUERY_ALL;
// private int acl=S3Constants.ACL_UNKNOW;
private Object acl = null;
private String storage = null;
private String destination;
private int nameconflict = NAMECONFLICT_DEFAULT;
private boolean createPath = true;
@Override
public void release() {
super.release();
acl = null;
storage = null;
type = TYPE_ALL;
// filter=null;
filter = null;
destination = null;
directory = null;
action = "list";
sort = null;
mode = -1;
strNewdirectory = null;
name = null;
recurse = false;
serverPassword = null;
listInfo = LIST_INFO_QUERY_ALL;
nameconflict = NAMECONFLICT_DEFAULT;
createPath = true;
pattern = null;
patternDelimiters = null;
}
public void setCreatepath(boolean createPath) {
this.createPath = createPath;
}
/**
* sets a filter
*
* @param filter
* @throws PageException
**/
public void setFilter(Object filter) throws PageException {
if (filter instanceof UDF) this.setFilter((UDF) filter);
else if (filter instanceof String) this.setFilter((String) filter);
}
public void setFilter(UDF filter) throws PageException {
this.filter = UDFFilter.createResourceAndResourceNameFilter(filter);
}
public void setFilter(String pattern) {
this.pattern = pattern;
}
public void setFilterdelimiters(String patternDelimiters) {
this.patternDelimiters = patternDelimiters;
}
/**
* set the value acl used only for s3 resources, for all others ignored
*
* @param acl value to set
* @throws ApplicationException
* @Deprecated only exists for backward compatibility to old ra files.
**/
public void setAcl(String acl) throws ApplicationException {
this.acl = acl;
}
public void setAcl(Object acl) {
this.acl = acl;
}
public void setStoreacl(Object acl) {
this.acl = acl;
}
/**
* set the value storage used only for s3 resources, for all others ignored
*
* @param storage value to set
* @throws PageException
**/
public void setStorage(String storage) throws PageException {
this.storage = improveStorage(storage);
}
public void setStorelocation(String storage) throws PageException {
setStorage(storage);
}
public static String improveStorage(String storage) throws ApplicationException {
storage = improveStorage(storage, null);
if (storage != null) return storage;
throw new ApplicationException("Invalid storage value, valid values are [eu, us, us-west]");
}
public static String improveStorage(String storage, String defaultValue) {
storage = storage.toLowerCase().trim();
if ("us".equals(storage)) return "us";
if ("usa".equals(storage)) return "us";
if ("u.s.".equals(storage)) return "us";
if ("u.s.a.".equals(storage)) return "us";
if ("united states of america".equals(storage)) return "us";
if ("eu".equals(storage)) return "eu";
if ("europe.".equals(storage)) return "eu";
if ("european union.".equals(storage)) return "eu";
if ("euro.".equals(storage)) return "eu";
if ("e.u.".equals(storage)) return "eu";
if ("us-west".equals(storage)) return "us-west";
if ("usa-west".equals(storage)) return "us-west";
return defaultValue;
}
public void setServerpassword(String serverPassword) {
this.serverPassword = serverPassword;
}
public void setListinfo(String strListinfo) {
strListinfo = strListinfo.trim().toLowerCase();
this.listInfo = "name".equals(strListinfo) ? LIST_INFO_QUERY_NAME : LIST_INFO_QUERY_ALL;
}
/**
* set the value directory The name of the directory to perform the action against.
*
* @param directory value to set
**/
public void setDirectory(String directory) {
this.directory = ResourceUtil.toResourceNotExisting(pageContext, directory);
// print.ln(this.directory);
}
/**
* set the value action Defines the action to be taken with directory(ies) specified in directory.
*
* @param action value to set
**/
public void setAction(String action) {
this.action = action.toLowerCase();
}
/**
* set the value sort Optional for action = "list". Ignored by all other actions. The query columns
* by which to sort the directory listing. Any combination of columns from query output can be
* specified in comma-separated list. You can specify ASC (ascending) or DESC (descending) as
* qualifiers for column names. ASC is the default
*
* @param sort value to set
**/
public void setSort(String sort) {
if (sort.trim().length() > 0) this.sort = sort;
}
public void setMode(String mode) throws PageException {
try {
this.mode = ModeUtil.toOctalMode(mode);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
* set the value newdirectory Required for action = "rename". Ignored by all other actions. The new
* name of the directory specified in the directory attribute.
*
* @param newdirectory value to set
**/
public void setNewdirectory(String newdirectory) {
// this.newdirectory=ResourceUtil.toResourceNotExisting(pageContext ,newdirectory);
this.strNewdirectory = newdirectory;
}
public void setDestination(String destination) {
this.destination = destination;
}
/**
* set the value name Required for action = "list". Ignored by all other actions. Name of output
* query for directory listing.
*
* @param name value to set
**/
public void setName(String name) {
this.name = name;
}
/**
* @param recurse The recurse to set.
*/
public void setRecurse(boolean recurse) {
this.recurse = recurse;
}
/**
* set the value nameconflict Action to take if destination directory is the same as that of a file
* in the directory.
*
* @param nameconflict value to set
* @throws ApplicationException
**/
public void setNameconflict(String nameconflict) throws ApplicationException {
this.nameconflict = FileUtil.toNameConflict(nameconflict, NAMECONFLICT_UNDEFINED | NAMECONFLICT_ERROR | NAMECONFLICT_OVERWRITE | NAMECONFLICT_SKIP, NAMECONFLICT_DEFAULT);
}
@Override
public int doStartTag() throws PageException {
if (this.filter == null && !StringUtil.isEmpty(this.pattern)) this.filter = new WildcardPatternFilter(pattern, patternDelimiters);
// securityManager = pageContext.getConfig().getSecurityManager();
if (action.equals("list")) {
Object res = actionList(pageContext, directory, serverPassword, type, filter, listInfo, recurse, sort);
if (!StringUtil.isEmpty(name) && res != null) pageContext.setVariable(name, res);
}
else if (action.equals("create")) actionCreate(pageContext, directory, serverPassword, createPath, mode, acl, storage, nameconflict);
else if (action.equals("delete")) actionDelete(pageContext, directory, recurse, serverPassword);
else if (action.equals("forcedelete")) actionDelete(pageContext, directory, true, serverPassword);
else if (action.equals("rename")) {
String res = actionRename(pageContext, directory, strNewdirectory, serverPassword, createPath, acl, storage);
if (!StringUtil.isEmpty(name) && res != null) pageContext.setVariable(name, res);
}
else if (action.equals("copy")) {
if (StringUtil.isEmpty(destination, true) && !StringUtil.isEmpty(strNewdirectory, true)) {
destination = strNewdirectory.trim();
}
actionCopy(pageContext, directory, destination, serverPassword, createPath, acl, storage, filter, recurse, nameconflict);
}
else if (action.equals("info")) {
Object res = getInfo(pageContext, directory, null);
if (!StringUtil.isEmpty(name) && res != null) pageContext.setVariable(name, res);
}
else throw new ApplicationException("Invalid action [" + action + "] for the tag [directory]");
return SKIP_BODY;
}
@Override
public int doEndTag() {
return EVAL_PAGE;
}
/**
* list all files and directories inside a directory
*
* @throws PageException
*/
public static Object actionList(PageContext pageContext, Resource directory, String serverPassword, int type, ResourceFilter filter, int listInfo, boolean recurse, String sort)
throws PageException {
// check directory
SecurityManager securityManager = pageContext.getConfig().getSecurityManager();
securityManager.checkFileLocation(pageContext.getConfig(), directory, serverPassword);
if (type != TYPE_ALL) {
ResourceFilter typeFilter = (type == TYPE_DIR) ? DIRECTORY_FILTER : FILE_FILTER;
if (filter == null) filter = typeFilter;
else filter = new AndResourceFilter(new ResourceFilter[] { typeFilter, filter });
}
// create query Object
String[] names = new String[] { "name", "size", "type", "dateLastModified", "attributes", "mode", "directory" };
String[] types = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "DATE", "VARCHAR", "VARCHAR", "VARCHAR" };
boolean hasMeta = directory instanceof ResourceMetaData;
if (hasMeta) {
names = new String[] { "name", "size", "type", "dateLastModified", "attributes", "mode", "directory", "meta" };
types = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "DATE", "VARCHAR", "VARCHAR", "VARCHAR", "OBJECT" };
}
boolean typeArray = (listInfo == LIST_INFO_ARRAY_NAME) || (listInfo == LIST_INFO_ARRAY_PATH);
boolean namesOnly = (listInfo == LIST_INFO_ARRAY_NAME) || (listInfo == LIST_INFO_QUERY_NAME) || (listInfo == LIST_INFO_ARRAY_PATH);
Array array = null;
Object rtn;
Query query = new QueryImpl(namesOnly ? new String[] { "name" } : names, namesOnly ? new String[] { "VARCHAR" } : types, 0, "query");
if (typeArray) {
rtn = array = new ArrayImpl();
}
else {
rtn = query;
}
if (!directory.exists()) {
if (directory instanceof FileResource) return rtn;
throw new ApplicationException("Directory [" + directory.toString() + "] doesn't exist");
}
if (!directory.isDirectory()) {
if (directory instanceof FileResource) return rtn;
throw new ApplicationException("File [" + directory.toString() + "] exists, but isn't a directory");
}
if (!directory.isReadable()) {
if (directory instanceof FileResource) return rtn;
throw new ApplicationException("No access to read directory [" + directory.toString() + "]");
}
long startNS = System.nanoTime();
try {
if (namesOnly) {
if (typeArray) {
_fillArrayPathOrName(array, directory, filter, 0, recurse, (listInfo == LIST_INFO_ARRAY_NAME));
return array;
}
// Query Name, available via the cfdirectory tag but not via directoryList()
if (recurse || type != TYPE_ALL) _fillQueryNamesRec("", query, directory, filter, 0, recurse);
else _fillQueryNames(query, directory, filter, 0);
}
else {
// Query All
_fillQueryAll(query, directory, filter, 0, hasMeta, recurse);
}
}
catch (IOException e) {
throw Caster.toPageException(e);
}
// sort
if (sort != null && query != null) {
String[] arr = sort.toLowerCase().split(",");
for (int i = arr.length - 1; i >= 0; i
try {
String[] col = arr[i].trim().split("\\s+");
if (col.length == 1) query.sort(col[0].trim());
else if (col.length == 2) {
String order = col[1].toLowerCase().trim();
if (order.equals("asc")) query.sort(col[0], lucee.runtime.type.Query.ORDER_ASC);
else if (order.equals("desc")) query.sort(col[0], lucee.runtime.type.Query.ORDER_DESC);
else throw new ApplicationException("Invalid order type [" + col[1] + "]");
}
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
}
query.setExecutionTime(System.nanoTime() - startNS);
if (typeArray) {
java.util.Iterator it = query.getIterator();
while (it.hasNext()) {
Struct row = (Struct) it.next();
if (namesOnly) array.appendEL(row.get("name"));
else array.appendEL(row.get("directory") + lucee.commons.io.FileUtil.FILE_SEPERATOR_STRING + row.get("name"));
}
}
return rtn;
}
public static Struct getInfo(PageContext pc, Resource directory, String serverPassword) throws PageException {
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);
if (!directory.exists()) throw new ApplicationException("Directory [" + directory.toString() + "] doesn't exist");
if (!directory.isDirectory()) throw new ApplicationException("[" + directory.toString() + "] isn't a directory");
if (!directory.canRead()) throw new ApplicationException("No access to read directory [" + directory.toString() + "]");
securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);
Struct sct = new StructImpl();
sct.setEL("directoryName", directory.getName());
sct.setEL(KeyConstants._size, Long.valueOf(directory.length()));
sct.setEL("isReadable", directory.isReadable());
sct.setEL(KeyConstants._path, directory.getAbsolutePath());
sct.setEL("dateLastModified", new DateTimeImpl(pc.getConfig()));
if (SystemUtil.isUnix()) sct.setEL(KeyConstants._mode, new ModeObjectWrap(directory));
File file = new File(Caster.toString(directory));
BasicFileAttributes attr;
try {
attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
sct.setEL("directoryCreated", new DateTimeImpl(pc, attr.creationTime().toMillis(), false));
}
catch (Exception e) {
}
return sct;
}
private static int _fillQueryAll(Query query, Resource directory, ResourceFilter filter, int count, boolean hasMeta, boolean recurse) throws PageException, IOException {
Resource[] list = directory.listResources();
if (list == null || list.length == 0) return count;
String dir = directory.getCanonicalPath();
// fill data to query
// query.addRow(list.length);
boolean isDir;
boolean modeSupported = directory.getResourceProvider().isModeSupported();
for (int i = 0; i < list.length; i++) {
isDir = list[i].isDirectory();
if (filter == null || filter.accept(list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name, count, list[i].getName());
query.setAt(KeyConstants._size, count, new Double(isDir ? 0 : list[i].length()));
query.setAt(KeyConstants._type, count, isDir ? "Dir" : "File");
if (modeSupported) {
query.setAt(MODE, count, new ModeObjectWrap(list[i]));
}
query.setAt(DATE_LAST_MODIFIED, count, new Date(list[i].lastModified()));
// TODO File Attributes are Windows only...
// this is slow as it fetches each the attributes one at a time
query.setAt(ATTRIBUTES, count, getFileAttribute(list[i], true));
if (hasMeta) {
query.setAt(META, count, ((ResourceMetaData) list[i]).getMetaData());
}
query.setAt(DIRECTORY, count, dir);
}
if (recurse && isDir) count = _fillQueryAll(query, list[i], filter, count, hasMeta, recurse);
}
return count;
}
// this method only exists for performance reasion
private static int _fillQueryNames(Query query, Resource directory, ResourceFilter filter, int count) throws PageException {
if (filter == null || filter instanceof ResourceNameFilter) {
ResourceNameFilter rnf = filter == null ? null : (ResourceNameFilter) filter;
String[] list = directory.list();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (rnf == null || rnf.accept(directory, list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name, count, list[i]);
}
}
}
else {
Resource[] list = directory.listResources();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (filter == null || filter.accept(list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name, count, list[i].getName());
}
}
}
return count;
}
private static int _fillQueryNamesRec(String parent, Query query, Resource directory, ResourceFilter filter, int count, boolean recurse) throws PageException {
Resource[] list = directory.listResources();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (filter == null || filter.accept(list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name, count, parent.concat(list[i].getName()));
}
if (recurse && list[i].isDirectory()) count = _fillQueryNamesRec(parent + list[i].getName() + "/", query, list[i], filter, count, recurse);
}
return count;
}
private static int _fillArrayPathOrName(Array arr, Resource directory, ResourceFilter filter, int count, boolean recurse, boolean onlyName) throws PageException {
Resource[] list = directory.listResources();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (filter == null || filter.accept(list[i])) {
arr.appendEL(onlyName ? list[i].getName() : list[i].getAbsolutePath());
count++;
}
if (recurse && list[i].isDirectory()) count = _fillArrayPathOrName(arr, list[i], filter, count, recurse, onlyName);
}
return count;
}
// this method only exists for performance reason
private static int _fillArrayName(Array arr, Resource directory, ResourceFilter filter, int count) {
if (filter == null || filter instanceof ResourceNameFilter) {
ResourceNameFilter rnf = filter == null ? null : (ResourceNameFilter) filter;
String[] list = directory.list();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (rnf == null || rnf.accept(directory, list[i])) {
arr.appendEL(list[i]);
}
}
}
else {
Resource[] list = directory.listResources();
if (list == null || list.length == 0) return count;
for (int i = 0; i < list.length; i++) {
if (filter.accept(list[i])) {
arr.appendEL(list[i].getName());
}
}
}
return count;
}
/**
* create a directory
*
* @throws PageException
*/
public static void actionCreate(PageContext pc, Resource directory, String serverPassword, boolean createPath, int mode, Object acl, String storage, int nameConflict)
throws PageException {
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);
if (directory.exists()) {
if (directory.isDirectory()) {
if (nameConflict == NAMECONFLICT_SKIP) return;
throw new ApplicationException("Directory [" + directory.toString() + "] already exists");
}
else if (directory.isFile()) throw new ApplicationException("Can't create directory [" + directory.toString() + "], a file exists with the same name");
}
// if(!directory.mkdirs()) throw new ApplicationException("can't create directory
// ["+directory.toString()+"]");
try {
directory.createDirectory(createPath);
}
catch (IOException ioe) {
throw Caster.toPageException(ioe);
}
// set S3 stuff
setS3Attrs(pc, directory, acl, storage);
// Set Mode
if (mode != -1) {
try {
directory.setMode(mode);
// FileUtil.setMode(directory,mode);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
}
public static void setS3Attrs(PageContext pc, Resource res, Object acl, String storage) throws PageException {
String scheme = res.getResourceProvider().getScheme();
if ("s3".equalsIgnoreCase(scheme)) {
// ACL
if (acl != null) {
try {
// old way
BIF bif = CFMLEngineFactory.getInstance().getClassUtil().loadBIF(pc, "StoreSetACL");
bif.invoke(pc, new Object[] { res.getAbsolutePath(), acl });
}
catch (Exception e) {
throw Caster.toPageException(e);
}
}
// STORAGE
if (storage != null) {
Reflector.callMethod(res, "setStorage", new Object[] { storage });
}
}
}
public static String improveACL(String acl) throws ApplicationException {
acl = acl.toLowerCase().trim();
if ("public-read".equals(acl)) return "public-read";
if ("publicread".equals(acl)) return "public-read";
if ("public_read".equals(acl)) return "public-read";
if ("public-read-write".equals(acl)) return "public-read-write";
if ("publicreadwrite".equals(acl)) return "public-read-write";
if ("public_read_write".equals(acl)) return "public-read-write";
if ("private".equals(acl)) return "private";
if ("authenticated-read".equals(acl)) return "authenticated-read";
if ("authenticated_read".equals(acl)) return "authenticated-read";
if ("authenticatedread".equals(acl)) return "authenticated-read";
throw new ApplicationException("Invalid acl value, valid values are [public-read, private, public-read-write, authenticated-read]");
}
/**
* delete directory
*
* @param dir
* @param forceDelete
* @throws PageException
*/
public static void actionDelete(PageContext pc, Resource dir, boolean forceDelete, String serverPassword) throws PageException {
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(), dir, serverPassword);
// directory doesn't exist
if (!dir.exists()) {
if (dir.isDirectory()) throw new ApplicationException("Directory [" + dir.toString() + "] doesn't exist");
else if (dir.isFile()) throw new ApplicationException("File [" + dir.toString() + "] doesn't exist and isn't a directory");
}
// check if file
if (dir.isFile()) throw new ApplicationException("Can't delete [" + dir.toString() + "], it isn't a directory, it's a file");
// check directory is empty
Resource[] dirList = dir.listResources();
if (dirList != null && dirList.length > 0 && forceDelete == false)
throw new ApplicationException("Directory [" + dir.toString() + "] is not empty", "set recurse=true to delete sub-directories and files too");
// delete directory
try {
dir.remove(forceDelete);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
* rename a directory to a new Name
*
* @throws PageException
*/
public static String actionRename(PageContext pc, Resource directory, String strNewdirectory, String serverPassword, boolean createPath, Object acl, String storage)
throws PageException {
// check directory
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);
if (!directory.exists()) throw new ApplicationException("The directory [" + directory.toString() + "] doesn't exist");
if (!directory.isDirectory()) throw new ApplicationException("The file [" + directory.toString() + "] exists, but it isn't a directory");
if (!directory.canRead()) throw new ApplicationException("No access to read directory [" + directory.toString() + "]");
if (strNewdirectory == null) throw new ApplicationException("The attribute [newDirectory] is not defined");
// real to source
Resource newdirectory = toDestination(pc, strNewdirectory, directory);
securityManager.checkFileLocation(pc.getConfig(), newdirectory, serverPassword);
if (newdirectory.exists()) throw new ApplicationException("New directory [" + newdirectory.toString() + "] already exists");
if (createPath) {
newdirectory.getParentResource().mkdirs();
}
try {
directory.moveTo(newdirectory);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
throw Caster.toPageException(t);
}
// set S3 stuff
setS3Attrs(pc, newdirectory, acl, storage);
return newdirectory.toString();
}
public static void actionCopy(PageContext pc, Resource directory, String strDestination, String serverPassword, boolean createPath, Object acl, String storage,
final ResourceFilter filter, boolean recurse, int nameconflict) throws PageException {
// check directory
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);
if (!directory.exists()) throw new ApplicationException("Directory [" + directory.toString() + "] doesn't exist");
if (!directory.isDirectory()) throw new ApplicationException("File [" + directory.toString() + "] exists, but isn't a directory");
if (!directory.canRead()) throw new ApplicationException("No access to read directory [" + directory.toString() + "]");
if (StringUtil.isEmpty(strDestination)) throw new ApplicationException("Attribute [destination] is not defined");
// real to source
Resource newdirectory = toDestination(pc, strDestination, directory);
if (nameconflict == NAMECONFLICT_ERROR && newdirectory.exists()) throw new ApplicationException("New directory [" + newdirectory.toString() + "] already exists");
securityManager.checkFileLocation(pc.getConfig(), newdirectory, serverPassword);
try {
boolean clearEmpty = false;
// has already a filter
ResourceFilter f = null;
if (filter != null) {
if (!recurse) {
f = new AndResourceFilter(new ResourceFilter[] { filter, new NotResourceFilter(DirectoryResourceFilter.FILTER) });
}
else {
clearEmpty = true;
f = new OrResourceFilter(new ResourceFilter[] { filter, DirectoryResourceFilter.FILTER });
}
}
else {
if (!recurse) f = new NotResourceFilter(DirectoryResourceFilter.FILTER);
}
if (!createPath) {
Resource p = newdirectory.getParentResource();
if (p != null && !p.exists()) throw new ApplicationException("parent directory for [" + newdirectory + "] doesn't exist");
}
ResourceUtil.copyRecursive(directory, newdirectory, f);
if (clearEmpty) ResourceUtil.removeEmptyFolders(newdirectory, f == null ? null : new NotResourceFilter(filter));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
throw new ApplicationException(t.getMessage());
}
// set S3 stuff
setS3Attrs(pc, newdirectory, acl, storage);
}
private static Resource toDestination(PageContext pageContext, String path, Resource source) {
if (source != null && path.indexOf(File.separatorChar) == -1 && path.indexOf('/') == -1 && path.indexOf('\\') == -1) {
Resource p = source.getParentResource();
if (p != null) return p.getRealResource(path);
}
return ResourceUtil.toResourceNotExisting(pageContext, path);
}
private static String getFileAttribute(Resource file, boolean exists) {
// TODO this is slow as it fetches attributes one at a time
// also Windows only!
return exists && !file.isWriteable() ? "R".concat(file.isHidden() ? "H" : "") : file.isHidden() ? "H" : "";
}
/**
* @param strType the type to set
*/
public void setType(String strType) throws ApplicationException {
if (StringUtil.isEmpty(strType)) return;
type = toType(strType);
}
public static int toType(String strType) throws ApplicationException {
strType = strType.trim().toLowerCase();
if ("all".equals(strType)) return TYPE_ALL;
else if ("dir".equals(strType)) return TYPE_DIR;
else if ("directory".equals(strType)) return TYPE_DIR;
else if ("file".equals(strType)) return TYPE_FILE;
else throw new ApplicationException("Invalid type [" + strType + "], valid types are [all, directory, file]");
}
} |
package org.jeecqrs.events;
/**
* Provides the ability to send events to interested listeners (publish-subscribe).
*
* @param <E> the base message type
*/
public interface EventBus<E> {
/**
* Dispatches and event in the given bucket on the event bus.
*
* @param bucketId the bucket in which the event shall be sent
* @param event the event to dispatch
*/
void dispatch(String bucketId, E event);
} |
package joshie.harvest.animals;
import joshie.harvest.animals.item.ItemAnimalTool.Tool;
import joshie.harvest.animals.tracker.AnimalTrackerServer;
import joshie.harvest.api.HFApi;
import joshie.harvest.api.animals.AnimalAction;
import joshie.harvest.api.animals.AnimalStats;
import joshie.harvest.api.animals.AnimalTest;
import joshie.harvest.core.HFTrackers;
import joshie.harvest.core.entity.EntityBasket;
import joshie.harvest.core.helpers.EntityHelper;
import joshie.harvest.core.util.annotations.HFEvents;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteract;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent;
import static joshie.harvest.core.handlers.BasketHandler.forbidsDrop;
import static joshie.harvest.core.helpers.InventoryHelper.ITEM;
import static joshie.harvest.core.helpers.InventoryHelper.ITEM_STACK;
@HFEvents
@SuppressWarnings("unused")
public class AnimalEvents {
@SubscribeEvent(priority = EventPriority.HIGHEST)
@SuppressWarnings("ConstantConditions")
public void onEntityLoaded(EntityJoinWorldEvent event) {
Entity entity = event.getEntity();
AnimalStats stats = EntityHelper.getStats(entity);
if (stats != null && entity instanceof EntityAnimal) {
if (!entity.world.isRemote) {
stats.setEntity((EntityAnimal)entity);
HFTrackers.<AnimalTrackerServer>getAnimalTracker(event.getWorld()).add(stats);
}
}
}
@SubscribeEvent
@SuppressWarnings("ConstantConditions")
public void onEntityDeath(LivingDeathEvent event) {
AnimalStats stats = EntityHelper.getStats(event.getEntityLiving());
if (stats != null && !event.getEntity().world.isRemote) {
HFTrackers.<AnimalTrackerServer>getAnimalTracker(event.getEntityLiving().world).onDeath(stats);
}
}
@SubscribeEvent
public void onEntityInteract(EntityInteract event) {
AnimalStats stats = EntityHelper.getStats(event.getTarget());
ItemStack stack = event.getItemStack();
if (stats != null && stack != null) {
if (HFApi.animals.canEat(stack, stats.getType().getFoodTypes()) && stats.performAction(event.getWorld(), stack, AnimalAction.FEED)) {
stack.splitStack(1);
event.setCanceled(true);
}
}
}
@SubscribeEvent
public void onEntityAttackedByPlayer(AttackEntityEvent event) {
AnimalStats stats = EntityHelper.getStats(event.getTarget());
if (stats != null) {
stats.affectHappiness(stats.getType().getRelationshipBonus(AnimalAction.HURT));
}
}
@SubscribeEvent
public void onEntityAttacked(LivingAttackEvent event) {
AnimalStats stats = EntityHelper.getStats(event.getEntityLiving());
if (stats != null) {
event.getEntityLiving().addPotionEffect(new PotionEffect(MobEffects.REGENERATION, 200, 0, true, false));
}
}
/* When right clicking poultry, will throw any poultry on your head **/
@HFEvents
public static class PickupPoultry {
public static boolean register() { return HFAnimals.PICKUP_POULTRY; }
private ItemStack[] stacks;
private ItemStack[] getStacks() {
if (stacks != null) return stacks;
stacks = new ItemStack[] {
HFAnimals.TOOLS.getStackFromEnum(Tool.CHICKEN_FEED),
HFAnimals.TOOLS.getStackFromEnum(Tool.MEDICINE)
};
return stacks;
}
private boolean isHolding(ItemStack stack) {
return ITEM_STACK.matchesAny(stack, getStacks()) || ITEM.matchesAny(stack, HFAnimals.TREATS, Items.NAME_TAG);
}
boolean blocksPickup(EntityPlayer player) {
return isHolding(player.getHeldItemMainhand()) || isHolding(player.getHeldItemOffhand()) || player.isSneaking();
}
@SubscribeEvent
public void onEntityInteract(PlayerInteractEvent.EntityInteract event) {
EntityPlayer player = event.getEntityPlayer();
if (!player.isBeingRidden() && !blocksPickup(player)) {
Entity entity = event.getTarget();
AnimalStats stats = EntityHelper.getStats(entity);
if (stats != null && stats.performTest(AnimalTest.CAN_CARRY)) {
entity.setEntityInvulnerable(true);
entity.startRiding(player, true);
}
}
}
@SubscribeEvent
public void onPlayerLoggedOut(PlayerLoggedOutEvent event) {
event.player.getPassengers().stream().filter(entity -> entity instanceof EntityBasket).forEach(entity -> {
AnimalStats stats = EntityHelper.getStats(entity);
entity.dismountRidingEntity();
entity.rotationPitch = event.player.rotationPitch;
entity.rotationYaw = event.player.rotationYaw;
entity.moveRelative(0F, 0.1F, 1.05F);
entity.setEntityInvulnerable(false);
});
}
@SubscribeEvent
@SuppressWarnings("ConstantConditions")
public void onRightClickGround(PlayerInteractEvent.RightClickBlock event) {
EntityPlayer player = event.getEntityPlayer();
if (!forbidsDrop(event.getWorld().getBlockState(event.getPos()).getBlock())) {
for (Entity entity : player.getPassengers()) {
AnimalStats stats = EntityHelper.getStats(entity);
if (stats != null && stats.performTest(AnimalTest.CAN_CARRY)) {
entity.dismountRidingEntity();
entity.rotationPitch = player.rotationPitch;
entity.rotationYaw = player.rotationYaw;
entity.moveRelative(0F, 0.1F, 1.05F);
entity.setEntityInvulnerable(false);
stats.performAction(player.world, null, AnimalAction.DISMOUNT);
}
}
}
}
}
} |
package uk.gov.dvla.core;
import java.util.regex.Pattern;
public final class Validators {
public static final String DLN_REGEX = "^(?=.{16}$)[A-Za-z]{1,5}9{0,4}[0-9](?:[05][1-9]|[16][0-2])(?:[0][1-9]|[12][0-9]|3[01])[0-9](?:99|[A-Za-z][A-Za-z9])(?![IOQYZioqyz01_])\\w[A-Za-z]{2}$";
public static final String POSTCODE_REGEX = "^[a-zA-Z0-9](?:\\s*[a-zA-Z0-9]){4,7}$";
public static final String VRM_REGEX = "^(?:[a-zA-z0-9]){1,15}(?:;(?:[a-zA-z0-9]){1,15})*;?$";
public static final String GUID_REGEX = "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$";
public static final String NINO_REGEX = "^(([A-CEHJ-MOPR-SW-Ya-cehj-mopr-sw-y]|(G(?!B|b))|(N(?!K|k))|(T(?!N|n))|(Z(?!Z|z))|(g(?!B|b))|(n(?!K|k))|(t(?!N|n))|(z(?!Z|z)))[A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z][0-9]{6}[ABCDabcd ])$";
public static final Pattern DLN_PATTERN = Pattern.compile(DLN_REGEX);
public static final Pattern POSTCODE_PATTERN = Pattern.compile(POSTCODE_REGEX);
public static final Pattern VRM_PATTERN = Pattern.compile(VRM_REGEX);
public static final Pattern GUID_PATTERN = Pattern.compile(GUID_REGEX);
public static final Pattern NINO_PATTERN = Pattern.compile(NINO_REGEX);
public static boolean validateDln(final String hex) {
return DLN_PATTERN.matcher(hex).matches();
}
public static boolean validatePostcode(String postcode) {
return POSTCODE_PATTERN.matcher(postcode).matches();
}
public static boolean validateVrm(String vrm) {
return VRM_PATTERN.matcher(vrm.replaceAll("[\\s-]+", "")).matches();
}
public static boolean validateGuid(String guid) {
return GUID_PATTERN.matcher(guid).matches();
}
public static boolean validateProposer(String proposer) {
return proposer.equalsIgnoreCase("P") || proposer.equalsIgnoreCase("N");
}
public static boolean validateNino(String hex) {
return NINO_PATTERN.matcher(hex).matches();
}
} |
package kr.co.leehana.chat.server;
import javax.swing.*;
import java.awt.*;
/**
* @author Hana Lee
* @since 2015-11-13 16-01
*/
public class ServerGui extends JFrame {
private static final long serialVersionUID = 477016551457497985L;
private ServerBackground serverBackground = new ServerBackground(this);
private JTextArea msgArea;
public ServerGui() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(400, 100, 400, 600);
setTitle(" ");
msgArea = new JTextArea(40, 25);
final JTextField msgField = new JTextField(25);
msgField.addActionListener((e) -> {
String msg = msgField.getText() + "\n";
msgArea.append(msg);
msgField.setText("");
});
add(msgArea, BorderLayout.CENTER);
add(msgField, BorderLayout.SOUTH);
setVisible(true);
serverBackground.setting();
}
public static void main(String[] args) {
new ServerGui();
}
public void appendMsg(String clientMsg) {
msgArea.append(clientMsg);
}
} |
package meew0.slotrelay;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
public class TileEntitySlotRelay extends TileEntity {
public int slotExtract, slotInsert;
public TileEntitySlotRelay() {
slotExtract = slotInsert = 0;
}
@Override
public boolean canUpdate() {
return true;
}
private ItemStack addItemStacks(ItemStack stack1, ItemStack stack2) {
ItemStack newStack = stack1.copy();
newStack.stackSize += stack2.stackSize;
return newStack;
}
@Override
public void updateEntity() {
try {
SlotRelay.debug("update");
// Get tile entity to extract from
TileEntity extractTE = worldObj.getTileEntity(xCoord, yCoord + 1, zCoord);
// Make sure it's an inventory
if (extractTE instanceof IInventory) {
SlotRelay.debug("extractTE instanceof IInventory");
IInventory extractInventory = (IInventory) extractTE;
// Get the stack and make sure it exists
ItemStack stack = extractInventory.getStackInSlot(slotExtract);
if (stack == null || stack.stackSize == 0) {
SlotRelay.debug("extractStack is empty");
return;
}
// Get tile entity to insert to
TileEntity insertTE = worldObj.getTileEntity(xCoord, yCoord - 1, zCoord);
if (insertTE instanceof IInventory) {
SlotRelay.debug("insertTE instanceof IInventory");
IInventory insertInventory = (IInventory) insertTE;
ItemStack stackInInsert = insertInventory.getStackInSlot(slotInsert);
// Make sure the stack is valid for the output slot (or the check is disabled in the config)
if (insertInventory.isItemValidForSlot(slotInsert, stack) || SlotRelay.ignoreStackValidity) {
SlotRelay.debug("item valid for slot");
if (stackInInsert == null || stackInInsert.stackSize == 0) {
SlotRelay.debug("insertStack is empty");
// If the stack to insert to doesn't exist, just put the stack to extract from into it...
insertInventory.setInventorySlotContents(slotInsert, stack);
// ...and delete the items in the extract stack
extractInventory.setInventorySlotContents(slotExtract, null);
} else if (stack.isItemEqual(stackInInsert)) {
SlotRelay.debug("items are equal");
// If the items are equal, then make sure the stack to insert to isn't full
if (stackInInsert.stackSize < stackInInsert.getMaxStackSize()) {
SlotRelay.debug("insertStack isn't full");
// If the stack to insert to isn't full, then...
if (stackInInsert.stackSize + stack.stackSize < stackInInsert.getMaxStackSize()) {
SlotRelay.debug("both together aren't full");
// If both stacks together wouldn't make the stack full, then just
// add the two stacks...
insertInventory.setInventorySlotContents(slotInsert,
addItemStacks(stack, stackInInsert));
// ...and delete the stack in the extract slot
extractInventory.setInventorySlotContents(slotExtract, null);
} else {
SlotRelay.debug("both together are full, complicated logic ahead");
// Otherwise remove some items from the extract slot and add them to the insert stack
insertInventory.setInventorySlotContents(slotInsert, addItemStacks(stackInInsert,
extractInventory.decrStackSize(slotExtract, stackInInsert.getMaxStackSize() -
stackInInsert.stackSize)));
}
}
}
}
}
}
} catch(Exception e) {
SlotRelay.log.error("An error has been encountered while processing item transfer! Ignoring");
}
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
slotExtract = nbt.getInteger("slotExtract");
slotInsert = nbt.getInteger("slotInsert");
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
nbt.setInteger("slotExtract", slotExtract);
nbt.setInteger("slotInsert", slotInsert);
}
} |
package mho.wheels.iterables;
import mho.wheels.math.BinaryFraction;
import mho.wheels.math.MathUtils;
import mho.wheels.ordering.Ordering;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.testing.Testing.*;
/**
* <p>A {@code RandomProvider} produces {@code Iterable}s that randomly generate some set of values with a specified
* distribution. A {@code RandomProvider} is deterministic, but not immutable: its state changes every time a random
* value is generated. It may be reverted to its original state with {@link RandomProvider#reset}.</p>
*
* <p>{@code RandomProvider} uses the cryptographically-secure ISAAC pseudorandom number generator, implemented in
* {@link mho.wheels.random.IsaacPRNG}. The source of its randomness is a {@code int[]} seed. It contains two scale
* parameters which some of the distributions depend on; the exact relationship between the parameters and the
* distributions is specified in the distribution's documentation.</p>
*
* <p>To create an instance which shares a generator with {@code this}, use {@link RandomProvider#copy()}. To create
* an instance which copies the generator, use {@link RandomProvider#deepCopy()}.</p>
*
* <p>Note that sometimes the documentation will say things like "returns an {@code Iterable} containing all
* {@code String}s". This cannot strictly be true, since {@link java.util.Random} has a finite period, and will
* therefore produce only a finite number of {@code String}s. So in general, the documentation often pretends that the
* source of randomness is perfect (but still deterministic).</p>
*/
public final strictfp class RandomProvider extends IterableProvider {
/**
* A list of all {@code Ordering}s.
*/
private static final List<Ordering> ORDERINGS = toList(ExhaustiveProvider.INSTANCE.orderings());
/**
* A list of all {@code RoundingMode}s.
*/
private static final List<RoundingMode> ROUNDING_MODES = toList(ExhaustiveProvider.INSTANCE.roundingModes());
/**
* The default value of {@code scale}.
*/
private static final int DEFAULT_SCALE = 32;
/**
* The default value of {@code secondaryScale}.
*/
private static final int DEFAULT_SECONDARY_SCALE = 8;
/**
* Sometimes a "special element" (for example, null) is inserted into an {@code Iterable} with some probability.
* That probability is 1/{@code SPECIAL_ELEMENT_RATIO}.
*/
private static final int SPECIAL_ELEMENT_RATIO = 50;
/**
* A list of numbers which determines exactly which values will be deterministically output over the life of
* {@code this}. It must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.
*/
private final @NotNull List<Integer> seed;
/**
* A pseudorandom number generator. It changes state every time a random number is generated.
*/
private @NotNull IsaacPRNG prng;
/**
* A map containing {@code RandomProvider}s that were created from {@code this} using
* {@link RandomProvider#withScale(int)} and {@link RandomProvider#withSecondaryScale(int)}. The key is a pair
* consisting of {@code scale} and {@code secondaryScale}, respectively. Whenever {@code this}
* is reset with {@link RandomProvider#reset()}, the dependents are reset as well.
*/
private @NotNull Map<Pair<Integer, Integer>, RandomProvider> dependents;
/**
* A parameter that determines the size of some of the generated objects.
*/
private int scale = DEFAULT_SCALE;
/**
* Another parameter that determines the size of some of the generated objects.
*/
private int secondaryScale = DEFAULT_SECONDARY_SCALE;
/**
* Constructs a {@code RandomProvider} with a seed generated from the current system time.
*
* <ul>
* <li>(conjecture) Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be
* constructed with this constructor.</li>
* </ul>
*/
public RandomProvider() {
prng = new IsaacPRNG();
seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
prng = new IsaacPRNG(seed);
dependents = new HashMap<>();
}
/**
* Constructs a {@code RandomProvider} with a given seed.
*
* <ul>
* <li>{@code seed} must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.</li>
* <li>Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be constructed with
* this constructor.</li>
* </ul>
*
* @param seed the source of randomness
*/
public RandomProvider(@NotNull List<Integer> seed) {
if (seed.size() != IsaacPRNG.SIZE) {
throw new IllegalArgumentException("seed must have length mho.wheels.random.IsaacPRNG#SIZE, which is " +
IsaacPRNG.SIZE + ". Length of invalid seed: " + seed.size());
}
this.seed = seed;
prng = new IsaacPRNG(seed);
dependents = new HashMap<>();
}
/**
* A {@code RandomProvider} used for testing. This allows for deterministic testing without manually setting up a
* lengthy seed each time.
*/
public static @NotNull RandomProvider example() {
IsaacPRNG prng = IsaacPRNG.example();
List<Integer> seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
return new RandomProvider(seed);
}
/**
* Returns {@code this}'s scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the scale parameter of {@code this}
*/
public int getScale() {
return scale;
}
/**
* Returns {@code this}'s other scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the other scale parameter of {@code this}
*/
public int getSecondaryScale() {
return secondaryScale;
}
/**
* Returns {@code this}'s seed. Makes a defensive copy.
*
* <ul>
* <li>The result is an array of {@link mho.wheels.random.IsaacPRNG#SIZE} {@code int}s.</li>
* </ul>
*
* @return the seed of {@code this}
*/
public @NotNull List<Integer> getSeed() {
return toList(seed);
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy shares {@code prng} with the original.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
@Override
public @NotNull RandomProvider copy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy receives a new copy of {@code prng},
* so generating values from the copy will not affect the state of the original's {@code prng}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
@Override
public @NotNull RandomProvider deepCopy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng.copy();
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code scale} may be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param scale the new scale
* @return A copy of {@code this} with a new scale
*/
@Override
public @NotNull RandomProvider withScale(int scale) {
Pair<Integer, Integer> key = new Pair<>(scale, secondaryScale);
RandomProvider copy = dependents.get(key);
if (copy == null) {
copy = copy();
copy.scale = scale;
dependents.put(key, copy);
}
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new secondary scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code secondaryScale} mat be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param secondaryScale the new secondary scale
* @return A copy of {@code this} with a new secondary scale
*/
@Override
public @NotNull RandomProvider withSecondaryScale(int secondaryScale) {
Pair<Integer, Integer> key = new Pair<>(scale, secondaryScale);
RandomProvider copy = dependents.get(key);
if (copy == null) {
copy = copy();
copy.secondaryScale = secondaryScale;
dependents.put(key, copy);
}
return copy;
}
/**
* Put the {@code prng} back in its original state. Creating a {@code RandomProvider}, generating some values,
* resetting, and generating the same types of values again will result in the same values. Any
* {@code RandomProvider}s created from {@code this} using {@link RandomProvider#withScale(int)} or
* {@link RandomProvider#withSecondaryScale(int)} (but not {@link RandomProvider#copy} or
* {@link RandomProvider#deepCopy()}) is also reset.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*/
@Override
public void reset() {
prng = new IsaacPRNG(seed);
dependents.values().forEach(mho.wheels.iterables.RandomProvider::reset);
}
/**
* Returns an id which has a good chance of being different in two instances with unequal {@code prng}s. It's used
* in {@link RandomProvider#toString()} to distinguish between different {@code RandomProvider} instances.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code this} may be any {@code long}.</li>
* </ul>
*/
public long getId() {
return prng.getId();
}
/**
* Returns a randomly-generated {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return an {@code int}
*/
public int nextInt() {
return prng.nextInt();
}
/**
* An {@code Iterable} that generates all {@code Integer}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> integers() {
return fromSupplier(this::nextInt);
}
/**
* Returns a randomly-generated {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @return a {@code long}
*/
public long nextLong() {
int a = nextInt();
int b = nextInt();
return (long) a << 32 | b & 0xffffffffL;
}
/**
* An {@code Iterable} that generates all {@code Long}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> longs() {
return fromSupplier(this::nextLong);
}
/**
* Returns a randomly-generated {@code boolean} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @return a {@code boolean}
*/
public boolean nextBoolean() {
return (nextInt() & 1) != 0;
}
/**
* An {@code Iterator} that generates both {@code Boolean}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Boolean> booleans() {
return fromSupplier(this::nextBoolean);
}
private int nextIntPow2(int bits) {
return nextInt() & ((1 << bits) - 1);
}
private @NotNull Iterable<Integer> integersPow2(int bits) {
int mask = (1 << bits) - 1;
return map(i -> i & mask, integers());
}
private long nextLongPow2(int bits) {
return nextLong() & ((1L << bits) - 1);
}
private @NotNull Iterable<Long> longsPow2(int bits) {
long mask = (1L << bits) - 1;
return map(l -> l & mask, longs());
}
private @NotNull BigInteger nextBigIntegerPow2(int bits) {
byte[] bytes = new byte[bits / 8 + 1];
int x = 0;
for (int i = 0; i < bytes.length; i++) {
if (i % 4 == 0) {
x = nextInt();
}
bytes[i] = (byte) x;
x >>= 8;
}
bytes[0] &= (1 << (bits % 8)) - 1;
return new BigInteger(bytes);
}
private @NotNull Iterable<BigInteger> bigIntegersPow2(int bits) {
return fromSupplier(() -> this.nextBigIntegerPow2(bits));
}
private int nextIntBounded(int n) {
int maxBits = MathUtils.ceilingLog2(n);
int i;
do {
i = nextIntPow2(maxBits);
} while (i >= n);
return i;
}
private @NotNull Iterable<Integer> integersBounded(int n) {
return filter(i -> i < n, integersPow2(MathUtils.ceilingLog2(n)));
}
private long nextLongBounded(long n) {
int maxBits = MathUtils.ceilingLog2(n);
long l;
do {
l = nextLongPow2(maxBits);
} while (l >= n);
return l;
}
private @NotNull Iterable<Long> longsBounded(long n) {
return filter(l -> l < n, longsPow2(MathUtils.ceilingLog2(n)));
}
private @NotNull BigInteger nextBigIntegerBounded(@NotNull BigInteger n) {
if (n.equals(BigInteger.ONE)) return BigInteger.ZERO;
int maxBits = MathUtils.ceilingLog2(n);
BigInteger i;
do {
i = nextBigIntegerPow2(maxBits);
} while (ge(i, n));
return i;
}
private @NotNull Iterable<BigInteger> bigIntegersBounded(@NotNull BigInteger n) {
if (n.equals(BigInteger.ONE)) return repeat(BigInteger.ZERO);
return filter(i -> lt(i, n), bigIntegersPow2(MathUtils.ceilingLog2(n)));
}
/**
* Returns a randomly-generated value taken from a given list.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code xs} cannot be empty.</li>
* <li>The result may be any value of type {@code T}, or null.</li>
* </ul>
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return a value from {@code xs}
*/
public <T> T nextUniformSample(@NotNull List<T> xs) {
return xs.get(nextIntBounded(xs.size()));
}
/**
* An {@code Iterable} that uniformly generates elements from a (possibly null-containing) list.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is non-removable and either empty or infinite.</li>
* </ul>
*
* Length is 0 if {@code xs} is empty, infinite otherwise
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return uniformly-distributed elements of {@code xs}
*/
@Override
public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) {
return xs.isEmpty() ? Collections.emptyList() : map(xs::get, integersBounded(xs.size()));
}
/**
* Returns a randomly-generated character taken from a given {@code String}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code s} cannot be empty.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param s the source {@code String}
* @return a {@code char} from {@code s}
*/
public char nextUniformSample(@NotNull String s) {
return s.charAt(nextIntBounded(s.length()));
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s from a {@code String}.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is an empty or infinite non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is 0 if {@code s} is empty, infinite otherwise
*
* @param s the source {@code String}
* @return uniformly-distributed {@code Character}s from {@code s}
*/
@Override
public @NotNull Iterable<Character> uniformSample(@NotNull String s) {
return s.isEmpty() ? Collections.emptyList() : map(s::charAt, integersBounded(s.length()));
}
/**
* Returns a randomly-generated {@code Ordering} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return an {@code Ordering}
*/
public @NotNull Ordering nextOrdering() {
return nextUniformSample(ORDERINGS);
}
/**
* An {@code Iterator} that generates all {@code Ordering}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Ordering> orderings() {
return uniformSample(ORDERINGS);
}
/**
* Returns a randomly-generated {@code RoundingMode} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code RoundingMode}
*/
public @NotNull RoundingMode nextRoundingMode() {
return nextUniformSample(ROUNDING_MODES);
}
/**
* An {@code Iterable} that generates all {@code RoundingMode}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<RoundingMode> roundingModes() {
return uniformSample(ROUNDING_MODES);
}
/**
* Returns a randomly-generated positive {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code byte}
*/
public byte nextPositiveByte() {
byte b;
do {
b = nextNaturalByte();
} while (b == 0);
return b;
}
/**
* An {@code Iterable} that generates all positive {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> positiveBytes() {
return fromSupplier(this::nextPositiveByte);
}
/**
* Returns a randomly-generated positive {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code short}
*/
public short nextPositiveShort() {
short s;
do {
s = nextNaturalShort();
} while (s == 0);
return s;
}
/**
* An {@code Iterable} that generates all positive {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> positiveShorts() {
return fromSupplier(this::nextPositiveShort);
}
/**
* Returns a randomly-generated positive {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code int}
*/
public int nextPositiveInt() {
int i;
do {
i = nextInt();
} while (i <= 0);
return i;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegers() {
return fromSupplier(this::nextPositiveInt);
}
/**
* Returns a randomly-generated positive {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code long}
*/
public long nextPositiveLong() {
long l;
do {
l = nextLong();
} while (l <= 0);
return l;
}
/**
* An {@code Iterable} that generates all positive {@code Long}s from a uniform distribution from a uniform
* distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> positiveLongs() {
return fromSupplier(this::nextPositiveLong);
}
/**
* Returns a randomly-generated negative {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code byte}
*/
public byte nextNegativeByte() {
return (byte) ~nextNaturalByte();
}
/**
* An {@code Iterable} that generates all negative {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> negativeBytes() {
return fromSupplier(this::nextNegativeByte);
}
/**
* Returns a randomly-generated negative {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code short}
*/
public short nextNegativeShort() {
return (short) ~nextNaturalShort();
}
/**
* An {@code Iterable} that generates all negative {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> negativeShorts() {
return fromSupplier(this::nextNegativeShort);
}
/**
* Returns a randomly-generated negative {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code int}
*/
public int nextNegativeInt() {
int i;
do {
i = nextInt();
} while (i >= 0);
return i;
}
/**
* An {@code Iterable} that generates all negative {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> negativeIntegers() {
return fromSupplier(this::nextNegativeInt);
}
/**
* Returns a randomly-generated negative {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code long}
*/
public long nextNegativeLong() {
long l;
do {
l = nextLong();
} while (l >= 0);
return l;
}
/**
* An {@code Iterable} that generates all negative {@code Long}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> negativeLongs() {
return fromSupplier(this::nextNegativeLong);
}
/**
* Returns a randomly-generated natural (non-negative) {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code byte}
*/
public byte nextNaturalByte() {
return (byte) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all natural {@code Byte}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> naturalBytes() {
return fromSupplier(this::nextNaturalByte);
}
/**
* Returns a randomly-generated natural (non-negative) {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code short}
*/
public short nextNaturalShort() {
return (short) nextIntPow2(15);
}
/**
* An {@code Iterable} that generates all natural {@code Short}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> naturalShorts() {
return fromSupplier(this::nextNaturalShort);
}
/**
* Returns a randomly-generated natural (non-negative) {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code int}
*/
public int nextNaturalInt() {
return nextIntPow2(31);
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) from a uniform distribution.
* Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegers() {
return fromSupplier(this::nextNaturalInt);
}
/**
* Returns a randomly-generated natural (non-negative) {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code long}
*/
public long nextNaturalLong() {
return nextLongPow2(63);
}
/**
* An {@code Iterable} that generates all natural {@code Long}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> naturalLongs() {
return fromSupplier(this::nextNaturalLong);
}
/**
* Returns a randomly-generated nonzero {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code byte}
*/
public byte nextNonzeroByte() {
byte b;
do {
b = nextByte();
} while (b == 0);
return b;
}
/**
* Returns a randomly-generated nonzero {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code short}
*/
public short nextNonzeroShort() {
short s;
do {
s = nextShort();
} while (s == 0);
return s;
}
/**
* Returns a randomly-generated nonzero {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code int}
*/
public int nextNonzeroInt() {
int i;
do {
i = nextInt();
} while (i == 0);
return i;
}
/**
* Returns a randomly-generated nonzero {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code long}
*/
public long nextNonzeroLong() {
long l;
do {
l = nextLong();
} while (l == 0L);
return l;
}
/**
* Returns a randomly-generated {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code byte}.</li>
* </ul>
*
* @return a {@code byte}
*/
public byte nextByte() {
return (byte) nextInt();
}
/**
* An {@code Iterable} that generates all {@code Byte}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> bytes() {
return fromSupplier(this::nextByte);
}
/**
* Returns a randomly-generated {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code short}.</li>
* </ul>
*
* @return a {@code short}
*/
public short nextShort() {
return (short) nextInt();
}
/**
* An {@code Iterable} that generates all {@code Short}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> shorts() {
return fromSupplier(this::nextShort);
}
/**
* Returns a randomly-generated ASCII {@code char} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is an ASCII {@code char}.</li>
* </ul>
*
* @return an ASCII {@code char}
*/
public char nextAsciiChar() {
return (char) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all ASCII {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> asciiCharacters() {
return fromSupplier(this::nextAsciiChar);
}
/**
* Returns a randomly-generated {@code char} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @return a {@code char}
*/
public char nextChar() {
return (char) nextInt();
}
/**
* An {@code Iterable} that generates all {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> characters() {
return fromSupplier(this::nextChar);
}
/**
* Returns a randomly-generated {@code byte} greater than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code byte}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code byte}
* @return a {@code byte} greater than or equal to {@code a}
*/
public byte nextFromRangeUp(byte a) {
return (byte) (nextIntBounded((1 << 7) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Byte}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeUp(byte a) {
int offset = 1 << 7;
return map(i -> (byte) (i + a), integersBounded(offset - a));
}
/**
* Returns a randomly-generated {@code short} greater than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code short}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code short}
* @return a {@code short} greater than or equal to {@code a}
*/
public short nextFromRangeUp(short a) {
return (short) (nextIntBounded((1 << 15) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Short}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeUp(short a) {
int offset = 1 << 15;
return map(i -> (short) (i + a), integersBounded(offset - a));
}
/**
* Returns a randomly-generated {@code int} greater than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code int}
* @return an {@code int} greater than or equal to {@code a}
*/
public int nextFromRangeUp(int a) {
return (int) (nextLongBounded((1L << 31) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Integer}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeUp(int a) {
long offset = 1L << 31;
return map(l -> (int) (l + a), longsBounded(offset - a));
}
/**
* Returns a randomly-generated {@code long} greater than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code long}
* @return a {@code long} greater than or equal to {@code a}
*/
public long nextFromRangeUp(long a) {
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(BigInteger.ONE.shiftLeft(63).subtract(ba)).add(ba).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Long}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeUp(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(offset.subtract(BigInteger.valueOf(a)))
);
}
/**
* Returns a randomly-generated {@code char} greater than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code char}
* @return a {@code char} greater than or equal to {@code a}
*/
public char nextFromRangeUp(char a) {
return (char) (nextIntBounded((1 << 16) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Characters}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Character}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeUp(char a) {
int offset = 1 << 16;
return map(i -> (char) (i + a), integersBounded(offset - a));
}
/**
* Returns a randomly-generated {@code byte} less than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code byte}.</li>
* </ul>
*
* @param a the inclusive upper bound of the generated {@code byte}
* @return a {@code byte} less than or equal to {@code a}
*/
public byte nextFromRangeDown(byte a) {
int offset = 1 << 7;
return (byte) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Byte}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeDown(byte a) {
int offset = 1 << 7;
return map(i -> (byte) (i - offset), integersBounded(a + offset + 1));
}
/**
* Returns a randomly-generated {@code short} less than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code short}.</li>
* </ul>
*
* @param a the inclusive upper bound of the generated {@code short}
* @return a {@code short} less than or equal to {@code a}
*/
public short nextFromRangeDown(short a) {
int offset = 1 << 15;
return (short) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Short}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeDown(short a) {
int offset = 1 << 15;
return map(i -> (short) (i - offset), integersBounded(a + offset + 1));
}
/**
* Returns a randomly-generated {@code int} less than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @param a the inclusive upper bound of the generated {@code int}
* @return an {@code int} less than or equal to {@code a}
*/
public int nextFromRangeDown(int a) {
long offset = 1L << 31;
return (int) (nextLongBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Integer}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeDown(int a) {
long offset = 1L << 31;
return map(l -> (int) (l - offset), longsBounded(a + offset + 1));
}
/**
* Returns a randomly-generated {@code long} less than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @param a the inclusive upper bound of the generated {@code long}
* @return a {@code long} less than or equal to {@code a}
*/
public long nextFromRangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(ba.add(BigInteger.ONE).add(offset)).subtract(offset).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Long}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
return map(
i -> i.subtract(offset).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(a).add(BigInteger.ONE).add(offset))
);
}
/**
* Returns a randomly-generated {@code char} less than or equal to {@code a}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param a the inclusive upper bound of the generated {@code char}
* @return a {@code char} less than or equal to {@code a}
*/
public char nextFromRangeDown(char a) {
return (char) nextIntBounded(a + 1);
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Character}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeDown(char a) {
return fromSupplier(() -> nextFromRangeDown(a));
}
/**
* Returns a randomly-generated {@code byte} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>{@code b} may be any {@code byte}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result may be any {@code byte}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code byte}
* @param b the inclusive upper bound of the generated {@code byte}
* @return a {@code byte} between {@code a} and {@code b}, inclusive
*/
public byte nextFromRange(byte a, byte b) {
if (a > b) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
return (byte) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Byte> range(byte a, byte b) {
if (a > b) return Collections.emptyList();
return map(i -> (byte) (i + a), integersBounded((int) b - a + 1));
}
/**
* Returns a randomly-generated {@code short} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>{@code b} may be any {@code short}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result may be any {@code short}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code short}
* @param b the inclusive upper bound of the generated {@code short}
* @return a {@code short} between {@code a} and {@code b}, inclusive
*/
public short nextFromRange(short a, short b) {
if (a > b) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
return (short) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Short> range(short a, short b) {
if (a > b) return Collections.emptyList();
return map(i -> (short) (i + a), integersBounded((int) b - a + 1));
}
/**
* Returns a randomly-generated {@code int} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>{@code b} may be any {@code int}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code int}
* @param b the inclusive upper bound of the generated {@code int}
* @return an {@code int} between {@code a} and {@code b}, inclusive
*/
public int nextFromRange(int a, int b) {
if (a > b) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
return (int) (nextLongBounded((long) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Integer> range(int a, int b) {
if (a > b) return Collections.emptyList();
return map(i -> (int) (i + a), longsBounded((long) b - a + 1));
}
/**
* Returns a randomly-generated {@code long} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>{@code b} may be any {@code long}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code long}
* @param b the inclusive upper bound of the generated {@code long}
* @return a {@code long} between {@code a} and {@code b}, inclusive
*/
public long nextFromRange(long a, long b) {
if (a > b) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
BigInteger ba = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return nextBigIntegerBounded(bb.subtract(ba).add(BigInteger.ONE)).add(ba).longValueExact();
}
public @NotNull Iterable<Long> range(long a, long b) {
if (a > b) return Collections.emptyList();
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(b).subtract(BigInteger.valueOf(a)).add(BigInteger.ONE))
);
}
/**
* Returns a randomly-generated {@code BigInteger} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code BigInteger}.</li>
* <li>{@code b} may be any {@code BigInteger}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code BigInteger}
* @param b the inclusive upper bound of the generated {@code BigInteger}
* @return a {@code BigInteger} between {@code a} and {@code b}, inclusive
*/
public @NotNull BigInteger nextFromRange(@NotNull BigInteger a, @NotNull BigInteger b) {
if (gt(a, b)) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
return nextBigIntegerBounded(b.subtract(a).add(BigInteger.ONE)).add(a);
}
@Override
public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) {
if (gt(a, b)) return Collections.emptyList();
return map(i -> i.add(a), bigIntegersBounded(b.subtract(a).add(BigInteger.ONE)));
}
/**
* Returns a randomly-generated {@code char} between {@code a} and {@code b}, inclusive.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>{@code b} may be any {@code char}.</li>
* <li>{@code a} must be less than or equal to {@code b}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param a the inclusive lower bound of the generated {@code char}
* @param b the inclusive upper bound of the generated {@code char}
* @return a {@code char} between {@code a} and {@code b}, inclusive
*/
public char nextFromRange(char a, char b) {
if (a > b) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + nicePrint(a) +
" and b is " + nicePrint(b) + ".");
}
return (char) (nextIntBounded(b - a + 1) + a);
}
@Override
public @NotNull Iterable<Character> range(char a, char b) {
if (a > b) return Collections.emptyList();
return map(i -> (char) (i + a), integersBounded(b - a + 1));
}
/**
* Returns a randomly-generated positive {@code int} from a geometric distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code int}
*/
public int nextPositiveIntGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
int i;
int j = 0;
do {
i = nextIntBounded(scale);
j++;
} while (i != 0);
return j;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s chosen from a geometric distribution with mean
* {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return () -> new NoRemoveIterator<Integer>() {
private @NotNull Iterator<Integer> is = integersBounded(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
int i;
int j = 0;
do {
i = is.next();
j++;
} while (i != 0);
return j;
}
};
}
/**
* Returns a randomly-generated negative {@code int} from a geometric distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code int}
*/
public int nextNegativeIntGeometric() {
return -nextPositiveIntGeometric();
}
@Override
public @NotNull Iterable<Integer> negativeIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNegativeIntGeometric);
}
/**
* Returns a randomly-generated natural {@code int} from a geometric distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is non-negative.</li>
* </ul>
*
* @return a natural {@code int}
*/
public int nextNaturalIntGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
int i;
int j = 0;
do {
i = nextIntBounded(scale + 1);
j++;
} while (i != 0);
return j - 1;
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) chosen from a geometric
* distribution with mean {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not
* support removal.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing natural {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return map(i -> i - 1, withScale(scale + 1).positiveIntegersGeometric());
}
/**
* Returns a randomly-generated natural {@code int} from a geometric distribution with mean
* {@code numerator}/{@code denominator}.
*
* <ul>
* <li>{@code numerator} must be positive.</li>
* <li>{@code denominator} must be positive.</li>
* <li>The sum of {@code numerator} and {@code denominator} must be less than 2<sup>31</sup>.</li>
* <li>The result is non-negative.</li>
* </ul>
*
* @return a natural {@code int}
*/
private int nextNaturalIntGeometric(int numerator, int denominator) {
if (numerator < 1) {
throw new IllegalArgumentException("numerator must be positive. numerator: " + numerator);
}
if (denominator < 1) {
throw new IllegalArgumentException("denominator must be positive. denominator: " + denominator);
}
long sum = (long) numerator + denominator;
if (sum > Integer.MAX_VALUE) {
throw new IllegalArgumentException("The sum of numerator and denominator must be less than 2^31." +
" numerator is " + numerator + " and denominator is " + denominator + ".");
}
int i;
int j = 0;
do {
i = nextIntBounded((int) sum);
j++;
} while (i >= denominator);
return j - 1;
}
/**
* Returns a randomly-generated nonzero {@code int} from a geometric distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is nonzero.</li>
* </ul>
*
* @return a nonzero {@code int}
*/
public int nextNonzeroIntGeometric() {
int i = nextPositiveIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> nonzeroIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroIntGeometric);
}
/**
* Returns a randomly-generated {@code int} from a geometric distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return a negative {@code int}
*/
public int nextIntGeometric() {
int i = nextNaturalIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> integersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return fromSupplier(this::nextIntGeometric);
}
/**
* Returns a randomly-generated {@code int} whose absolute value is chosen from a geometric distribution with mean
* {@code numerator}/{@code denominator}, and whose sign is chosen uniformly.
*
* <ul>
* <li>{@code numerator} must be positive.</li>
* <li>{@code denominator} must be positive.</li>
* <li>The sum of {@code numerator} and {@code denominator} must be less than 2<sup>31</sup>.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* @return a negative {@code int}
*/
private int nextIntGeometric(int numerator, int denominator) {
int absolute = nextNaturalIntGeometric(numerator, denominator);
return nextBoolean() ? absolute : -absolute;
}
/**
* Returns a randomly-generated {@code int} greater than or equal to {@code a}, chosen from a geometric
* distribution with mean {@code scale}.
*
* <ul>
* <li>{@code this} must have a scale greater than {@code a} and less than {@code Integer.MAX_VALUE}+a.</li>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return an {@code int} greater than or equal to {@code a}
*/
public int nextIntGeometricFromRangeUp(int a) {
if (scale <= a) {
throw new IllegalStateException("this must have a scale greater than a, which is " + a +
". Invalid scale: " + scale);
}
if (a < 1 && scale >= Integer.MAX_VALUE + a) {
throw new IllegalStateException("this must have a scale less than Integer.MAX_VALUE + a, which is " +
(Integer.MAX_VALUE + a));
}
int j;
do {
int i;
j = 0;
do {
i = nextIntBounded(scale - a + 1);
j++;
} while (i != 0);
j += a - 1;
} while (j < a);
return j;
}
/**
* An {@code Iterable} that generates all {@code Integer}s greater than or equal to {@code a}, chosen from a
* geometric distribution with mean {@code scale}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale greater than {@code a} and less than {@code Integer.MAX_VALUE}+a.</li>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> rangeUpGeometric(int a) {
if (scale <= a) {
throw new IllegalStateException("this must have a scale greater than a, which is " + a +
". Invalid scale: " + scale);
}
if (a < 1 && scale >= Integer.MAX_VALUE + a) {
throw new IllegalStateException("this must have a scale less than Integer.MAX_VALUE + a, which is " +
(Integer.MAX_VALUE + a));
}
return filter(j -> j >= a, map(i -> i + a - 1, withScale(scale - a + 1).positiveIntegersGeometric()));
}
public int nextIntGeometricFromRangeDown(int a) {
if (scale >= a) {
throw new IllegalStateException("this must have a scale less than a, which is " + a + ". Invalid scale: " +
scale);
}
if (a > -1 && scale <= a - Integer.MAX_VALUE) {
throw new IllegalStateException("this must have a scale greater than a - Integer.MAX_VALUE, which is " +
(a - Integer.MAX_VALUE));
}
int j;
do {
int i;
j = 0;
do {
i = nextIntBounded(a - scale + 1);
j++;
} while (i != 0);
j = a - j + 1;
} while (j > a);
return j;
}
@Override
public @NotNull Iterable<Integer> rangeDownGeometric(int a) {
if (scale >= a) {
throw new IllegalStateException("this must have a scale less than a, which is " + a + ". Invalid scale: " +
scale);
}
if (a > -1 && scale <= a - Integer.MAX_VALUE) {
throw new IllegalStateException("this must have a scale greater than a - Integer.MAX_VALUE, which is " +
(a - Integer.MAX_VALUE));
}
return filter(j -> j <= a, map(i -> a - i + 1, withScale(a - scale + 1).positiveIntegersGeometric()));
}
/**
* Returns a randomly-generated positive {@code BigInteger}. The bit size is chosen from a geometric distribution
* with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all {@code BigInteger}s with
* that bit size.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code BigInteger}
*/
public @NotNull BigInteger nextPositiveBigInteger() {
int size = nextPositiveIntGeometric();
return nextBigIntegerPow2(size).setBit(size - 1);
}
/**
* An {@code Iterable} that generates all positive {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
public @NotNull Iterable<BigInteger> positiveBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextPositiveBigInteger);
}
/**
* Returns a randomly-generated negative {@code BigInteger}. The bit size is chosen from a geometric distribution
* with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all {@code BigInteger}s with
* that bit size.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code BigInteger}
*/
public @NotNull BigInteger nextNegativeBigInteger() {
return nextPositiveBigInteger().negate();
}
/**
* An {@code Iterable} that generates all negative {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> negativeBigIntegers() {
return map(BigInteger::negate, positiveBigIntegers());
}
/**
* Returns a randomly-generated natural {@code BigInteger}. The bit size is chosen from a geometric distribution
* with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all {@code BigInteger}s with
* that bit size.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is non-negative.</li>
* </ul>
*
* @return a natural {@code BigInteger}
*/
public @NotNull BigInteger nextNaturalBigInteger() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
int size = nextNaturalIntGeometric();
if (size == 0) return BigInteger.ZERO;
return nextBigIntegerPow2(size).setBit(size - 1);
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s (including 0). The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> naturalBigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return fromSupplier(this::nextNaturalBigInteger);
}
/**
* Returns a randomly-generated nonzero {@code BigInteger}. The bit size is chosen from a geometric distribution
* with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all {@code BigInteger}s with
* that bit size.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code BigInteger}
*/
public @NotNull BigInteger nextNonzeroBigInteger() {
BigInteger i = nextPositiveBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all nonzero {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing nonzero {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> nonzeroBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroBigInteger);
}
/**
* Returns a randomly-generated {@code BigInteger}. The bit size is chosen from a geometric distribution with mean
* {@code scale}, and then the {@code BigInteger} is chosen uniformly from all {@code BigInteger}s with that bit
* size.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code BigInteger}
*/
public @NotNull BigInteger nextBigInteger() {
BigInteger i = nextNaturalBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> bigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return fromSupplier(this::nextBigInteger);
}
public @NotNull BigInteger nextFromRangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
int absBitLength = a.abs().bitLength();
int size = nextIntGeometricFromRangeUp(minBitLength);
BigInteger i;
if (size != absBitLength) {
if (size == 0) {
i = BigInteger.ZERO;
} else {
i = nextBigIntegerPow2(size);
boolean mostSignificantBit = i.testBit(size - 1);
if (!mostSignificantBit) {
i = i.setBit(size - 1);
if (size < absBitLength && a.signum() == -1) {
i = i.negate();
}
}
}
} else {
if (a.signum() != -1) {
i = nextBigIntegerBounded(BigInteger.ONE.shiftLeft(absBitLength).subtract(a)).add(a);
} else {
BigInteger b = BigInteger.ONE.shiftLeft(absBitLength - 1);
BigInteger x = nextBigIntegerBounded(b.add(a.negate().subtract(b)).add(BigInteger.ONE));
i = lt(x, b) ? x.add(b) : b.negate().subtract(x.subtract(b));
}
}
return i;
}
@Override
public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return fromSupplier(() -> nextFromRangeUp(a));
}
public @NotNull BigInteger nextFromRangeDown(@NotNull BigInteger a) {
return nextFromRangeUp(a.negate()).negate();
}
@Override
public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) {
int minBitLength = a.signum() == 1 ? 0 : a.negate().bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return map(BigInteger::negate, fromSupplier(() -> nextFromRangeUp(a.negate())));
}
/**
* Returns a randomly-generated positive {@code BinaryFraction}. The mantissa bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd {@code BigInteger}s
* with that bit size. The absolute value of the exponent is chosen from a geometric distribution with mean
* {@code secondaryScale}, and its sign is chosen uniformly.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a positive secondary scale.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code BinaryFraction}
*/
public @NotNull BinaryFraction nextPositiveBinaryFraction() {
return BinaryFraction.of(nextPositiveBigInteger().setBit(0), withScale(secondaryScale).nextIntGeometric());
}
/**
* An {@code Iterable} that generates all positive {@code BinaryFraction}s. The mantissa bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd
* {@code BigInteger}s with that bit size. The absolute value of the exponent is chosen from a geometric
* distribution with mean {@code secondaryScale}, and its sign is chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a positive secondary scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> positiveBinaryFractions() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
if (secondaryScale < 1) {
throw new IllegalStateException("this must have a positive secondaryScale. Invalid secondaryScale: " +
secondaryScale);
}
return fromSupplier(this::nextPositiveBinaryFraction);
}
/**
* Returns a randomly-generated negative {@code BinaryFraction}. The mantissa bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd {@code BigInteger}s
* with that bit size. The absolute value of the exponent is chosen from a geometric distribution with mean
* {@code secondaryScale}, and its sign is chosen uniformly.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a positive secondary scale.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code BinaryFraction}
*/
public @NotNull BinaryFraction nextNegativeBinaryFraction() {
return nextPositiveBinaryFraction().negate();
}
/**
* An {@code Iterable} that generates all negative {@code BinaryFraction}s. The mantissa bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd
* {@code BigInteger}s with that bit size. The absolute value of the exponent is chosen from a geometric
* distribution with mean {@code secondaryScale}, and its sign is chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a secondary scale of at least 1.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> negativeBinaryFractions() {
return map(BinaryFraction::negate, positiveBinaryFractions());
}
/**
* Returns a randomly-generated nonzero {@code BinaryFraction}. The mantissa bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd {@code BigInteger}s
* with that bit size. The absolute value of the exponent is chosen from a geometric distribution with mean
* {@code secondaryScale}, and its sign is chosen uniformly. Finally, the sign of the {@code BinaryFraction} itself
* is chosen uniformly.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a positive secondary scale.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code BinaryFraction}
*/
public @NotNull BinaryFraction nextNonzeroBinaryFraction() {
return nextBoolean() ? nextPositiveBinaryFraction() : nextPositiveBinaryFraction().negate();
}
/**
* An {@code Iterable} that generates all nonzero {@code BinaryFraction}s. The mantissa bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the mantissa is chosen uniformly from all odd
* {@code BigInteger}s with that bit size. The absolute value of the exponent is chosen from a geometric
* distribution with mean {@code secondaryScale}, and its sign is chosen uniformly. Finally, the sign of the
* {@code BinaryFraction} itself is chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2 and a positive secondary scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing nonzero {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> nonzeroBinaryFractions() {
return zipWith((s, bf) -> s ? bf : bf.negate(), booleans(), positiveBinaryFractions());
}
/**
* Returns a randomly-generated {@code BinaryFraction}. The mantissa bit size is chosen from a geometric
* distribution with mean {@code scale}. If the bit size is zero, the {@code BinaryFraction} is zero; otherwise,
* the mantissa is chosen uniformly from all odd {@code BigInteger}s with that bit size, thhe absolute value of the
* exponent is chosen from a geometric distribution with mean {@code secondaryScale}, the exponent's sign is chosen
* uniformly, and, finally, the sign of the {@code BinaryFraction} itself is chosen uniformly.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code BinaryFraction}
*/
public @NotNull BinaryFraction nextBinaryFraction() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (secondaryScale < 1) {
throw new IllegalStateException("this must have a positive secondaryScale. Invalid secondaryScale: " +
secondaryScale);
}
BigInteger mantissa = nextBigInteger();
if (mantissa.equals(BigInteger.ZERO)) {
return BinaryFraction.ZERO;
} else {
int exponent = nextIntGeometric(secondaryScale * (scale + 1), scale);
return BinaryFraction.of(mantissa.setBit(0), exponent);
}
}
/**
* An {@code Iterable} that generates all {@code BinaryFraction}s. The mantissa bit size is chosen from a geometric
* distribution with mean {@code scale}. If the bit size is zero, the {@code BinaryFraction} is zero; otherwise,
* the mantissa is chosen uniformly from all odd {@code BigInteger}s with that bit size, thhe absolute value of the
* exponent is chosen from a geometric distribution with mean {@code secondaryScale}, the exponent's sign is chosen
* uniformly, and, finally, the sign of the {@code BinaryFraction} itself is chosen uniformly. Does not support
* removal.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> binaryFractions() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (secondaryScale < 1) {
throw new IllegalStateException("this must have a positive secondaryScale. Invalid secondaryScale: " +
secondaryScale);
}
return fromSupplier(this::nextBinaryFraction);
}
/**
* Returns a randomly-generated {@code BinaryFraction} greater than or equal to {@code a}. A higher {@code scale}
* corresponds to a higher mantissa bit size and a higher {@code secondaryScale} corresponds to a higher exponent
* bit size, but the exact relationship is not simple to describe.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>{@code a} cannot be null.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code BinaryFraction} greater than or equal to {@code a}
*/
public @NotNull BinaryFraction nextFromRangeUp(@NotNull BinaryFraction a) {
return nextBinaryFraction().abs().add(BinaryFraction.of(a.getMantissa())).shiftLeft(a.getExponent());
}
/**
* An {@code Iterable} that generates all {@code BinaryFraction}s greater than or equal to {@code a}. A higher
* {@code scale} corresponds to a higher mantissa bit size and a higher {@code secondaryScale} corresponds to a
* higher exponent bit size, but the exact relationship is not simple to describe. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>{@code a} cannot be null.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> rangeUp(@NotNull BinaryFraction a) {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (secondaryScale < 1) {
throw new IllegalStateException("this must have a positive secondaryScale. Invalid secondaryScale: " +
secondaryScale);
}
return fromSupplier(() -> nextFromRangeUp(a));
}
/**
* Returns a randomly-generated {@code BinaryFraction} less than or equal to {@code a}. A higher {@code scale}
* corresponds to a higher mantissa bit size and a higher {@code secondaryScale} corresponds to a higher exponent
* bit size, but the exact relationship is not simple to describe.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>{@code a} cannot be null.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code BinaryFraction} less than or equal to {@code a}
*/
public @NotNull BinaryFraction nextFromRangeDown(@NotNull BinaryFraction a) {
return nextFromRangeUp(a.negate()).negate();
}
/**
* An {@code Iterable} that generates all {@code BinaryFraction}s less than or equal to {@code a}. A higher
* {@code scale} corresponds to a higher mantissa bit size and a higher {@code secondaryScale} corresponds to a
* higher exponent bit size, but the exact relationship is not simple to describe. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale and a positive secondary scale.</li>
* <li>{@code a} cannot be null.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BinaryFraction}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BinaryFraction> rangeDown(@NotNull BinaryFraction a) {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (secondaryScale < 1) {
throw new IllegalStateException("this must have a positive secondaryScale. Invalid secondaryScale: " +
secondaryScale);
}
return map(BinaryFraction::negate, rangeUp(a.negate()));
}
public @NotNull BinaryFraction nextFromRange(@NotNull BinaryFraction a, @NotNull BinaryFraction b) {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
if (a.equals(b)) return a;
if (gt(a, b)) {
throw new IllegalArgumentException("a must be less than or equal to b. a is " + a + " and b is " + b +
".");
}
BinaryFraction difference = b.subtract(a);
int division = nextNaturalIntGeometric();
if (division == 0) {
return BinaryFraction.of(
nextFromRange(BigInteger.ZERO, difference.getMantissa()),
difference.getExponent()
).add(a);
} else {
BinaryFraction fraction = BinaryFraction.of(
nextFromRange(
BigInteger.ZERO,
BigInteger.ONE.shiftLeft(division - 1).subtract(BigInteger.ONE)
).shiftLeft(1).add(BigInteger.ONE),
-division
);
return fraction.add(
BinaryFraction.of(
nextFromRange(BigInteger.ZERO, difference.getMantissa().subtract(BigInteger.ONE))
)
).shiftLeft(difference.getExponent()).add(a);
}
}
@Override
public @NotNull Iterable<BinaryFraction> range(@NotNull BinaryFraction a, @NotNull BinaryFraction b) {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
if (gt(a, b)) return Collections.emptyList();
return fromSupplier(() -> nextFromRange(a, b));
}
/**
* Returns a randomly-generated positive {@code float} from a uniform distribution among {@code float}s, including
* {@code Infinity} but not positive zero.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code float}
*/
public float nextPositiveFloat() {
while (true) {
float f = nextFloat();
if (f > 0) return f;
}
}
@Override
public @NotNull Iterable<Float> positiveFloats() {
return filter(f -> f > 0, floats());
}
/**
* Returns a randomly-generated negative {@code float} from a uniform distribution among {@code float}s, including
* {@code -Infinity} but not negative zero.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code float}
*/
public float nextNegativeFloat() {
while (true) {
float f = nextFloat();
if (f < 0) return f;
}
}
@Override
public @NotNull Iterable<Float> negativeFloats() {
return filter(f -> f < 0, floats());
}
/**
* Returns a randomly-generated nonzero {@code float} from a uniform distribution among {@code float}s, including
* {@code Infinity} and {@code -Infinity}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code float}
*/
public float nextNonzeroFloat() {
while (true) {
float f = nextFloat();
if (f != 0) return f;
}
}
@Override
public @NotNull Iterable<Float> nonzeroFloats() {
return filter(f -> f != 0, floats());
}
/**
* Returns a randomly-generated {@code float} from a uniform distribution among {@code float}s, including
* {@code NaN}, positive and negative zeros, {@code Infinity}, and {@code -Infinity}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code float}.</li>
* </ul>
*
* @return a {@code float}
*/
public float nextFloat() {
while (true) {
int floatBits = nextInt();
float f = Float.intBitsToFloat(floatBits);
if (!Float.isNaN(f) || floatBits == 0x7fc00000) return f; //only generate the canonical NaN
}
}
/**
* An {@code Iterable} that generates all {@code Float}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Float> floats() {
return fromSupplier(this::nextFloat);
}
/**
* Returns a randomly-generated positive {@code double} from a uniform distribution among {@code double}s,
* including {@code Infinity} but not positive zero.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code double}
*/
public double nextPositiveDouble() {
while (true) {
double d = nextDouble();
if (d > 0) return d;
}
}
@Override
public @NotNull Iterable<Double> positiveDoubles() {
return filter(d -> d > 0, doubles());
}
/**
* Returns a randomly-generated negative {@code double} from a uniform distribution among {@code double}s,
* including {@code -Infinity} but not negative zero.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code double}
*/
public double nextNegativeDouble() {
while (true) {
double d = nextDouble();
if (d < 0) return d;
}
}
@Override
public @NotNull Iterable<Double> negativeDoubles() {
return filter(d -> d < 0, doubles());
}
/**
* Returns a randomly-generated nonzero {@code double} from a uniform distribution among {@code double}s, including
* {@code Infinity} and {@code -Infinity}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code double}
*/
public double nextNonzeroDouble() {
while (true) {
double d = nextDouble();
if (d != 0) return d;
}
}
@Override
public @NotNull Iterable<Double> nonzeroDoubles() {
return filter(d -> d != 0, doubles());
}
/**
* Returns a randomly-generated {@code double} from a uniform distribution among {@code double}s, including
* {@code NaN}, positive and negative zeros, {@code Infinity}, and {@code -Infinity}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code double}.</li>
* </ul>
*
* @return a {@code double}
*/
public double nextDouble() {
while (true) {
long longBits = nextLong();
double d = Double.longBitsToDouble(longBits);
if (!Double.isNaN(d) || longBits == 0x7ff8000000000000L) return d; //only generate the canonical NaN
}
}
/**
* An {@code Iterable} that generates all {@code Double}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Double> doubles() {
return fromSupplier(this::nextDouble);
}
@Override
public @NotNull Iterable<BigDecimal> positiveBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> negativeBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> bigDecimals() {
return map(p -> new BigDecimal(p.a, p.b), pairs(bigIntegers(), integersGeometric()));
}
public @NotNull <T> Iterable<T> addSpecialElement(@Nullable T x, @NotNull Iterable<T> xs) {
return () -> new Iterator<T>() {
private Iterator<T> xsi = xs.iterator();
private Iterator<Integer> specialSelector = integersBounded(SPECIAL_ELEMENT_RATIO).iterator();
boolean specialSelection = specialSelector.next() == 0;
@Override
public boolean hasNext() {
return specialSelection || xsi.hasNext();
}
@Override
public T next() {
boolean previousSelection = specialSelection;
specialSelection = specialSelector.next() == 0;
return previousSelection ? x : xsi.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) {
return addSpecialElement(null, xs);
}
@Override
public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) {
return addSpecialElement(Optional.<T>empty(), map(Optional::of, xs));
}
@Override
public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) {
return addSpecialElement(NullableOptional.<T>empty(), map(NullableOptional::of, xs));
}
public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairs(
@NotNull Iterable<A> xs,
@NotNull Function<A, Iterable<B>> f
) {
return () -> new NoRemoveIterator<Pair<A, B>>() {
private @NotNull Iterator<A> xsi = xs.iterator();
private @NotNull Map<A, Iterator<B>> map = new HashMap<>();
@Override
public boolean hasNext() {
return true;
}
@Override
public Pair<A, B> next() {
A x = xsi.next();
Iterator<B> ys = map.get(x);
if (ys == null) {
ys = f.apply(x).iterator();
map.put(x, ys);
}
return new Pair<>(x, ys.next());
}
};
}
@Override
public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) {
return zip(as, bs);
}
@Override
public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
return zip3(as, bs, cs);
}
@Override
public
@NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
return zip4(as, bs, cs, ds);
}
@Override
public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
return zip5(as, bs, cs, ds, es);
}
@Override
public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
return zip6(as, bs, cs, ds, es, fs);
}
@Override
public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
return zip7(as, bs, cs, ds, es, fs, gs);
}
@Override
public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(2, xs);
return zip(xss.get(0), xss.get(1));
}
@Override
public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(3, xs);
return zip3(xss.get(0), xss.get(1), xss.get(2));
}
@Override
public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(4, xs);
return zip4(xss.get(0), xss.get(1), xss.get(2), xss.get(3));
}
@Override
public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(5, xs);
return zip5(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4));
}
@Override
public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(6, xs);
return zip6(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5));
}
@Override
public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(7, xs);
return zip7(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5), xss.get(6));
}
@Override
public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) {
if (size == 0) {
return repeat(Collections.emptyList());
} else {
return transpose(demux(size, xs));
}
}
@Override
public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next() + minSize;
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next();
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) {
return map(IterableUtils::charsToString, transpose(demux(size, cs)));
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Collections.singletonList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next() + minSize;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size) {
return strings(size, characters());
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize) {
return stringsAtLeast(minSize, characters());
}
@Override
public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Collections.singletonList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings() {
return strings(characters());
}
@Override
public @NotNull <T> Iterable<List<T>> permutations(@NotNull List<T> xs) {
return () -> new NoRemoveIterator<List<T>>() {
Random random = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
List<T> shuffled = toList(xs);
Collections.shuffle(shuffled, random);
return shuffled;
}
};
}
/**
* Determines whether {@code this} is equal to {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code that} may be any {@code Object}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param that The {@code RandomProvider} to be compared with {@code this}
* @return {@code this}={@code that}
*/
/**
* Calculates the hash code of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>(conjecture) The result may be any {@code int}.</li>
* </ul>
*
* @return {@code this}'s hash code.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RandomProvider that = (RandomProvider) o;
return scale == that.scale && secondaryScale == that.secondaryScale &&
seed.equals(that.seed) && prng.equals(that.prng);
}
@Override
public int hashCode() {
int result = seed.hashCode();
result = 31 * result + prng.hashCode();
result = 31 * result + scale;
result = 31 * result + secondaryScale;
return result;
}
/**
* Creates a {@code String} representation of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>See tests and demos for example results.</li>
* </ul>
*
* @return a {@code String} representation of {@code this}
*/
public String toString() {
return "RandomProvider[@" + getId() + ", " + scale + ", " + secondaryScale + "]";
}
/**
* Ensures that {@code this} is valid. Must return true for any {@code RandomProvider} used outside this class.
*/
public void validate() {
prng.validate();
assertEquals(this, seed.size(), IsaacPRNG.SIZE);
for (Map.Entry<Pair<Integer, Integer>, RandomProvider> entry : dependents.entrySet()) {
Pair<Integer, Integer> key = entry.getKey();
RandomProvider value = entry.getValue();
assertNotNull(this, key);
assertNotNull(this, key.a);
assertNotNull(this, key.b);
assertNotNull(this, value);
assertTrue(this, prng == value.prng);
value.validate();
}
}
} |
package net.alcuria.umbracraft.engine.map;
import net.alcuria.umbracraft.Config;
import net.alcuria.umbracraft.Game;
import net.alcuria.umbracraft.definitions.map.MapDefinition;
import net.alcuria.umbracraft.definitions.tileset.TilesetDefinition;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.Json;
/** An internal representation of a playable, explorable map. It consists largely
* of an array of {@link Layer} objects and an array of {@link TextureRegion}
* objects to render the map.
* @author Andrew Keturi */
public class Map implements Disposable {
private int[][] altMap, typeMap;
// private final BitmapFont font = Game.assets().get("fonts/message.fnt", BitmapFont.class);
private int height;
private Array<Layer> layers;
private int maxAlt;
private String name;
private Array<TextureRegion> tiles;
private TilesetDefinition tilesetDefinition;
private final int tileSide = 1;
private final int tileTop = 2;
private boolean[][] typeFlags;
private int width;
public void create(String id) {
if (id == null) {
throw new NullPointerException("id cannot be null. Perhaps an area node's mapDefinition field is null?");
}
name = id;
// json -> object
Json json = new Json();
tilesetDefinition = Game.db().tileset(0);
String filename = tilesetDefinition.filename;
// create tiles from definition
tiles = new Array<TextureRegion>();
tiles.addAll(getRegions(filename));
// create alt map from definition
final MapDefinition mapDef = Game.db().map(id);
if (mapDef == null) {
throw new NullPointerException("Map not found: " + id);
}
width = mapDef.getWidth();
height = mapDef.getHeight();
altMap = new int[width][height];
typeFlags = new boolean[width][height];
typeMap = new int[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
typeFlags[i][j] = false;
altMap[i][j] = mapDef.tiles.get(i).get(height - j - 1).altitude;
typeMap[i][j] = mapDef.tiles.get(i).get(height - j - 1).type;
if (typeMap[i][j] == 1) {
typeMap[i][j] = tilesetDefinition.terrain1;
} else if (typeMap[i][j] == 2) {
typeMap[i][j] = tilesetDefinition.terrain2;
} else if (typeMap[i][j] == 3) {
typeMap[i][j] = tilesetDefinition.terrain3;
} else if (typeMap[i][j] == 4) {
typeMap[i][j] = tilesetDefinition.terrain4;
} else if (typeMap[i][j] == 5) {
typeMap[i][j] = tilesetDefinition.stairs;
}
}
}
// remove unusable terrain
// for (int i = 0; i < width; i++) {
// for (int j = 0; j < height; j++) {
// if (getAltitudeAt(i - 2, j) < getAltitudeAt(i, j) || getAltitudeAt(i - 1, j) != getAltitudeAt(i, j)) {
// typeMap[i][j] = 0;
// if (getAltitudeAt(i + 2, j) < getAltitudeAt(i, j) || getAltitudeAt(i + 1, j) != getAltitudeAt(i, j)) {
// typeMap[i][j] = 0;
// if (getAltitudeAt(i, j - 2) < getAltitudeAt(i, j) || getAltitudeAt(i, j - 1) != getAltitudeAt(i, j)) {
// typeMap[i][j] = 0;
// if (getAltitudeAt(i, j + 2) < getAltitudeAt(i, j) || getAltitudeAt(i, j + 1) != getAltitudeAt(i, j)) {
// typeMap[i][j] = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
final int terrain = tilesetDefinition.terrain1;
if (typeMap[i][j] == 0 && !typeFlags[i][j]) {
// get surrounding mask
// top topright right rightdown _ down downleft left lefttop
int[] dX = { 0, 1, 1, 1, 0, -1, -1, -1 };
int[] dY = { 1, 1, 0, -1, -1, -1, 0, 1 };
int value = 0b0000_0000;
int mask = 0b1000_0000;
boolean valid = false;
for (int k = 0; k < dX.length; k++) {
System.out.println(String.format("Value: %s mask: %s ", Integer.toBinaryString(value), Integer.toBinaryString(mask)));
if (getTypeAt(i + dX[k], j + dY[k]) == terrain) {
value = value ^ mask;
valid = true;
}
mask = mask >>> 1;
}
if (valid) {
switch (value) {
case 0b0000_0000:
throw new IllegalStateException("Tile marked as valid but has no valid adjacent tiles");
case 0b1000_0000: // top permutations
case 0b1100_0000:
case 0b1000_0001:
case 0b1100_0001:
setTypeAt(i, j, terrain + 16);
break;
case 0b0100_0000:
setTypeAt(i, j, terrain + 15);
break;
case 0b0010_0000: // right permutations
case 0b0110_0000:
case 0b0011_0000:
case 0b0111_0000:
setTypeAt(i, j, terrain - 1);
break;
case 0b0001_0000:
setTypeAt(i, j, terrain - 17);
break;
case 0b0000_1000: // down permutations
case 0b0000_1100:
case 0b0001_1000:
case 0b0001_1100:
setTypeAt(i, j, terrain - 16);
break;
case 0b0000_0100:
setTypeAt(i, j, terrain - 15);
break;
case 0b0000_0010: // left permuatations
case 0b0000_0011:
case 0b0000_0110:
case 0b0000_0111:
setTypeAt(i, j, terrain + 1);
break;
case 0b0000_0001:
setTypeAt(i, j, terrain + 17);
break;
case 0b1000_0011: // top left 3/4ths
case 0b1000_0111:
case 0b1100_0011:
case 0b1100_0111:
setTypeAt(i, j, terrain - 14);
case 0b1110_0000: // top right 3/4ths
case 0b1110_0001:
case 0b1111_0000:
case 0b1111_0001:
setTypeAt(i, j, terrain - 13);
break;
case 0b0011_1000: // down right 3/4ths
case 0b0011_1100:
case 0b0111_1000:
case 0b0111_1100:
setTypeAt(i, j, terrain + 3);
break;
case 0b0000_1110: // down left 3/4ths
case 0b0001_1110:
case 0b0000_1111:
case 0b0001_1111:
setTypeAt(i, j, terrain + 2);
break;
}
//case 0b1101_0000:
//case 0b1000_0101:
typeFlags[i][j] = true;
}
}
}
}
// setTypeAt(i + 1, j + 1, terrain - 15);
// setTypeAt(i - 1, j + 1, terrain - 17);
// setTypeAt(i + 1, j - 1, terrain + 17);
// setTypeAt(i - 1, j - 1, terrain + 15);
// create list of all heights
Array<Integer> heights = new Array<Integer>();
for (int i = 0; i < altMap.length; i++) {
for (int j = 0; j < altMap[0].length; j++) {
if (!heights.contains(Integer.valueOf(altMap[i][j]), false)) {
heights.add(new Integer(altMap[i][j]));
}
}
}
heights.sort();
maxAlt = heights.get(heights.size - 1);
// build the layers
layers = new Array<Layer>();
for (Integer altitude : heights) {
Layer layer = new Layer();
layer.alt = altitude;
layer.data = new Tile[width][height];
for (int i = 0; i < altMap.length; i++) {
for (int j = -getMaxAltitude(); j < altMap[0].length; j++) {
if (getAltitudeAt(i, j) >= altitude) {
if (isInBounds(i, j + altitude)) {
layer.data[i][j + altitude] = new Tile(createEdge(i, j, altitude), layer.alt); // create edge
}
// check if we need to create a wall
if (j - 1 >= 0 && j - 1 < altMap[0].length) {
int drop = (altitude - getAltitudeAt(i, j - 1));
while (drop > 0) {
if (isInBounds(i, (j + altitude) - drop)) {
layer.data[i][(j + altitude) - drop] = new Tile(createWall(i, j, drop, altitude, getAltitudeAt(i, j - 1)), layer.alt);
}
drop
}
}
}
}
}
layers.add(layer);
}
}
private int createEdge(int i, int j, int altitude) {
if (tilesetDefinition == null) {
return 0;
}
// top right down left
int mask = 0b0000;
if (getAltitudeAt(i, j + 1) < altitude) {
mask = mask ^ 0b1000;
}
if (getAltitudeAt(i + 1, j) < altitude) {
mask = mask ^ 0b0100;
}
if (getAltitudeAt(i, j - 1) < altitude) {
mask = mask ^ 0b0010;
}
if (getAltitudeAt(i - 1, j) < altitude) {
mask = mask ^ 0b0001;
}
// now to switch on every possibility
switch (mask) {
case 0b0001:
return tilesetDefinition.edgeLeft;
case 0b0010:
return tilesetDefinition.edgeBottom;
case 0b0100:
return tilesetDefinition.edgeRight;
case 0b1000:
return tilesetDefinition.edgeTop;
case 0b1100:
return tilesetDefinition.edgeTopRight;
case 0b1001:
return tilesetDefinition.edgeTopLeft;
case 0b0110:
return tilesetDefinition.edgeBottomRight;
case 0b0011:
return tilesetDefinition.edgeBottomLeft;
}
//TODO: More cases (0101, 1010, 1111, etc)
return getTypeAt(i, j);
}
private int createWall(int i, int j, int drop, int altitude, int baseAlt) {
if (drop == altitude - baseAlt) {
// lower walls
if (getAltitudeAt(i - 1, j) < altitude) {
return tilesetDefinition.bottomLeftWall;
} else if (getAltitudeAt(i + 1, j) < altitude) {
return tilesetDefinition.bottomRightWall;
} else {
return tilesetDefinition.bottomCenterWall;
}
} else {
// upper walls
if (getAltitudeAt(i - 1, j) < altitude) {
return tilesetDefinition.middleLeftWall;
} else if (getAltitudeAt(i + 1, j) < altitude) {
return tilesetDefinition.middleRightWall;
} else {
return tilesetDefinition.middleCenterWall;
}
}
}
@Override
public void dispose() {
}
/** @param f
* @param g
* @return the altitude at tile f, g */
public float getAltitudeAt(float f, float g) {
return getAltitudeAt((int) f, (int) g);
}
/** Gets the altitude at some tile coordinates and does bounds checking too!
* @param x x tile
* @param y y tile
* @return */
public int getAltitudeAt(int x, int y) {
// clamp to the size of the map so it's assumed tiles outside the map are the same as edge tiles
try {
x = MathUtils.clamp(x, 0, altMap.length - 1);
y = MathUtils.clamp(y, 0, altMap[0].length - 1);
return altMap[x][y];
} catch (NullPointerException npe) {
return 0;
}
}
public TilesetDefinition getDefinition() {
return tilesetDefinition;
}
/** @return the height (not altitude) of the map */
public int getHeight() {
return height;
}
/** @return the tallest altitude on this map */
public int getMaxAltitude() {
return maxAlt;
}
public String getName() {
return name;
}
/** Returns an array of texture regions loaded from the tileset
* @param filename */
private Array<TextureRegion> getRegions(String filename) {
if (filename == null) {
throw new NullPointerException("Tileset filename is null");
}
Array<TextureRegion> regions = new Array<TextureRegion>();
// if (Game.assets().containsAsset("tiles/" + filename)) {
final Texture texture = Game.assets().get("tiles/" + filename, Texture.class);
for (int i = 0; i < Math.pow(Config.tilesetWidth / Config.tileWidth, 2); i++) {
final int x = (i * Config.tileWidth) % Config.tilesetWidth;
final int y = (i / Config.tileWidth) * Config.tileWidth;
final int w = Config.tileWidth;
regions.add(new TextureRegion(texture, x, y, w, w));
}
return regions;
}
/** Gets the terrain yupe at some tile coordinates and does bounds checking
* too!
* @param x x tile
* @param y y tile
* @return */
public int getTypeAt(int x, int y) {
// clamp to the size of the map so it's assumed tiles outside the map are the same as edge tiles
try {
x = MathUtils.clamp(x, 0, altMap.length - 1);
y = MathUtils.clamp(y, 0, altMap[0].length - 1);
return typeMap[x][y];
} catch (NullPointerException npe) {
return 0;
}
}
public int getWidth() {
return width;
}
private boolean isInBounds(int i, int j) {
return i >= 0 && i < altMap.length && j >= 0 && j < altMap[0].length;
}
/** Renders every visible layer.
* @param row the map row to render, in tiles
* @param xOffset the camera offset in tiles, to ensure we only render tiles
* visible in the x axis */
public void render(int row, int xOffset) {
final int tileSize = Config.tileWidth;
if (layers == null) {
return;
}
for (int k = 0; k < layers.size; k++) {
int alt = layers.get(k).alt;
final Tile[][] data = layers.get(k).data;
if (row < 0 || row >= altMap[0].length) {
return;
}
for (int i = xOffset, n = xOffset + Config.viewWidth / Config.tileWidth + 1; i < n; i++) {
// prevents bottom rows from creeping up during rendering
// TODO: make this generic. i think for alts > 0 it will break
int rowRenderHeight = alt == 0 ? 0 : getAltitudeAt(i, row);
for (int j = 0; j <= rowRenderHeight; j++) {
try {
if (i >= 0 && i < data.length && row >= 0 && row < data[i].length && data[i][row + j] != null) {
Game.batch().draw(tiles.get(data[i][row + j].id), (i * tileSize), (row * tileSize) + j * tileSize, tileSize, tileSize);
}
} catch (ArrayIndexOutOfBoundsException e) {
//FIXME: Halp. someting up with rendering very top and very bottom rows.
// Game.log(i + " " + j + " " + row);
}
}
}
}
// for (int i = 0; i < altMap.length; i++) {
// for (int j = 0; j < altMap[0].length; j++) {
// font.draw(Game.batch(), String.valueOf(altMap[i][j]), i * tileSize + 6, j * tileSize + 14);
}
/** Given some tile coordinates, checks if they're valid and the tile type
* there has not been defined., and if so, applies newType to those
* coordinates.
* @param x
* @param y
* @param newType */
private void setTypeAt(int x, int y, int newType) {
if (x >= 0 && x < altMap.length && y >= 0 && y < altMap[0].length && typeMap[x][y] == 0) {
typeMap[x][y] = newType;
}
}
/** Updates the map
* @param delta the time since the last frame */
public void update(float delta) {
}
} |
package net.mgsx.game.plugins.core;
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.core.annotations.PluginDef;
import net.mgsx.game.core.components.Hidden;
import net.mgsx.game.core.plugins.Plugin;
import net.mgsx.game.core.storage.AssetSerializer;
import net.mgsx.game.core.storage.EntityGroupRef;
import net.mgsx.game.core.storage.EntityGroupRefSerializer;
import net.mgsx.game.plugins.core.components.EntityEmitter;
import net.mgsx.game.plugins.core.components.Orientation3D;
import net.mgsx.game.plugins.core.components.PolygonComponent;
import net.mgsx.game.plugins.core.components.ProxyComponent;
import net.mgsx.game.plugins.core.components.Rotate2DAnimation;
import net.mgsx.game.plugins.core.components.SlavePhysics;
import net.mgsx.game.plugins.core.components.Transform2DComponent;
import net.mgsx.game.plugins.core.components.Transform3DComponent;
import net.mgsx.game.plugins.core.storage.ProxySerializer;
import net.mgsx.game.plugins.core.systems.ClearScreenSystem;
import net.mgsx.game.plugins.core.systems.DependencySystem;
import net.mgsx.game.plugins.core.systems.EntityEmitterSystem;
import net.mgsx.game.plugins.core.systems.ExpirySystem;
import net.mgsx.game.plugins.core.systems.Rotation2DSystem;
import net.mgsx.game.plugins.core.systems.Translation3DSystem;
@PluginDef(components={
ProxyComponent.class,
Transform2DComponent.class,
PolygonComponent.class,
Rotate2DAnimation.class,
EntityEmitter.class,
SlavePhysics.class,
Transform3DComponent.class,
Orientation3D.class,
Hidden.class})
public class CorePlugin implements Plugin
{
@Override
public void initialize(GameScreen engine)
{
engine.assets.setLoader(ShaderProgram.class, new ShaderProgramLoader(engine.assets.getFileHandleResolver(), "-vertex.glsl", "-fragment.glsl"));
// basic type serializers
engine.registry.addSerializer(Texture.class, new AssetSerializer<Texture>(Texture.class));
engine.entityEngine.addSystem(new Translation3DSystem());
engine.entityEngine.addSystem(new Rotation2DSystem());
engine.entityEngine.addSystem(new EntityEmitterSystem(engine));
engine.entityEngine.addSystem(new ExpirySystem());
engine.entityEngine.addSystem(new DependencySystem());
engine.entityEngine.addSystem(new ClearScreenSystem());
engine.registry.addSerializer(ProxyComponent.class, new ProxySerializer());
engine.registry.addSerializer(EntityGroupRef.class, new EntityGroupRefSerializer());
}
} |
package nl.b3p.kar.stripes;
import nl.b3p.kar.ExportCreatorThread;
import com.vividsolutions.jts.geom.GeometryCollection;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.tag.BeanFirstPopulationStrategy;
import net.sourceforge.stripes.validation.OneToManyTypeConverter;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import nl.b3p.commons.stripes.CustomPopulationStrategy;
import nl.b3p.incaa.IncaaExport;
import nl.b3p.kar.hibernate.ActivationPointSignal;
import nl.b3p.kar.hibernate.DataOwner;
import nl.b3p.kar.hibernate.Deelgebied;
import nl.b3p.kar.hibernate.Gebruiker;
import nl.b3p.kar.hibernate.Movement;
import nl.b3p.kar.hibernate.MovementActivationPoint;
import nl.b3p.kar.hibernate.RoadsideEquipment;
import nl.b3p.kar.hibernate.VehicleType;
import nl.b3p.kar.inform.CarrierInformerListener;
import nl.b3p.kar.jaxb.KarNamespacePrefixMapper;
import nl.b3p.kar.jaxb.TmiPush;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.EntityTypeConverter;
import org.stripesstuff.stripersist.Stripersist;
/**
* Exporteren van KV9 gegevens.
*
* @author Matthijs Laan
*/
@UrlBinding("/action/export")
@StrictBinding
@CustomPopulationStrategy(BeanFirstPopulationStrategy.class)
public class ExportActionBean implements ActionBean, ValidationErrorHandler {
private final int EXPORT_THRESHOLD = 125;
private static final Log log = LogFactory.getLog(ExportActionBean.class);
private static final String OVERVIEW = "/WEB-INF/jsp/export/overview.jsp";
private ActionBeanContext context;
@Validate(required = true, on = {"exportPtx", "exportXml"})
private RoadsideEquipment rseq;
@Validate(converter = OneToManyTypeConverter.class, on = "export")
private List<Long> rseqs;
private List<RoadsideEquipment> roadsideEquipmentList;
private List<Deelgebied> deelgebieden = new ArrayList();
@Validate(converter = EntityTypeConverter.class, on = {"rseqByDeelgebied"})
private Deelgebied filter;
@Validate(converter = OneToManyTypeConverter.class, on = "export")
private List<DataOwner> dataowner;
@Validate
private Integer karAddress;
@Validate(on = {"export", "allRseqs"})
private String exportType;
@Validate
private String filterType;
@Validate(on = {"rseqByDeelgebied", "allRseqs"})
private boolean onlyValid;
@Validate(on = {"rseqByDeelgebied", "allRseqs"})
private String vehicleType;
@Validate
private boolean onlyReady = true;
@Validate
private boolean doAsync = false;
private List<DataOwner> dataowners = new ArrayList<>();
@Validate(converter = OneToManyTypeConverter.class, on = "adminExport")
private List<DataOwner> dos = new ArrayList<>();
@DefaultHandler
public Resolution overview() {
return new ForwardResolution(OVERVIEW);
}
public Resolution export() throws Exception {
EntityManager em = Stripersist.getEntityManager();
roadsideEquipmentList = new ArrayList();
List<RoadsideEquipment> notReadyForExport = new ArrayList<>();
if (rseqs == null) {
this.context.getValidationErrors().add("Verkeerssystemen", new SimpleError(("Selecteer een of meerdere verkeerssystemen")));
return new ForwardResolution(OVERVIEW);
}
for (Long id : rseqs) {
RoadsideEquipment r = em.find(RoadsideEquipment.class, id);
if (r.isReadyForExport() || !onlyReady) {
r.setVehicleTypeToExport(vehicleType);
roadsideEquipmentList.add(r);
} else {
notReadyForExport.add(r);
}
}
if (!notReadyForExport.isEmpty()) {
String message = "Kan niet exporteren omdat er een of meerdere verkeerssytemen zijn die niet klaar voor export zijn. Pas de selectie aan. De volgende zijn nog niet klaar: ";
for (RoadsideEquipment r : notReadyForExport) {
message += "<br/> " + r.getKarAddress() + " - " + r.getDescription() + ", ";
}
message = message.substring(0, message.length() - 2);
this.context.getValidationErrors().add("export", new SimpleError((message)));
return new ForwardResolution(OVERVIEW);
} else if (exportType == null) {
this.context.getValidationErrors().add("exportType", new SimpleError(("Selecteer een exporttype")));
return new ForwardResolution(OVERVIEW);
} else if (doAsync) {
Gebruiker g = getGebruiker();
if (g.getEmail().isEmpty()) {
this.context.getMessages().add(new SimpleError("E-mailadres is leeg. Kan export niet maken. Neem contact op met het meldpunt van CROW-NDOV."));
return new ForwardResolution(OVERVIEW);
} else {
if (exportType.equals("incaa") || exportType.equals("csvsimple") || exportType.equals("kv9") || exportType.equals("csvextended")) {
String fromAddress = context.getServletContext().getInitParameter("inform.kv7checker.fromAddress");
String appURL = context.getServletContext().getInitParameter("application-url");
String downloadLocation = context.getServletContext().getInitParameter("download.location");
ExportCreatorThread ect = new ExportCreatorThread(exportType, roadsideEquipmentList, g, fromAddress, appURL, downloadLocation);
ect.start();
this.context.getMessages().add(new SimpleMessage("Export wordt op de achtergrond gemaakt. U ontvangt een mail met de export als link."));
return new ForwardResolution(OVERVIEW);
} else {
this.context.getMessages().add(new SimpleError("Export Type is niet bekend", exportType));
return new ForwardResolution(OVERVIEW);
}
}
} else {
switch (exportType) {
case "incaa":
return exportPtx();
case "kv9":
if (roadsideEquipmentList.size() > EXPORT_THRESHOLD) {
this.context.getValidationErrors().add("Aantal", new SimpleError(("Kan maximaal " + EXPORT_THRESHOLD + " VRI's exporteren. Het huidige aantal is " + roadsideEquipmentList.size() + ".")));
return new ForwardResolution(OVERVIEW);
} else {
return exportXml();
}
case "csvsimple":
return exportCSVSimple();
case "csvextended":
return exportCSVExtended();
default:
this.context.getMessages().add(new SimpleError("Export Type is niet bekend", exportType));
return new ForwardResolution(OVERVIEW);
}
}
}
public Resolution exportXml() throws Exception {
ByteArrayOutputStream bos = exportXml(rseq, roadsideEquipmentList);
Date now = new Date();
DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String prefix = "geo-ov_";
if (roadsideEquipmentList.size() == 1) {
prefix = "" + roadsideEquipmentList.get(0).getKarAddress();
}
String filename = prefix + "_kv9_" + sdf.format(now);
return new StreamingResolution("text/xml", new ByteArrayInputStream(bos.toByteArray()))
.setAttachment(true)
.setFilename(filename + ".xml")
.setLength(bos.size());
}
public static ByteArrayOutputStream exportXml(RoadsideEquipment rseq, List<RoadsideEquipment> roadsideEquipmentList) throws Exception{
JAXBContext ctx = JAXBContext.newInstance(TmiPush.class);
Marshaller m = ctx.createMarshaller();
m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new KarNamespacePrefixMapper());
m.setProperty("jaxb.formatted.output", Boolean.TRUE);
/* TODO subscriberId per dataOwner of in gebruikersprofiel instellen/vragen oid */
if (rseq != null) {
roadsideEquipmentList = Arrays.asList(new RoadsideEquipment[]{rseq});
}
TmiPush push = new TmiPush("B3P", roadsideEquipmentList);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
m.marshal(push, bos);
return bos;
}
public Resolution exportPtx() throws Exception {
File f = exportPtx(rseq, roadsideEquipmentList);
if (f != null) {
FileInputStream fis = new FileInputStream(f);
String filename = "HLPXXXXX";
Date now = new Date();
DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename += sdf.format(now);
return new StreamingResolution("text/plain", fis)
.setAttachment(true)
.setFilename(filename + ".ptx")
.setLength(f.length());
} else {
throw new Exception("Could not find roadsideequipments");
}
}
public static File exportPtx(RoadsideEquipment rseq, List<RoadsideEquipment> roadsideEquipmentList){
IncaaExport exporter = new IncaaExport();
File f = null;
if (rseq != null) {
f = exporter.convert(rseq);
} else if (roadsideEquipmentList != null) {
f = exporter.convert(roadsideEquipmentList);
}
return f;
}
public Resolution exportCSVSimple() {
try {
File f = exportCSVSimple(roadsideEquipmentList);
return fileResolution(f);
} catch (IOException ex) {
log.error("Cannot read/write csv file", ex);
return new ErrorResolution(500, "Exporteerproblemen. Raadpleeg CROW-NDOV.");
}
}
public static File exportCSVSimple(List<RoadsideEquipment> roadsideEquipmentList) throws IOException {
Collections.sort(roadsideEquipmentList);
DateFormat stomdateformat = new SimpleDateFormat("dd-MM-yyyy");
File f = File.createTempFile("tmp", "csvsimple.csv");
FileWriter fw = new FileWriter(f);
PrintWriter out = new PrintWriter(fw);
try (CSVPrinter csv = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(';'))) {
csv.printRecord(new Object[]{"Soort verkeerssysteem", "Beheerder", "Beheerdersaanduiding", "Plaats", "Locatie", "Geldig vanaf", "Geldig tot", "KAR-adres",
"RD-X", "RD-Y", "Bevat OV-punten", "Bevat HD-punten", "KV9-validatie", "Gereed voor export"});
for (RoadsideEquipment r : roadsideEquipmentList) {
String vt = r.getVehicleType();
String hasHD = vt == null || vt.equalsIgnoreCase("Gemixt") || r.getVehicleType().equalsIgnoreCase("Hulpdiensten") ? "Ja" : "Nee";
String hasOV = vt == null || vt.equalsIgnoreCase("Gemixt") || r.getVehicleType().equalsIgnoreCase("OV") ? "Ja" : "Nee";
String type;
switch (r.getType()) {
case RoadsideEquipment.TYPE_BAR:
type = "Afsluitsysteem";
break;
case RoadsideEquipment.TYPE_CROSSING:
type = "VRI";
break;
case RoadsideEquipment.TYPE_GUARD:
type = "Bewakingssysteem";
break;
default:
type = "VRI";
break;
}
Object[] values = {type, r.getDataOwner().getOmschrijving(), r.getCrossingCode(), r.getTown(), r.getDescription(),
r.getValidFrom() != null ? stomdateformat.format(r.getValidFrom()) : "", r.getValidUntil() != null ? stomdateformat.format(r.getValidUntil()) : "",
r.getKarAddress(),
(int) Math.round(r.getLocation().getCoordinate().x),
(int) Math.round(r.getLocation().getCoordinate().y),
hasOV, hasHD, r.getValidationErrors() > 0 ? "Bevat fouten" : "OK",
r.isReadyForExport() ? "Ja" : "Nee"};
csv.printRecord(values);
}
csv.flush();
}
return f;
}
public Resolution exportCSVExtended() {
try {
File f = exportCSVExtended(roadsideEquipmentList);
return fileResolution(f);
} catch (IOException ex) {
log.error("Cannot read/write csv file", ex);
return new ErrorResolution(500, "Exporteerproblemen. Raadpleeg CROW-NDOV.");
}
}
public static File exportCSVExtended(List<RoadsideEquipment> roadsideEquipmentList) throws IOException {
DateFormat stomdateformat = new SimpleDateFormat("dd-MM-yyyy");
File f = File.createTempFile("tmp", "csvsimple.csv");
FileWriter fw = new FileWriter(f);
PrintWriter out = new PrintWriter(fw);
CSVPrinter csv = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(';'));
Collections.sort(roadsideEquipmentList);
csv.printRecord(new Object[]{"Soort verkeerssysteem", "Beheerder", "Beheerdersaanduiding", "Plaats", "Locatie", "Geldig vanaf", "Geldig tot",
"KAR-adres", "Signaalgroep", "Richtingen", "Beweging", "Volgnummer beweging", "KAR-punt", "Type melding", "Triggertype", "RD-X", "RD-Y",
"Afstand", "Bus", "Tram", "CVV", "Taxi", "HOV", "Politie", "Brandweer", "Ambulance", "Politie niet in uniform", "Marechaussee",
"Virtual local loop-number",});
for (RoadsideEquipment r : roadsideEquipmentList) {
String type;
switch (r.getType()) {
case RoadsideEquipment.TYPE_BAR:
type = "Afsluitsysteem";
break;
case RoadsideEquipment.TYPE_CROSSING:
type = "VRI";
break;
case RoadsideEquipment.TYPE_GUARD:
type = "Bewakingssysteem";
break;
default:
type = "VRI";
break;
}
SortedSet<Movement> mset = r.getMovements();
List<Movement> ms = new ArrayList<>(mset);
Collections.sort(ms, (o1, o2) -> {
if (o1.getId() == o2.getId()) {
return 0;
} else {
Integer s1 = o1.getSignalGroupNumberOfCheckoutpoint();
Integer s2 = o2.getSignalGroupNumberOfCheckoutpoint();
if (s1 != null && s2 != null) {
return s1.compareTo(s2);
} else {
return o1.getNummer().compareTo(o2.getNummer());
}
}
});
for (Movement m : ms) {
List<MovementActivationPoint> maps = m.getPoints();
String movementLabel = getLabel(m);
for (MovementActivationPoint map : maps) {
String triggerType = "";
if (map.getSignal() != null) {
String tt = map.getSignal().getTriggerType();
switch (tt) {
case ActivationPointSignal.TRIGGER_FORCED:
triggerType = "automatisch";
break;
case ActivationPointSignal.TRIGGER_MANUAL:
triggerType = "handmatig";
break;
case ActivationPointSignal.TRIGGER_STANDARD:
triggerType = "standaard";
break;
default:
triggerType = "";
break;
}
}
Map<String, String> vhts = getVehicleTypes(map);
Object[] values = {
type, r.getDataOwner().getOmschrijving(), r.getCrossingCode(), r.getTown(), r.getDescription(),
r.getValidFrom() != null ? stomdateformat.format(r.getValidFrom()) : "",
r.getValidUntil() != null ? stomdateformat.format(r.getValidUntil()) : "", r.getKarAddress(),
map.getSignal() != null ? map.getSignal().getSignalGroupNumber() : "",
getDirectionLabel(map),
movementLabel,
m.getNummer(),
map.getPoint().getLabel(),
map.getBeginEndOrActivation().equals("END") ? "eind" : map.getBeginEndOrActivation().equals("BEGIN") ? "begin" : map.getSignal().getKarCommandType() == 1 ? "in" : map.getSignal().getKarCommandType() == 2 ? "uit" : "voor",
triggerType,
(int) Math.round(map.getPoint().getLocation().getX()),
(int) Math.round(map.getPoint().getLocation().getY()),
map.getSignal() != null ? map.getSignal().getDistanceTillStopLine() : "",
vhts.getOrDefault("Bus", ""),
vhts.getOrDefault("Tram", ""),
vhts.getOrDefault("CVV", ""),
vhts.getOrDefault("Taxi", ""),
vhts.getOrDefault("Hoogwaardig Openbaar Vervoer (HOV) bus", ""),
vhts.getOrDefault("Politie", ""),
vhts.getOrDefault("Brandweer", ""),
vhts.getOrDefault("Ambulance", ""),
vhts.getOrDefault("Politie niet in uniform", ""),
vhts.getOrDefault("Marechaussee", ""),
map.getSignal() != null ? map.getSignal().getVirtualLocalLoopNumber() : ""};
csv.printRecord(values);
}
}
}
csv.flush();
csv.close();
return f;
}
private static Map<String, String> getVehicleTypes(MovementActivationPoint map){
Map<String, String> mapVhs = new HashMap<>();
if (map.getSignal() != null) {
List<VehicleType> vts = map.getSignal().getVehicleTypes();
for (VehicleType vt : vts) {
mapVhs.put(vt.getOmschrijving(), "x");
}
}
return mapVhs;
}
private static String getDirectionLabel(MovementActivationPoint map){
String label = "";
if(map.getSignal() != null){
String direction = map.getSignal().getDirection();
if(direction == null || direction.isEmpty()){
return label;
}
String[] dirs = direction.split(",");
for (String dir : dirs) {
switch(dir){
case "1":
label += "la-";
break;
case "2":
label += "ra-";
break;
case "3":
label += "rd-";
break;
}
}
if(label.length() > 0){
label = label.substring(0, label.length() - 1);
}
}
return label;
}
private static String getLabel(Movement m){
List<MovementActivationPoint> maps = m.getPoints();
String l ="";
if(maps.size() > 0){
l = maps.get(0).getPoint().getLabel();
if(maps.size() > 1){
l += " - " + maps.get(maps.size()-1).getPoint().getLabel();
}
}
return l;
}
private Resolution fileResolution(File f) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(f);
String filename = "KAR_Geo_Tool_CSV_";
Date now = new Date();
DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename += sdf.format(now);
return new StreamingResolution("text/plain", fis)
.setAttachment(true)
.setFilename(filename + ".csv")
.setLength(f.length());
}
public Resolution adminExport() {
EntityManager em = Stripersist.getEntityManager();
if (context.getRequest().isUserInRole("beheerder")) {
String[] headers = {"dataowner", "totalvri", "vriwithouterrors", "vriwithouterrorsready"};
List<List<String>> values = getExportValues(dos, em);
Resolution response;
if (exportType == null) {
return new ErrorResolution(405, "Verkeerde exporttype meegegeven.");
} else if (exportType.endsWith("JSON")) {
response = exportAdminJSON(values, headers);
} else if (exportType.endsWith("CSV")) {
try {
response = exportAdminCSV(values, headers);
} catch (IOException ex) {
log.error("Cannot read/write csv file", ex);
response = null;
}
} else {
return new ErrorResolution(405, "Verkeerde exporttype meegegeven.");
}
return response;
} else {
return new ErrorResolution(403, "Alleen beheerders mogen deze export maken.");
}
}
public static List<List<String>> getExportValues(List<DataOwner> dos, EntityManager em) {
List<List<String>> values = new ArrayList<>();
for (DataOwner dataOwner : dos) {
List<String> row = new ArrayList<>();
row.add(dataOwner.getOmschrijving());
List<RoadsideEquipment> rseqs = em.createQuery("FROM RoadsideEquipment Where dataOwner = :do", RoadsideEquipment.class).setParameter("do", dataOwner).getResultList();
row.add("" + rseqs.size());
Integer numberNoErrors = 0, numberReady = 0;
for (RoadsideEquipment r : rseqs) {
if (r.getValidationErrors() == 0) {
numberNoErrors++;
if (r.isReadyForExport()) {
numberReady++;
}
}
}
row.add("" + numberNoErrors);
row.add("" + numberReady);
values.add(row);
}
return values;
}
private Resolution exportAdminJSON(List<List<String>> values, String[] headers) {
JSONObject response = new JSONObject();
response.put("success", Boolean.FALSE);
JSONArray data = new JSONArray();
for (List<String> row : values) {
JSONObject j = new JSONObject();
for (int i = 0; i < row.size(); i++) {
String value = row.get(i);
String key = headers[i];
j.put(key, value);
}
data.put(j);
}
response.put("items", data);
response.put("success", Boolean.TRUE);
return new StreamingResolution("application/json", new StringReader(response.toString(4)));
}
private Resolution exportAdminCSV(List<List<String>> values, Object[] headers) throws IOException {
final File f = getAdminExport(values);
return new StreamingResolution("text/plain") {
@Override
public void stream(HttpServletResponse response) throws Exception {
FileInputStream fis = new FileInputStream(f);
OutputStream out = response.getOutputStream();
try {
IOUtils.copy(fis, out);
out.flush();
} finally {
fis.close();
out.close();
f.delete();
}
}
}.setAttachment(true).setFilename("export.csv");
}
public static File getAdminExport(List<List<String>> values) throws IOException {
File f = File.createTempFile("tmp", "adminExport");
FileWriter fw = new FileWriter(f);
PrintWriter out = new PrintWriter(fw);
CSVPrinter csv = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(';'));
csv.printRecord(new Object[]{"Beheerder", "Totaal VRI\'s", "VRI's zonder KV9-fouten", "VRI's zonder KV9-fouten en gereed voor export"});
csv.printRecords(values);
csv.flush();
csv.close();
return f;
}
// <editor-fold desc="RSEQ resolutions" defaultstate="collapsed">
public Resolution rseqByDeelgebied() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
JSONObject info = new JSONObject();
info.put("success", Boolean.FALSE);
try {
Session sess = (Session) em.getDelegate();
GeometryCollection deelgebiedPoly = filter.getGeom();
String query = "from RoadsideEquipment where intersects(location, ?) = true";
if(exportType == null || !exportType.equals("csvsimple")){
query += " and validation_errors = 0";
}
if (onlyReady) {
query += " and readyForExport = true";
}
Query q = sess.createQuery(query);
q.setParameter(0, deelgebiedPoly);
List<RoadsideEquipment> rseqList = (List<RoadsideEquipment>) q.list();
JSONArray rseqArray = makeRseqArray(rseqList);
info.put("rseqs", rseqArray);
info.put("success", Boolean.TRUE);
} catch (Exception e) {
log.error("search rseq exception", e);
info.put("error", ExceptionUtils.getMessage(e));
}
return new StreamingResolution("application/json", new StringReader(info.toString(4)));
}
public Resolution rseqByKarAddress() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
JSONObject info = new JSONObject();
info.put("success", Boolean.FALSE);
try {
String query = "from RoadsideEquipment where karAddress = :karAddress";
if(exportType == null || !exportType.equals("csvsimple")){
query += " and validation_errors = 0";
}
if (onlyReady) {
query += " and readyForExport = true";
}
List<RoadsideEquipment> r = em.createQuery(query).setParameter("karAddress", karAddress).getResultList();
JSONArray rseqArray = makeRseqArray(r);
info.put("rseqs", rseqArray);
info.put("success", Boolean.TRUE);
} catch (JSONException e) {
log.error("search rseq exception", e);
info.put("error", ExceptionUtils.getMessage(e));
}
return new StreamingResolution("application/json", new StringReader(info.toString(4)));
}
public Resolution rseqByDataowner() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
JSONObject info = new JSONObject();
info.put("success", Boolean.FALSE);
try {
String query = "from RoadsideEquipment where dataOwner in :dataowner";
if(exportType == null || !exportType.equals("csvsimple")){
query += " and validation_errors = 0";
}
if (onlyReady) {
query += " and readyForExport = true";
}
List<RoadsideEquipment> rseqs = em.createQuery(query).setParameter("dataowner", dataowner).getResultList();
JSONArray rseqArray = makeRseqArray(rseqs);
info.put("rseqs", rseqArray);
info.put("success", Boolean.TRUE);
} catch (Exception e) {
log.error("search rseq exception", e);
info.put("error", ExceptionUtils.getMessage(e));
}
return new StreamingResolution("application/json", new StringReader(info.toString(4)));
}
public Resolution allRseqs() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
JSONObject info = new JSONObject();
info.put("success", Boolean.FALSE);
try {
String query = "from RoadsideEquipment";
if(exportType == null || !exportType.equals("csvsimple")){
query += " where validation_errors = 0";
}
if (onlyReady) {
if(exportType != null && exportType.equals("csvsimple")){
query += " where ";
}else{
query += " and ";
}
query += "readyForExport = true";
}
List<RoadsideEquipment> rseqList = em.createQuery(query, RoadsideEquipment.class).getResultList();
JSONArray rseqArray = makeRseqArray(rseqList);
info.put("rseqs", rseqArray);
info.put("success", Boolean.TRUE);
} catch (Exception e) {
log.error("search rseq exception", e);
info.put("error", ExceptionUtils.getMessage(e));
}
return new StreamingResolution("application/json", new StringReader(info.toString(4)));
}
// </editor-fold>
@Before(stages = LifecycleStage.BindingAndValidation)
public void lists() throws Exception {
EntityManager em = Stripersist.getEntityManager();
deelgebieden = em.createQuery("from Deelgebied where gebruiker = :geb order by id").setParameter("geb", getGebruiker()).getResultList();
dataowners = em.createQuery("from DataOwner order by omschrijving").getResultList();
}
private JSONArray makeRseqArray(List<RoadsideEquipment> rseqs) throws JSONException {
JSONArray rseqArray = new JSONArray();
for (RoadsideEquipment rseqObj : rseqs) {
if (getGebruiker().canRead(rseqObj)) {
if (onlyValid && !rseqObj.isValid()) {
continue;
}
if(vehicleType == null || vehicleType.equalsIgnoreCase(VehicleType.VEHICLE_TYPE_GEMIXT) || rseqObj.getVehicleType().equalsIgnoreCase(vehicleType) || rseqObj.getVehicleType().equalsIgnoreCase(VehicleType.VEHICLE_TYPE_GEMIXT)){
JSONObject jRseq = new JSONObject();
jRseq.put("id", rseqObj.getId());
jRseq.put("naam", rseqObj.getDescription());
jRseq.put("karAddress", rseqObj.getKarAddress());
jRseq.put("dataowner", rseqObj.getDataOwner().getOmschrijving());
String type = rseqObj.getType();
if (type.equalsIgnoreCase("CROSSING")) {
jRseq.put("type", "VRI");
} else if (type.equalsIgnoreCase("BAR")) {
jRseq.put("type", "Afsluitingssysteem");
} else if (type.equalsIgnoreCase("GUARD")) {
jRseq.put("type", "Waarschuwingssyteem");
}
rseqArray.put(jRseq);
}
}
}
return rseqArray;
}
@Override
public Resolution handleValidationErrors(ValidationErrors errors) throws Exception {
return null;
}
// <editor-fold defaultstate="collapsed" desc="Getters and Setters">
public Gebruiker getGebruiker() {
final String attribute = this.getClass().getName() + "_GEBRUIKER";
Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute);
if (g != null) {
return g;
}
Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal();
g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId());
getContext().getRequest().setAttribute(attribute, g);
return g;
}
@Override
public ActionBeanContext getContext() {
return context;
}
@Override
public void setContext(ActionBeanContext context) {
this.context = context;
}
public List<Deelgebied> getDeelgebieden() {
return deelgebieden;
}
public void setDeelgebieden(List<Deelgebied> deelgebieden) {
this.deelgebieden = deelgebieden;
}
public String getExportType() {
return exportType;
}
public void setExportType(String exportType) {
this.exportType = exportType;
}
public List<Long> getRseqs() {
return rseqs;
}
public void setRseqs(List<Long> rseqs) {
this.rseqs = rseqs;
}
public Deelgebied getFilter() {
return filter;
}
public void setFilter(Deelgebied filter) {
this.filter = filter;
}
public String getFilterType() {
return filterType;
}
public void setFilterType(String filterType) {
this.filterType = filterType;
}
public boolean isOnlyValid() {
return onlyValid;
}
public void setOnlyValid(boolean onlyValid) {
this.onlyValid = onlyValid;
}
public String getVehicleType() {
return vehicleType;
}
public void setVehicleType(String vehicleType) {
this.vehicleType = vehicleType;
}
public RoadsideEquipment getRseq() {
return rseq;
}
public void setRseq(RoadsideEquipment rseq) {
this.rseq = rseq;
}
public List<DataOwner> getDataowners() {
return dataowners;
}
public void setDataowners(List<DataOwner> dataowners) {
this.dataowners = dataowners;
}
public List<DataOwner> getDataowner() {
return dataowner;
}
public void setDataowner(List<DataOwner> dataowner) {
this.dataowner = dataowner;
}
public boolean isOnlyReady() {
return onlyReady;
}
public void setOnlyReady(boolean onlyReady) {
this.onlyReady = onlyReady;
}
public List<DataOwner> getDos() {
return dos;
}
public void setDos(List<DataOwner> dos) {
this.dos = dos;
}
public Integer getKarAddress() {
return karAddress;
}
public void setKarAddress(Integer karAddress) {
this.karAddress = karAddress;
}
public boolean isDoAsync() {
return doAsync;
}
public void setDoAsync(boolean doAsync) {
this.doAsync = doAsync;
}
// </editor-fold>
} |
package nl.mpi.kinnate.svg;
import java.awt.geom.AffineTransform;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import org.apache.batik.bridge.UpdateManager;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
public class SvgUpdateHandler {
private GraphPanel graphPanel;
private KinTermSavePanel kinTermSavePanel;
private boolean dragUpdateRequired = false;
private boolean threadRunning = false;
private int updateDragNodeX = 0;
private int updateDragNodeY = 0;
private float[][] dragRemainders = null;
protected SvgUpdateHandler(GraphPanel graphPanelLocal, KinTermSavePanel kinTermSavePanelLocal) {
graphPanel = graphPanelLocal;
kinTermSavePanel = kinTermSavePanelLocal;
}
protected void updateSvgSelectionHighlights() {
if (kinTermSavePanel != null) {
String kinTypeStrings = "";
for (String entityID : graphPanel.selectedGroupId) {
if (kinTypeStrings.length() != 0) {
kinTypeStrings = kinTypeStrings + "|";
}
kinTypeStrings = kinTypeStrings + graphPanel.getKinTypeForElementId(entityID);
}
if (kinTypeStrings != null) {
kinTermSavePanel.setSelectedKinTypeSting(kinTypeStrings);
}
}
UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager();
if (updateManager != null) { // todo: there may be issues related to the updateManager being null, this should be looked into if symptoms arise.
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
if (graphPanel.doc != null) {
// for (String groupString : new String[]{"EntityGroup", "LabelsGroup"}) {
// Element entityGroup = graphPanel.doc.getElementById(groupString);
{
Element entityGroup = graphPanel.doc.getElementById("EntityGroup");
for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityId = idAttrubite.getTextContent();
System.out.println("group id: " + entityId);
Node existingHighlight = null;
// find any existing highlight
for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) {
if ("rect".equals(subGoupNode.getLocalName())) {
Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id");
if (subGroupIdAttrubite != null) {
if ("highlight".equals(subGroupIdAttrubite.getTextContent())) {
existingHighlight = subGoupNode;
}
}
}
}
if (!graphPanel.selectedGroupId.contains(entityId)) {
// remove all old highlights
if (existingHighlight != null) {
currentChild.removeChild(existingHighlight);
}
// add the current highlights
} else {
if (existingHighlight == null) {
// svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
// System.out.println("bbox X: " + bbox.getX());
// System.out.println("bbox Y: " + bbox.getY());
// System.out.println("bbox W: " + bbox.getWidth());
// System.out.println("bbox H: " + bbox.getHeight());
Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect");
int paddingDistance = 20;
symbolNode.setAttribute("id", "highlight");
symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance));
symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance));
symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2));
symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2));
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("stroke-width", "1");
if (graphPanel.selectedGroupId.indexOf(entityId) == 0) {
symbolNode.setAttribute("stroke-dasharray", "3");
symbolNode.setAttribute("stroke-dashoffset", "0");
} else {
symbolNode.setAttribute("stroke-dasharray", "6");
symbolNode.setAttribute("stroke-dashoffset", "0");
}
symbolNode.setAttribute("stroke", "blue");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;"
// + "stroke-dasharray:1, 1;stroke-dashoffset:0");
currentChild.appendChild(symbolNode);
}
}
}
}
}
}
}
}
});
}
}
protected void dragCanvas(int updateDragNodeXLocal, int updateDragNodeYLocal) {
AffineTransform at = new AffineTransform();
at.translate(updateDragNodeXLocal, updateDragNodeYLocal);
at.concatenate(graphPanel.svgCanvas.getRenderingTransform());
graphPanel.svgCanvas.setRenderingTransform(at);
}
protected void startDrag() {
// dragRemainders is used to store the remainder after snap between drag updates
dragRemainders = null;
}
protected void updateDragNode(int updateDragNodeXLocal, int updateDragNodeYLocal) {
UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager();
synchronized (SvgUpdateHandler.this) {
dragUpdateRequired = true;
updateDragNodeX += updateDragNodeXLocal;
updateDragNodeY += updateDragNodeYLocal;
if (!threadRunning) {
threadRunning = true;
updateManager.getUpdateRunnableQueue().invokeLater(getRunnable());
}
}
}
private Runnable getRunnable() {
return new Runnable() {
public void run() {
if (dragRemainders == null) {
dragRemainders = new float[graphPanel.selectedGroupId.size()][];
for (int dragCounter = 0; dragCounter < dragRemainders.length; dragCounter++) {
dragRemainders[dragCounter] = new float[]{0, 0};
}
}
boolean continueUpdating = true;
while (continueUpdating) {
continueUpdating = false;
int updateDragNodeXInner;
int updateDragNodeYInner;
synchronized (SvgUpdateHandler.this) {
dragUpdateRequired = false;
updateDragNodeXInner = updateDragNodeX;
updateDragNodeYInner = updateDragNodeY;
updateDragNodeX = 0;
updateDragNodeY = 0;
}
// System.out.println("updateDragNodeX: " + updateDragNodeXInner);
// System.out.println("updateDragNodeY: " + updateDragNodeYInner);
if (graphPanel.doc == null || graphPanel.dataStoreSvg.graphData == null) {
GuiHelper.linorgBugCatcher.logError(new Exception("graphData or the svg document is null, is this an old file format? try redrawing before draging."));
} else {
boolean allRealtionsSelected = true;
relationLoop:
for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) {
if (selectedEntity.isVisible
&& graphPanel.selectedGroupId.contains(selectedEntity.getUniqueIdentifier())) {
for (EntityRelation entityRelation : selectedEntity.getVisiblyRelateNodes()) {
EntityData relatedEntity = entityRelation.getAlterNode();
if (relatedEntity.isVisible && !graphPanel.selectedGroupId.contains(relatedEntity.getUniqueIdentifier())) {
allRealtionsSelected = false;
break relationLoop;
}
}
}
}
int dragCounter = 0;
for (String entityId : graphPanel.selectedGroupId) {
// store the remainder after snap for re use on each update
dragRemainders[dragCounter] = graphPanel.entitySvg.moveEntity(graphPanel.doc, entityId, updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, allRealtionsSelected);
dragCounter++;
}
// Element entityGroup = doc.getElementById("EntityGroup");
// for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
// if ("g".equals(currentChild.getLocalName())) {
// Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
// if (idAttrubite != null) {
// String entityPath = idAttrubite.getTextContent();
// if (selectedGroupElement.contains(entityPath)) {
// SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
//// ((SVGLocatable) currentDraggedElement).g
// // drageboth x and y
//// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeYInner - bbox.getY()) + ")");
// // limit drag to x only
// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", 0)");
//// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeXInner));
//// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeYInner));
// // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
//// System.out.println("bbox X: " + bbox.getX());
//// System.out.println("bbox Y: " + bbox.getY());
//// System.out.println("bbox W: " + bbox.getWidth());
//// System.out.println("bbox H: " + bbox.getHeight());
//// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned
//// SVGLocatable.getTransformToElement()
//// SVGPoint.matrixTransform()
int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); // graphPanel.dataStoreSvg.graphData.gridHeight);
int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); // graphPanel.dataStoreSvg.graphData.gridWidth);
new RelationSvg().updateRelationLines(graphPanel, graphPanel.selectedGroupId, graphPanel.svgNameSpace, hSpacing, vSpacing);
//new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
}
synchronized (SvgUpdateHandler.this) {
continueUpdating = dragUpdateRequired;
if (!continueUpdating) {
threadRunning = false;
}
}
}
}
};
}
public void addLabel(final String labelString, final float xPos, final float yPos) {
UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager();
if (updateManager != null) {
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
Element labelGroup = graphPanel.doc.getElementById("LabelsGroup");
Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text");
labelText.setAttribute("x", Float.toString(xPos));
labelText.setAttribute("y", Float.toString(yPos));
labelText.setAttribute("fill", "black");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "28");
labelText.setAttribute("id", "label" + labelGroup.getChildNodes().getLength());
Text textNode = graphPanel.doc.createTextNode(labelString);
labelText.appendChild(textNode);
// todo: put this into a geometry group and allow for selection and drag
labelGroup.appendChild(labelText);
// graphPanel.doc.getDocumentElement().appendChild(labelText);
((EventTarget) labelText).addEventListener("mousedown", new MouseListenerSvg(graphPanel), false);
}
});
}
}
} |
package no.difi.sdp.client2.domain;
import no.digipost.api.representations.AvsenderOrganisasjonsnummer;
public class Avsender {
private final AvsenderOrganisasjonsnummer organisasjonsnummer;
private String avsenderIdentifikator;
private String fakturaReferanse;
public Avsender(AvsenderOrganisasjonsnummer organisasjonsnummer) {
this.organisasjonsnummer = organisasjonsnummer;
}
public String getAvsenderIdentifikator() {
return avsenderIdentifikator;
}
public String getFakturaReferanse() {
return fakturaReferanse;
}
public AvsenderOrganisasjonsnummer getOrganisasjonsnummer() {
return organisasjonsnummer;
}
public static Builder builder(AvsenderOrganisasjonsnummer organisasjonsnummer) {
return new Builder(organisasjonsnummer);
}
public static class Builder {
private final Avsender target;
private boolean built = false;
private Builder(AvsenderOrganisasjonsnummer organisasjonsnummer) {
target = new Avsender(organisasjonsnummer);
}
public Builder fakturaReferanse(String fakturaReferanse) {
target.fakturaReferanse = fakturaReferanse;
return this;
}
public Builder avsenderIdentifikator(String avsenderIdentifikator) {
target.avsenderIdentifikator = avsenderIdentifikator;
return this;
}
public Avsender build() {
if (built) throw new IllegalStateException("Kan ikke bygges flere ganger.");
built = true;
return this.target;
}
}
} |
// Tapestry Web Application Framework
// Howard Lewis Ship
// mailto:hship@users.sf.net
// This library is free software.
// You may redistribute it and/or modify it under the terms of the GNU
// included with this distribution, you may find a copy at the FSF web
// Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
package net.sf.tapestry;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Category;
import net.sf.tapestry.parse.ComponentTemplate;
import net.sf.tapestry.parse.TemplateToken;
import net.sf.tapestry.parse.TokenType;
import net.sf.tapestry.spec.ComponentSpecification;
/**
* Base implementation for most components that use an HTML template.
*
* @author Howard Lewis Ship
* @version $Id$
**/
public class BaseComponent extends AbstractComponent
{
/**
* @deprecated to be remoaved after 2.1
*
**/
protected static final int OUTER_INIT_SIZE = 5;
/**
*
* @deprecated to be removed after 2.1, use {@link IComponent#renderWrapped(IMarkupWriter, IRequestCycle)}.
*
**/
protected int outerCount = 0;
/**
*
* @deprecated to be removed after 2.1, use {@link IComponent#renderWrapped(IMarkupWriter, IRequestCycle)}.
*
**/
protected IRender[] outer;
private static final Category CAT =
Category.getInstance(BaseComponent.class);
/**
* A class used with invisible localizations. Constructed
* from {@link TokenType#LOCALIZATION} {@link TemplateToken}s.
*
* @since 2.0.4
*
**/
private class LocalizedStringRender implements IRender
{
private String key;
private Map attributes;
private LocalizedStringRender(String key, Map attributes)
{
this.key = key;
this.attributes = attributes;
}
public void render(IMarkupWriter writer, IRequestCycle cycle)
throws RequestCycleException
{
if (cycle.isRewinding())
return;
if (attributes != null)
{
writer.begin("span");
Iterator i = attributes.entrySet().iterator();
while (i.hasNext())
{
Map.Entry entry = (Map.Entry) i.next();
String attributeName = (String) entry.getKey();
String attributeValue = (String) entry.getValue();
writer.attribute(attributeName, attributeValue);
}
}
writer.print(getString(key));
if (attributes != null)
writer.end();
}
public String toString()
{
StringBuffer buffer = new StringBuffer("LocalizedStringRender@");
buffer.append(Integer.toHexString(hashCode()));
buffer.append('[');
buffer.append(key);
if (attributes != null)
{
buffer.append(' ');
buffer.append(attributes);
}
buffer.append(']');
return buffer.toString();
}
}
/**
* Adds an element as an outer element for the receiver. Outer
* elements are elements that should be directly rendered by the
* receiver's <code>render()</code> method. That is, they are
* top-level elements on the HTML template.
*
* @deprecated to be marked private after 2.1
*
**/
protected void addOuter(IRender element)
{
if (outer == null)
{
outer = new IRender[OUTER_INIT_SIZE];
outer[0] = element;
outerCount = 1;
return;
}
// No more room? Make the array bigger.
if (outerCount == outer.length)
{
IRender[] newOuter;
newOuter = new IRender[outer.length * 2];
System.arraycopy(outer, 0, newOuter, 0, outerCount);
outer = newOuter;
}
outer[outerCount++] = element;
}
/**
*
* Reads the receiver's template and figures out which elements wrap which
* other elements.
*
* <P>This is coded as a single, big, ugly method for efficiency.
*
* @deprecated to be marked private after 2.1
**/
protected void readTemplate(IPageLoader loader) throws PageLoaderException
{
ComponentTemplate componentTemplate;
Set seenIds = new HashSet();
IPageSource pageSource = loader.getEngine().getPageSource();
if (CAT.isDebugEnabled())
CAT.debug(this +" reading template");
try
{
ITemplateSource source = loader.getTemplateSource();
componentTemplate = source.getTemplate(this);
}
catch (ResourceUnavailableException ex)
{
throw new PageLoaderException(
Tapestry.getString("BaseComponent.unable-to-obtain-template"),
this,
ex);
}
int count = componentTemplate.getTokenCount();
// The stack can never be as large as the number of tokens, so this is safe.
IComponent[] componentStack = new IComponent[count];
IComponent activeComponent = null;
int stackx = 0;
for (int i = 0; i < count; i++)
{
TemplateToken token = componentTemplate.getToken(i);
TokenType type = token.getType();
if (type == TokenType.TEXT)
{
addText(activeComponent, token);
continue;
}
if (type == TokenType.OPEN)
{
IComponent component =
addStartComponent(
activeComponent,
token,
pageSource,
seenIds);
componentStack[stackx++] = activeComponent;
activeComponent = component;
continue;
}
if (type == TokenType.CLOSE)
{
try
{
activeComponent = componentStack[--stackx];
}
catch (IndexOutOfBoundsException ex)
{
// This is now almost impossible to reach, because the
// TemplateParser does a great job of checking for most of these cases.
throw new PageLoaderException(
Tapestry.getString(
"BaseComponent.unbalanced-close-tags"),
this);
}
continue;
}
if (type == TokenType.LOCALIZATION)
{
addStringLocalization(activeComponent, token);
continue;
}
}
// This is also pretty much unreachable, and the message is kind of out
// of date, too.
if (stackx != 0)
throw new PageLoaderException(
Tapestry.getString("BaseComponent.unbalance-open-tags"),
this);
checkAllComponentsReferenced(seenIds);
if (CAT.isDebugEnabled())
CAT.debug(this +" finished reading template");
}
/** @since 2.1-beta-2 **/
private void addStringLocalization(
IComponent activeComponent,
TemplateToken token)
{
IRender renderer =
new LocalizedStringRender(token.getId(), token.getAttributes());
if (activeComponent == null)
addOuter(renderer);
else
activeComponent.addWrapped(renderer);
}
/** @since 2.1-beta-2 **/
private IComponent addStartComponent(
IComponent activeComponent,
TemplateToken token,
IPageSource pageSource,
Set seenIds)
throws PageLoaderException, BodylessComponentException
{
String id = token.getId();
IComponent component = null;
try
{
component = getComponent(id);
}
catch (NoSuchComponentException ex)
{
throw new PageLoaderException(
Tapestry.getString(
"BaseComponent.undefined-embedded-component",
getExtendedId(),
id),
this,
ex);
}
// Make sure the template contains each component only once.
if (seenIds.contains(id))
throw new PageLoaderException(
Tapestry.getString(
"BaseComponent.multiple-component-references",
getExtendedId(),
id),
this);
seenIds.add(id);
if (activeComponent == null)
addOuter(component);
else
{
// If you use a <jwc> tag in the template, you can get here.
// If you use a normal tag and a jwcid attribute, the
// body is automatically editted out.
if (!activeComponent.getSpecification().getAllowBody())
throw new BodylessComponentException(activeComponent);
activeComponent.addWrapped(component);
}
addStaticBindings(component, token.getAttributes(), pageSource);
return component;
}
/** @since 2.1-beta-2 **/
private void addText(IComponent activeComponent, TemplateToken token)
throws BodylessComponentException
{
// Get a render for the token. This allows the token and the render
// to be shared across sessions.
IRender element = token.getRender();
if (activeComponent == null)
addOuter(element);
else
{
// The new template parser edits text out automatically;
// this code probably can't be reached.
if (!activeComponent.getSpecification().getAllowBody())
throw new BodylessComponentException(activeComponent);
activeComponent.addWrapped(element);
}
}
/**
* Adds static bindings for any attrributes specified in the HTML
* template, skipping any that are reserved (explicitly, or
* because they match a formal parameter name).
*
**/
private void addStaticBindings(
IComponent component,
Map attributes,
IPageSource pageSource)
{
if (attributes == null || attributes.isEmpty())
return;
ComponentSpecification spec = component.getSpecification();
boolean rejectInformal = !spec.getAllowInformalParameters();
Iterator i = attributes.entrySet().iterator();
while (i.hasNext())
{
Map.Entry e = (Map.Entry) i.next();
String name = (String) e.getKey();
// If matches a formal parameter name, allow it to be set
// unless there's already a binding.
boolean isFormal = (spec.getParameter(name) != null);
if (isFormal)
{
if (component.getBinding(name) != null)
continue;
}
else
{
// Skip informal parameters if the component doesn't allow them.
if (rejectInformal)
continue;
// If the name is reserved (matches a formal parameter
// or reserved name, caselessly), then skip it.
if (spec.isReservedParameterName(name))
continue;
}
String value = (String) e.getValue();
IBinding binding = pageSource.getStaticBinding(value);
component.setBinding(name, binding);
}
}
private void checkAllComponentsReferenced(Set seenIds)
throws PageLoaderException
{
Set ids = null;
// First, contruct a modifiable copy of the ids of all expected components
// (that is, components declared in the specification).
Map components = getComponents();
// Occasionally, a component will have a template but no embedded components.
if (components == null)
ids = Collections.EMPTY_SET;
else
ids = components.keySet();
// If the seen ids ... ids referenced in the template, matches
// all the ids in the specification then we're fine.
if (seenIds.containsAll(ids))
return;
// Create a modifiable copy. Remove the ids that are referenced in
// the template. The remainder are worthy of note.
ids = new HashSet(ids);
ids.removeAll(seenIds);
int count = ids.size();
String key =
(count == 1)
? "BaseComponent.missing-component-spec-single"
: "BaseComponent.missing-component-spec-multi";
StringBuffer buffer =
new StringBuffer(Tapestry.getString(key, getExtendedId()));
Iterator i = ids.iterator();
int j = 1;
while (i.hasNext())
{
if (j == 1)
buffer.append(' ');
else if (j == count)
{
buffer.append(' ');
buffer.append(Tapestry.getString("BaseComponent.and"));
buffer.append(' ');
}
else
buffer.append(", ");
buffer.append(i.next());
j++;
}
buffer.append('.');
throw new PageLoaderException(buffer.toString(), this);
}
/**
* Renders the top level components contained by the receiver.
*
* @since 2.0.3
**/
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
throws RequestCycleException
{
if (CAT.isDebugEnabled())
CAT.debug("Begin render " + getExtendedId());
for (int i = 0; i < outerCount; i++)
outer[i].render(writer, cycle);
if (CAT.isDebugEnabled())
CAT.debug("End render " + getExtendedId());
}
/**
* Loads the template for the component, and invokes
* {@link #finishLoad()}. Subclasses must invoke this method first,
* before adding any additional behavior, though its usually
* simpler to override {@link #finishLoad()} instead.
*
**/
public void finishLoad(
IPageLoader loader,
ComponentSpecification specification)
throws PageLoaderException
{
readTemplate(loader);
finishLoad();
}
} |
package controller.configuration;
import hochberger.utilities.files.checker.FileChecker;
import hochberger.utilities.files.checker.aspects.ExistingFolderFileAspect;
import hochberger.utilities.properties.LoadProperties;
import hochberger.utilities.text.Text;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import model.NuFiImage;
import com.google.common.collect.Iterables;
import controller.NuFiApplication;
public class NuFiConfiguration {
private final Properties properties;
private NuFiConfiguration(final Properties properties) {
super();
this.properties = properties;
}
public File getSourceFolder() {
return new File(getCustomProperty(NuFiConfigurationConstants.SOURCE_FOLDER));
}
public String getChannelSeparator() {
return getCustomProperty(NuFiConfigurationConstants.CHANNEL_SEPARATOR);
}
public Iterable<String> getChannelDesignators() {
final String channelsProperty = getCustomProperty(NuFiConfigurationConstants.USED_CHANNELS);
final String channelSeparator = NuFiConfigurationConstants.CHANNEL_SEPARATOR;
return Text.trimAll(Text.toIterable(channelsProperty, channelSeparator));
}
public String getImageFiletype() {
return getCustomProperty(NuFiConfigurationConstants.CHANNEL_FILETYPE);
}
public NuFiImage getNuFiImage() {
final ChannelFileBuilder fileBuilder = new ChannelFileBuilder(this.properties);
return fileBuilder.getNuFiImage();
}
public String getCustomProperty(final String key) {
if (!this.properties.containsKey(key)) {
throw new MissingConfigurationEntryException(key);
}
return this.properties.getProperty(key);
}
public static NuFiConfiguration createFrom(final String filePath) throws IOException, ConfigurationException {
final Properties properties = LoadProperties.fromExtern(filePath);
validateProperties(properties);
return new NuFiConfiguration(properties);
}
private static void validateProperties(final Properties properties) throws ConfigurationException {
validateEntryExistence(properties);
validateSourceFolderExistence(properties);
validateChannelExistence(properties);
}
private static void validateEntryExistence(final Properties properties) throws InvalidConfigurationException {
final List<String> missingEntries = new LinkedList<String>();
for (final String key : NuFiConfigurationConstants.MANDATORY_ENTRIES) {
if (Text.empty().equals(properties.getProperty(key, Text.empty()))) {
missingEntries.add(key);
}
}
if (!missingEntries.isEmpty()) {
throw new InvalidConfigurationException(Text.fromIterable(missingEntries, ", "));
}
NuFiApplication.getLogger().info("Configuration keys are okay.");
}
private static void validateSourceFolderExistence(final Properties properties) throws MissingSourceFolderException {
final FileChecker fileChecker = new FileChecker(sourceFolder(properties));
fileChecker.addFileAspect(new ExistingFolderFileAspect());
if (!fileChecker.check()) {
throw new MissingSourceFolderException(Text.fromIterable(fileChecker.getResultDescriptions(), ", "));
}
NuFiApplication.getLogger().info("Source folder is okay.");
}
private static File sourceFolder(final Properties properties) {
return new File(properties.getProperty(NuFiConfigurationConstants.SOURCE_FOLDER));
}
private static void validateChannelExistence(final Properties properties) throws MissingChannelFilesException {
final String channelsProperty = properties.getProperty(NuFiConfigurationConstants.USED_CHANNELS);
final String channelSeparator = NuFiConfigurationConstants.CHANNEL_SEPARATOR;
final Iterable<String> channels = Text.trimAll(Text.toIterable(channelsProperty, channelSeparator));
final ChannelFileBuilder builder = new ChannelFileBuilder(properties);
final Iterable<File> channelFiles = builder.getChannelFiles();
if (Iterables.size(channelFiles) != Iterables.size(channels)) {
throw new MissingChannelFilesException("Number of expected channels does not match actual number.\nExpected channels: " + channelsProperty + "\nfound: "
+ Text.fromIterable(channelFiles, ", "));
}
NuFiApplication.getLogger().info("Channel files are okay.");
NuFiApplication.getLogger().info("Using: " + Text.fromIterable(channelFiles, ", "));
}
public static class ConfigurationException extends Exception {
private static final long serialVersionUID = -4487918431701008904L;
public ConfigurationException(final String message) {
super(message);
}
}
public static class InvalidConfigurationException extends ConfigurationException {
private static final long serialVersionUID = 3651037404940742635L;
public InvalidConfigurationException(final String missingKeys) {
super("There are missing keys in the configuration: " + missingKeys);
}
}
public static class MissingSourceFolderException extends ConfigurationException {
private static final long serialVersionUID = 5203928823071388289L;
public MissingSourceFolderException(final String description) {
super("Source folder error: " + description);
}
}
public static class MissingChannelFilesException extends ConfigurationException {
private static final long serialVersionUID = 5203928823071388289L;
public MissingChannelFilesException(final String description) {
super("Channel files error: " + description);
}
}
public static class MissingConfigurationEntryException extends RuntimeException {
public MissingConfigurationEntryException(final String key) {
super("Configuration lacks desired key: '" + key + "'.");
}
}
} |
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JPanel;
public class Game extends JPanel implements KeyListener, ActionListener {
private static final long serialVersionUID = 469989049178129651L;
public ArrayList<WorldObject> objects;
private static final double SPEED = 50;
private static final double REDUCED_SPEED = SPEED / Context.TICK;
private Context ctx;
private AffineTransform cannonTransform;
private WorldObject cannonBody;
private WorldObject cannonBarrel;
Game() {
addKeyListener(this);
objects = new ArrayList<>();
cannonTransform = new AffineTransform();
cannonBody = new WorldObject(new Ellipse2D.Double(0, 0, 100, 100),
cannonTransform);
cannonBarrel = new WorldObject(new Rectangle2D.Double(30, 40, 100, 20),
cannonTransform);
cannonBarrel.setColor(new Color(0x9E, 0x9E, 0x9E));
cannonBody.setColor(new Color(0x60, 0x7D, 0x8B));
cannonTransform.translate(100, 100);
objects.add(cannonBarrel);
objects.add(cannonBody);
}
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawString("Time: " + System.currentTimeMillis(), 100, 100);
objects.forEach((o) -> {
o.render(g);
});
}
public void tick() {
// cannonTransform.translate(10.0 / Context.TICK, 0);
// cannonTransform.rotate(Math.PI / Context.TICK, 50, 50);
if (this.isVisible()) {
repaint();
}
}
public Context getContext() {
return ctx;
}
public void setContext(Context ctx) {
this.ctx = ctx;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_W:
cannonTransform.translate(SPEED, 0);
break;
case KeyEvent.VK_A:
break;
case KeyEvent.VK_S:
break;
case KeyEvent.VK_D:
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void actionPerformed(ActionEvent e) {
}
} |
package org.apdplat.word.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author
*/
public class WordConfTools {
private static final Logger LOGGER = LoggerFactory.getLogger(WordConfTools.class);
private static final Map<String, String> conf = new HashMap<>();
public static void set(String key, String value){
conf.put(key, value);
}
public static boolean getBoolean(String key, boolean defaultValue){
String value = conf.get(key) == null ? Boolean.valueOf(defaultValue).toString() : conf.get(key);
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("" + key + "=" + value);
}
return value.contains("true");
}
public static boolean getBoolean(String key){
return getBoolean(key, false);
}
public static int getInt(String key, int defaultValue){
int value = conf.get(key) == null ? defaultValue : Integer.parseInt(conf.get(key).trim());
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("" + key + "=" + value);
}
return value;
}
public static int getInt(String key){
return getInt(key, -1);
}
public static String get(String key, String defaultValue){
String value = conf.get(key) == null ? defaultValue : conf.get(key);
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("" + key + "=" + value);
}
return value;
}
public static String get(String key){
String value = conf.get(key);
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("" + key + "=" + value);
}
return value;
}
static{
reload();
}
public static void reload(){
conf.clear();
LOGGER.info("");
long start = System.currentTimeMillis();
loadConf("word.conf");
loadConf("word.local.conf");
checkSystemProperties();
long cost = System.currentTimeMillis() - start;
LOGGER.info(""+cost+" "+conf.size());
LOGGER.info("");
AtomicInteger i = new AtomicInteger();
conf.keySet().stream().sorted().forEach(key -> {
LOGGER.info(i.incrementAndGet()+""+key+"="+conf.get(key));
});
}
/**
*
* @param confFile
*/
public static void forceOverride(String confFile) {
File file = new File(confFile);
try(InputStream in = new FileInputStream(file)){
LOGGER.info(" "+file.getAbsolutePath()+" ");
loadConf(in);
} catch (Exception ex) {
LOGGER.error("", ex);
}
int i=1;
for(String key : conf.keySet()){
LOGGER.info((i++)+""+key+"="+conf.get(key));
}
}
/**
*
* @param confFile
*/
private static void loadConf(String confFile) {
InputStream in = WordConfTools.class.getClassLoader().getResourceAsStream(confFile);
if(in == null){
LOGGER.info(""+confFile);
return;
}
LOGGER.info(""+confFile);
loadConf(in);
}
/**
*
* @param in
*/
private static void loadConf(InputStream in) {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"))){
String line;
while((line = reader.readLine()) != null){
line = line.trim();
if("".equals(line) || line.startsWith("
continue;
}
int index = line.indexOf("=");
if(index==-1){
LOGGER.error(""+line);
continue;
}
//K V
if(index>0 && line.length()>index+1) {
String key = line.substring(0, index).trim();
String value = line.substring(index + 1, line.length()).trim();
conf.put(key, value);
}
else if(index>0 && line.length()==index+1) {
String key = line.substring(0, index).trim();
conf.put(key, "");
}else{
LOGGER.error(""+line);
}
}
} catch (IOException ex) {
System.err.println(":"+ex.getMessage());
throw new RuntimeException(ex);
}
}
private static void checkSystemProperties() {
for(String key : conf.keySet()){
String value = System.getProperty(key);
if(value != null){
conf.put(key, value);
LOGGER.info(""+key+"="+value);
}
}
}
public static void main(String[] args){
}
} |
package org.voovan.tools;
import org.voovan.db.CallType;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.Map.Entry;
public class TSQL {
/**
* SQL , SQL
* @param sqlStr sql (select * from table where x=::x and y=::y)
* @return sql ([:x,:y])
*/
public static List<String> getSqlParamNames(String sqlStr){
String[] params = TString.searchByRegex(sqlStr, "::\\w+\\b");
ArrayList<String> sqlParamNames = new ArrayList<String>();
for(String param : params){
sqlParamNames.add(param);
}
return sqlParamNames;
}
/**
* preparedStatement sql (?)
* @param sqlStr sql (select * from table where x=:x and y=::y)
* @return :? (select * from table where x=? and y=?)
*/
public static String preparedSql(String sqlStr){
return TString.fastReplaceAll(sqlStr, "::\\w+\\b", "?");
}
/**
* preparedStatement
*
* @param preparedStatement preparedStatement
* @param sqlParamNames sql
* @param params Map
* @throws SQLException SQL
*/
public static void setPreparedParams(PreparedStatement preparedStatement,List<String> sqlParamNames,Map<String, ?> params) throws SQLException{
for(int i=0;i<sqlParamNames.size();i++){
String paramName = sqlParamNames.get(i);
paramName = paramName.substring(2,paramName.length());
Object data = params.get(paramName);
if(data==null){
throw new NullPointerException("SQL param: "+paramName+ " is null");
}
if(TReflect.isBasicType(data.getClass())) {
preparedStatement.setObject(i + 1, params.get(paramName));
}else{
//,, JSON
preparedStatement.setObject(i + 1, JSON.toJSON(params.get(paramName)));
}
}
}
/**
* PreparedStatement
* @param conn
* @param sqlStr sql
* @param params Map
* @return PreparedStatement
* @throws SQLException SQL
*/
public static PreparedStatement createPreparedStatement(Connection conn,String sqlStr,Map<String, Object> params) throws SQLException{
List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr);
sqlStr = TSQL.removeEmptyCondiction(sqlStr,sqlParamNames,params);
if(Logger.isLogLevel("DEBUG")) {
Logger.debug("[SQL_Executed]: " + assembleSQLWithMap(sqlStr, params));
}
//preparedStatement SQL
String preparedSql = TSQL.preparedSql(sqlStr);
PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(preparedSql);
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//preparedStatement
TSQL.setPreparedParams(preparedStatement, sqlParamNames, params);
return preparedStatement;
}
/**
* PreparedStatement
* @param conn
* @param sqlStr sql
* @param params Map
* @param callTypes
* @return PreparedStatement
* @throws SQLException SQL
*/
public static CallableStatement createCallableStatement(Connection conn,String sqlStr,Map<String, Object> params, CallType[] callTypes) throws SQLException{
Logger.debug("[SQL_Executed]: " + sqlStr);
List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr);
//preparedStatement SQL
String preparedSql = TSQL.preparedSql(sqlStr);
// jdbc statement
CallableStatement callableStatement = (CallableStatement) conn.prepareCall(preparedSql);
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//callableStatement
TSQL.setPreparedParams(callableStatement,sqlParamNames,params);
//, OUT
ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData();
for(int i=0;i<parameterMetaData.getParameterCount();i++){
int paramMode = parameterMetaData.getParameterMode(i+1);
if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut) {
callableStatement.registerOutParameter(i + 1, parameterMetaData.getParameterType(i + 1));
}
}
return callableStatement;
}
/**
*
* @param callableStatement callableStatement
* @return
* @throws SQLException SQL
*/
public static List<Object> getCallableStatementResult(CallableStatement callableStatement) throws SQLException{
ArrayList<Object> result = new ArrayList<Object>();
ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData();
for(int i=0;i<parameterMetaData.getParameterCount();i++){
int paramMode = parameterMetaData.getParameterMode(i+1);
// out ,
if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut){
String methodName = getDataMethod(parameterMetaData.getParameterType(i+1));
Object value;
try {
// int
Method method = TReflect.findMethod(CallableStatement.class,methodName,new Class[]{int.class});
value = TReflect.invokeMethod(callableStatement, method,i+1);
result.add(value);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* SQL
* @param sqlStr SQL
* @param args
* @return SQL
*/
public static String assembleSQLWithArray(String sqlStr,Object[] args){
// [, ] Map
Map<String,Object> argMap = TObject.arrayToMap(args);
return assembleSQLWithMap(sqlStr,argMap);
}
/**
* argObjectjSQL
* @param sqlStr SQL
* @param argObjectj
* @return SQL
* @throws ReflectiveOperationException
*/
public static String assembleSQLWithObject(String sqlStr,Object argObjectj) throws ReflectiveOperationException{
// [-] Map
Map<String,Object> argMap = TReflect.getMapfromObject(argObjectj);
return assembleSQLWithMap(sqlStr,argMap);
}
/**
* argMapKVSQL
* SQL:
* @param sqlStr SQL
* @param argMap Map
* @return
*/
public static String assembleSQLWithMap(String sqlStr,Map<String ,Object> argMap) {
if(argMap!=null) {
for (Entry<String, Object> arg : argMap.entrySet()) {
sqlStr = TString.fastReplaceAll(sqlStr+" ", "::" + arg.getKey()+"\\b", getSQLString(argMap.get(arg.getKey()))+" ");
}
}
return sqlStr.trim();
}
/**
* resultSetMap
* @param resultset
* @return Map
* @throws SQLException SQL
* @throws ReflectiveOperationException
*/
public static Map<String, Object> getOneRowWithMap(ResultSet resultset)
throws SQLException, ReflectiveOperationException {
HashMap<String, Object> resultMap = new HashMap<String,Object>();
HashMap<String,Integer> columns = new HashMap<String,Integer>();
int columnCount = resultset.getMetaData().getColumnCount();
for(int i=1;i<=columnCount;i++){
columns.put(resultset.getMetaData().getColumnLabel(i),resultset.getMetaData().getColumnType(i));
}
//Map
for(Entry<String, Integer> columnEntry : columns.entrySet())
{
String methodName =getDataMethod(columnEntry.getValue());
Object value = TReflect.invokeMethod(resultset, methodName, columnEntry.getKey());
resultMap.put(columnEntry.getKey(), value);
}
return resultMap;
}
/**
* resultSet
* @param clazz
* @param resultset
* @return
* @throws ReflectiveOperationException
* @throws SQLException SQL
* @throws ParseException
*/
public static Object getOneRowWithObject(Class<?> clazz,ResultSet resultset)
throws SQLException, ReflectiveOperationException, ParseException {
Map<String,Object>rowMap = getOneRowWithMap(resultset);
HashMap<String,Object> newMap = new HashMap<String,Object>();
for(Entry<String,Object> entry : rowMap.entrySet()){
String key = TString.fastReplaceAll(entry.getKey(), "\\W", "");
newMap.put(key,entry.getValue());
}
rowMap.clear();
return TReflect.getObjectFromMap(clazz, newMap,true);
}
/**
* resultSetList,Map
* @param resultSet
* @return List[Map]
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public static List<Map<String,Object>> getAllRowWithMapList(ResultSet resultSet)
throws SQLException, ReflectiveOperationException {
List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
while(resultSet!=null && resultSet.next()){
resultList.add(getOneRowWithMap(resultSet));
}
return resultList;
}
/**
* resultSetList,
* @param clazz
* @param resultSet
* @return
* @throws ParseException
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public static List<Object> getAllRowWithObjectList(Class<?> clazz,ResultSet resultSet)
throws SQLException, ReflectiveOperationException, ParseException {
List<Object> resultList = new ArrayList<Object>();
while(resultSet!=null && resultSet.next()){
resultList.add(getOneRowWithObject(clazz,resultSet));
}
return resultList;
}
/**
* SQL ,
* @param sqlText SQL
* @param sqlParamNames sql
* @param params
* @return
*/
public static String removeEmptyCondiction(String sqlText,List<String> sqlParamNames,Map<String, Object> params){
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//::paramName ``paramName
for(String paramName : params.keySet()){
sqlText = sqlText.replace("::"+paramName,"``"+paramName);
}
String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\s\\)\\s)|(\\sand\\s)|(\\sor\\s)|(\\sorder\\s)|(\\shaving\\s)|$)";
String[] sqlCondiction = TString.searchByRegex(sqlText,sqlRegx);
for(String condiction : sqlCondiction){
String[] condictions = TString.searchByRegex(condiction,"::\\w+\\b");
if(condictions.length>0){
if(condiction.trim().toLowerCase().startsWith("where")){
sqlText = sqlText.replace(condiction.trim(),"where 1=1");
}else{
sqlText = sqlText.replace(condiction.trim(),"");
}
sqlParamNames.remove(condictions[0]);
}
}
//``paramName ::paramName
return sqlText.replace("``","::");
}
/**
* SQL
* @param sqlText SQL
* @return SQL
*/
public static List<String[]> parseSQLCondiction(String sqlText) {
ArrayList<String[]> condictionList = new ArrayList<String[]>();
sqlText = sqlText.toLowerCase();
String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\s\\)\\s)|(\\sand\\s)|(\\sor\\s)|(\\sorder\\s)|(\\shaving\\s)|$)";
String[] sqlCondiction = TString.searchByRegex(sqlText,sqlRegx);
for(String condiction : sqlCondiction){
condiction = condiction.trim();
String concateMethod = condiction.substring(0,condiction.indexOf(" ")+1).trim();
condiction = condiction.substring(condiction.indexOf(" ")+1,condiction.length()).trim();
String operatorChar = TString.searchByRegex(condiction, "(\\slike\\s*)|(\\sin\\s*)|(>=)|(<=)|[=<>]")[0].trim();
String[] condictionArr = condiction.split("(\\slike\\s*)|(\\sin\\s*)|(>=)|(<=)|[=<>]");
condictionArr[0] = condictionArr[0].trim();
condictionArr[1] = condictionArr[1].trim();
if(condictionArr[0].trim().indexOf(".")>1){
condictionArr[0] = condictionArr[0].split("\\.")[1];
condictionArr[0] = condictionArr[0].substring(condictionArr[0].lastIndexOf(" ")+1);
}
if(condictionArr.length>1){
if((condictionArr[1].trim().startsWith("'") && condictionArr[1].trim().endsWith("'")) ||
(condictionArr[1].trim().startsWith("(") && condictionArr[1].trim().endsWith(")"))
){
condictionArr[1] = condictionArr[1].substring(1,condictionArr[1].length()-1);
}
if(operatorChar.contains("in")){
condictionArr[1] = condictionArr[1].replace("'", "");
}
//System.out.println(": "+concateMethod+" \t: "+condictionArr[0]+" \t: "+operatorChar+" \t: "+condictionArr[1]);
condictionList.add(new String[]{concateMethod, condictionArr[0], operatorChar, condictionArr[1]});
}else{
Logger.error("Parse SQL condiction error");
}
}
return condictionList;
}
/**
* SQL, JAVA SQL
* :String 'chs'
* @param argObj
* @return
*/
public static String getSQLString(Object argObj)
{
if(argObj==null){
return "null";
}
if(argObj instanceof List)
{
Object[] objects =((List<?>)argObj).toArray();
StringBuilder listValueStr= new StringBuilder("(");
for(Object obj : objects)
{
String sqlValue = getSQLString(obj);
if(sqlValue!=null) {
listValueStr.append(sqlValue);
listValueStr.append(",");
}
}
return TString.removeSuffix(listValueStr.toString())+")";
}
//String
else if(argObj instanceof String){
return "\'"+argObj.toString()+"\'";
}
//Boolean
else if(argObj instanceof Boolean){
if((Boolean)argObj)
return "true";
else
return "false";
}
//Date
else if(argObj instanceof Date){
SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE);
return "'"+dateFormat.format(argObj)+"'";
}
//String
else
{
return argObj.toString();
}
}
/**
* SQL Result
* @param databaseType
* @return
*/
public static String getDataMethod(int databaseType){
switch(databaseType){
case Types.CHAR :
return "getString";
case Types.VARCHAR :
return "getString";
case Types.LONGVARCHAR :
return "getString";
case Types.NCHAR :
return "getString";
case Types.LONGNVARCHAR :
return "getString";
case Types.NUMERIC :
return "getBigDecimal";
case Types.DECIMAL :
return "getBigDecimal";
case Types.BIT :
return "getBoolean";
case Types.BOOLEAN :
return "getBoolean";
case Types.TINYINT :
return "getByte";
case Types.SMALLINT :
return "getShort";
case Types.INTEGER :
return "getInt";
case Types.BIGINT :
return "getLong";
case Types.REAL :
return "getFloat";
case Types.FLOAT :
return "getFloat";
case Types.DOUBLE :
return "getDouble";
case Types.BINARY :
return "getBytes";
case Types.VARBINARY :
return "getBytes";
case Types.LONGVARBINARY :
return "getBytes";
case Types.DATE :
return "getDate";
case Types.TIME :
return "getTime";
case Types.TIMESTAMP :
return "getTimestamp";
case Types.CLOB :
return "getClob";
case Types.BLOB :
return "getBlob";
case Types.ARRAY :
return "getArray";
default:
return "getString";
}
}
/**
* JAVA SQL
* @param obj
* @return
*/
public static int getSqlTypes(Object obj){
Class<?> objectClass = obj.getClass();
if(char.class == objectClass){
return Types.CHAR;
}else if(String.class == objectClass){
return Types.VARCHAR ;
}else if(BigDecimal.class == objectClass){
return Types.NUMERIC;
}else if(Boolean.class == objectClass){
return Types.BIT;
}else if(Byte.class == objectClass){
return Types.TINYINT;
}else if(Short.class == objectClass){
return Types.SMALLINT;
}else if(Integer.class == objectClass){
return Types.INTEGER;
}else if(Long.class == objectClass){
return Types.BIGINT;
}else if(Float.class == objectClass){
return Types.FLOAT;
}else if(Double.class == objectClass){
return Types.DOUBLE;
}else if(Byte[].class == objectClass){
return Types.BINARY;
}else if(Date.class == objectClass){
return Types.DATE;
}else if(Time.class == objectClass){
return Types.TIME;
}else if(Timestamp.class == objectClass){
return Types.TIMESTAMP;
}else if(Clob.class == objectClass){
return Types.CLOB;
}else if(Blob.class == objectClass){
return Types.BLOB;
}else if(Object[].class == objectClass){
return Types.ARRAY;
}
return 0;
}
} |
package org.voovan.tools;
import org.voovan.db.CallType;
import org.voovan.db.DataBaseType;
import org.voovan.db.JdbcOperate;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.Map.Entry;
public class TSQL {
/**
* SQL , SQL
* @param sqlStr sql (select * from table where x=::x and y=::y)
* @return sql ([:x,:y])
*/
public static List<String> getSqlParamNames(String sqlStr){
String[] params = TString.searchByRegex(sqlStr, "::\\w+\\b");
ArrayList<String> sqlParamNames = new ArrayList<String>();
for(String param : params){
sqlParamNames.add(param);
}
return sqlParamNames;
}
/**
* preparedStatement sql (?)
* @param sqlStr sql (select * from table where x=:x and y=::y)
* @return :? (select * from table where x=? and y=?)
*/
public static String preparedSql(String sqlStr){
return TString.fastReplaceAll(sqlStr, "::\\w+\\b", "?");
}
/**
* preparedStatement
*
* @param preparedStatement preparedStatement
* @param sqlParamNames sql
* @param params Map
* @throws SQLException SQL
*/
public static void setPreparedParams(PreparedStatement preparedStatement,List<String> sqlParamNames,Map<String, ?> params) throws SQLException{
for(int i=0;i<sqlParamNames.size();i++){
String paramName = sqlParamNames.get(i);
paramName = paramName.substring(2,paramName.length());
Object data = params.get(paramName);
if(data==null){
preparedStatement.setObject(i + 1, null);
} else if(TReflect.isBasicType(data.getClass())) {
preparedStatement.setObject(i + 1, params.get(paramName));
} else{
//,, JSON
preparedStatement.setObject(i + 1, JSON.toJSON(params.get(paramName)));
}
}
}
/**
* PreparedStatement
* @param conn
* @param sqlStr sql
* @param params Map
* @return PreparedStatement
* @throws SQLException SQL
*/
public static PreparedStatement createPreparedStatement(Connection conn,String sqlStr,Map<String, Object> params) throws SQLException{
List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr);
sqlStr = TSQL.removeEmptyCondiction(sqlStr,sqlParamNames,params);
if(Logger.isLogLevel("DEBUG")) {
Logger.debug("[SQL_Executed]: " + assembleSQLWithMap(sqlStr, params));
}
//preparedStatement SQL
String preparedSql = TSQL.preparedSql(sqlStr);
PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(preparedSql);
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//preparedStatement
TSQL.setPreparedParams(preparedStatement, sqlParamNames, params);
return preparedStatement;
}
/**
* PreparedStatement
* @param conn
* @param sqlStr sql
* @param params Map
* @param callTypes
* @return PreparedStatement
* @throws SQLException SQL
*/
public static CallableStatement createCallableStatement(Connection conn,String sqlStr,Map<String, Object> params, CallType[] callTypes) throws SQLException{
Logger.debug("[SQL_Executed]: " + sqlStr);
List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr);
//preparedStatement SQL
String preparedSql = TSQL.preparedSql(sqlStr);
// jdbc statement
CallableStatement callableStatement = (CallableStatement) conn.prepareCall(preparedSql);
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//callableStatement
TSQL.setPreparedParams(callableStatement,sqlParamNames,params);
//, OUT
ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData();
for(int i=0;i<parameterMetaData.getParameterCount();i++){
int paramMode = parameterMetaData.getParameterMode(i+1);
if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut) {
callableStatement.registerOutParameter(i + 1, parameterMetaData.getParameterType(i + 1));
}
}
return callableStatement;
}
/**
*
* @param callableStatement callableStatement
* @return
* @throws SQLException SQL
*/
public static List<Object> getCallableStatementResult(CallableStatement callableStatement) throws SQLException{
ArrayList<Object> result = new ArrayList<Object>();
ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData();
for(int i=0;i<parameterMetaData.getParameterCount();i++){
int paramMode = parameterMetaData.getParameterMode(i+1);
// out ,
if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut){
String methodName = getDataMethod(parameterMetaData.getParameterType(i+1));
Object value;
try {
// int
Method method = TReflect.findMethod(CallableStatement.class,methodName,new Class[]{int.class});
value = TReflect.invokeMethod(callableStatement, method,i+1);
result.add(value);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* SQL
* @param sqlStr SQL
* @param args
* @return SQL
*/
public static String assembleSQLWithArray(String sqlStr,Object[] args){
// [, ] Map
Map<String,Object> argMap = TObject.arrayToMap(args);
return assembleSQLWithMap(sqlStr,argMap);
}
/**
* argObjectjSQL
* @param sqlStr SQL
* @param argObjectj
* @return SQL
* @throws ReflectiveOperationException
*/
public static String assembleSQLWithObject(String sqlStr,Object argObjectj) throws ReflectiveOperationException{
// [-] Map
Map<String,Object> argMap = TReflect.getMapfromObject(argObjectj);
return assembleSQLWithMap(sqlStr,argMap);
}
/**
* argMapKVSQL
* SQL:
* @param sqlStr SQL
* @param argMap Map
* @return
*/
public static String assembleSQLWithMap(String sqlStr,Map<String ,Object> argMap) {
if(argMap!=null) {
for (Entry<String, Object> arg : argMap.entrySet()) {
sqlStr = TString.fastReplaceAll(sqlStr+" ", "::" + arg.getKey()+"\\b", getSQLString(argMap.get(arg.getKey()))+" ");
}
}
return sqlStr.trim();
}
/**
* resultSetMap
* @param resultset
* @return Map
* @throws SQLException SQL
* @throws ReflectiveOperationException
*/
public static Map<String, Object> getOneRowWithMap(ResultSet resultset)
throws SQLException, ReflectiveOperationException {
HashMap<String, Object> resultMap = new HashMap<String,Object>();
HashMap<String,Integer> columns = new HashMap<String,Integer>();
int columnCount = resultset.getMetaData().getColumnCount();
for(int i=1;i<=columnCount;i++){
columns.put(resultset.getMetaData().getColumnLabel(i),resultset.getMetaData().getColumnType(i));
}
//Map
for(Entry<String, Integer> columnEntry : columns.entrySet())
{
String methodName =getDataMethod(columnEntry.getValue());
Object value = TReflect.invokeMethod(resultset, methodName, columnEntry.getKey());
resultMap.put(columnEntry.getKey(), value);
}
return resultMap;
}
/**
* resultSet
* @param clazz
* @param resultset
* @return
* @throws ReflectiveOperationException
* @throws SQLException SQL
* @throws ParseException
*/
public static Object getOneRowWithObject(Class<?> clazz,ResultSet resultset)
throws SQLException, ReflectiveOperationException, ParseException {
Map<String,Object>rowMap = getOneRowWithMap(resultset);
return TReflect.getObjectFromMap(clazz, rowMap, true);
}
/**
* resultSetList,Map
* @param resultSet
* @return List[Map]
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public static List<Map<String,Object>> getAllRowWithMapList(ResultSet resultSet)
throws SQLException, ReflectiveOperationException {
List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
while(resultSet!=null && resultSet.next()){
resultList.add(getOneRowWithMap(resultSet));
}
return resultList;
}
/**
* resultSetList,
* @param clazz
* @param resultSet
* @return
* @throws ParseException
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public static List<Object> getAllRowWithObjectList(Class<?> clazz,ResultSet resultSet)
throws SQLException, ReflectiveOperationException, ParseException {
List<Object> resultList = new ArrayList<Object>();
while(resultSet!=null && resultSet.next()){
resultList.add(getOneRowWithObject(clazz,resultSet));
}
return resultList;
}
/**
* SQL ,
* @param sqlText SQL
* @param sqlParamNames sql
* @param params
* @return
*/
public static String removeEmptyCondiction(String sqlText,List<String> sqlParamNames,Map<String, Object> params){
//params,
if(params==null){
params = new Hashtable<String, Object>();
}
//::paramName ``paramName
for(String paramName : params.keySet()){
sqlText = sqlText.replace("::"+paramName,"``"+paramName);
}
String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\s\\)\\s)|(\\sand\\s)|(\\sor\\s)|(\\sgroup by\\s)|(\\sorder\\s)|(\\shaving\\s)|$)";
String[] sqlCondiction = TString.searchByRegex(sqlText,sqlRegx);
for(String condiction : sqlCondiction){
String[] condictions = TString.searchByRegex(condiction,"::\\w+\\b");
if(condictions.length>0){
if(condiction.trim().toLowerCase().startsWith("where")){
sqlText = sqlText.replace(condiction.trim(),"where 1=1");
}else{
sqlText = sqlText.replace(condiction.trim(),"");
}
sqlParamNames.remove(condictions[0]);
}
}
//``paramName ::paramName
return sqlText.replace("``","::");
}
/**
* SQL
* @param sqlText SQL
* @return SQL
*/
public static List<String[]> parseSQLCondiction(String sqlText) {
ArrayList<String[]> condictionList = new ArrayList<String[]>();
sqlText = sqlText.toLowerCase();
String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\s\\)\\s)|(\\sand\\s)|(\\sor\\s)|(\\sgroup by\\s)|(\\sorder\\s)|(\\shaving\\s)|$)";
String[] sqlCondiction = TString.searchByRegex(sqlText,sqlRegx);
for(String condiction : sqlCondiction){
condiction = condiction.trim();
String concateMethod = condiction.substring(0,condiction.indexOf(" ")+1).trim();
condiction = condiction.substring(condiction.indexOf(" ")+1,condiction.length()).trim();
String operatorChar = TString.searchByRegex(condiction, "(\\slike\\s*)|(\\sin\\s*)|(>=)|(<=)|[=<>]")[0].trim();
String[] condictionArr = condiction.split("(\\slike\\s*)|(\\sin\\s*)|(>=)|(<=)|[=<>]");
condictionArr[0] = condictionArr[0].trim();
condictionArr[1] = condictionArr[1].trim();
if(condictionArr[0].trim().indexOf(".")>1){
condictionArr[0] = condictionArr[0].split("\\.")[1];
condictionArr[0] = condictionArr[0].substring(condictionArr[0].lastIndexOf(" ")+1);
}
if(condictionArr.length>1){
if((condictionArr[1].trim().startsWith("'") && condictionArr[1].trim().endsWith("'")) ||
(condictionArr[1].trim().startsWith("(") && condictionArr[1].trim().endsWith(")"))
){
condictionArr[1] = condictionArr[1].substring(1,condictionArr[1].length()-1);
}
if(operatorChar.contains("in")){
condictionArr[1] = condictionArr[1].replace("'", "");
}
//System.out.println(": "+concateMethod+" \t: "+condictionArr[0]+" \t: "+operatorChar+" \t: "+condictionArr[1]);
condictionList.add(new String[]{concateMethod, condictionArr[0], operatorChar, condictionArr[1]});
}else{
Logger.error("Parse SQL condiction error");
}
}
return condictionList;
}
/**
* SQL, JAVA SQL
* :String 'chs'
* @param argObj
* @return
*/
public static String getSQLString(Object argObj)
{
if(argObj==null){
return "null";
}
if(argObj instanceof List)
{
Object[] objects =((List<?>)argObj).toArray();
StringBuilder listValueStr= new StringBuilder("(");
for(Object obj : objects)
{
String sqlValue = getSQLString(obj);
if(sqlValue!=null) {
listValueStr.append(sqlValue);
listValueStr.append(",");
}
}
return TString.removeSuffix(listValueStr.toString())+")";
}
//String
else if(argObj instanceof String){
return "\'"+argObj.toString()+"\'";
}
//Boolean
else if(argObj instanceof Boolean){
if((Boolean)argObj)
return "true";
else
return "false";
}
//Date
else if(argObj instanceof Date){
SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE);
return "'"+dateFormat.format(argObj)+"'";
}
//String
else
{
return argObj.toString();
}
}
/**
* SQL Result
* @param databaseType
* @return
*/
public static String getDataMethod(int databaseType){
switch(databaseType){
case Types.CHAR :
return "getString";
case Types.VARCHAR :
return "getString";
case Types.LONGVARCHAR :
return "getString";
case Types.NCHAR :
return "getString";
case Types.LONGNVARCHAR :
return "getString";
case Types.NUMERIC :
return "getBigDecimal";
case Types.DECIMAL :
return "getBigDecimal";
case Types.BIT :
return "getBoolean";
case Types.BOOLEAN :
return "getBoolean";
case Types.TINYINT :
return "getByte";
case Types.SMALLINT :
return "getShort";
case Types.INTEGER :
return "getInt";
case Types.BIGINT :
return "getLong";
case Types.REAL :
return "getFloat";
case Types.FLOAT :
return "getFloat";
case Types.DOUBLE :
return "getDouble";
case Types.BINARY :
return "getBytes";
case Types.VARBINARY :
return "getBytes";
case Types.LONGVARBINARY :
return "getBytes";
case Types.DATE :
return "getDate";
case Types.TIME :
return "getTime";
case Types.TIMESTAMP :
return "getTimestamp";
case Types.CLOB :
return "getClob";
case Types.BLOB :
return "getBlob";
case Types.ARRAY :
return "getArray";
default:
return "getString";
}
}
/**
* JAVA SQL
* @param obj
* @return
*/
public static int getSqlTypes(Object obj){
Class<?> objectClass = obj.getClass();
if(char.class == objectClass){
return Types.CHAR;
}else if(String.class == objectClass){
return Types.VARCHAR ;
}else if(BigDecimal.class == objectClass){
return Types.NUMERIC;
}else if(Boolean.class == objectClass){
return Types.BIT;
}else if(Byte.class == objectClass){
return Types.TINYINT;
}else if(Short.class == objectClass){
return Types.SMALLINT;
}else if(Integer.class == objectClass){
return Types.INTEGER;
}else if(Long.class == objectClass){
return Types.BIGINT;
}else if(Float.class == objectClass){
return Types.FLOAT;
}else if(Double.class == objectClass){
return Types.DOUBLE;
}else if(Byte[].class == objectClass){
return Types.BINARY;
}else if(Date.class == objectClass){
return Types.DATE;
}else if(Time.class == objectClass){
return Types.TIME;
}else if(Timestamp.class == objectClass){
return Types.TIMESTAMP;
}else if(Clob.class == objectClass){
return Types.CLOB;
}else if(Blob.class == objectClass){
return Types.BLOB;
}else if(Object[].class == objectClass){
return Types.ARRAY;
}
return 0;
}
/**
*
* @return
* @throws SQLException SQL
*/
public static DataBaseType getDataBaseType(Connection connection) {
try {
//driverName
if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MYSQL") != -1) {
return DataBaseType.MySql;
}
if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MARIADB") != -1) {
return DataBaseType.Mariadb;
} else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("POSTAGE") != -1) {
return DataBaseType.Postage;
} else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("ORACLE") != -1) {
return DataBaseType.Oracle;
}
return DataBaseType.UNKNOW;
} catch (SQLException e) {
return DataBaseType.UNKNOW;
}
}
/**
* SQL
* @param jdbcOperate jdbcOperate
* @param sqlField sql
* @return
*/
public static String wrapSqlField(JdbcOperate jdbcOperate, String sqlField){
try {
Connection connection = jdbcOperate.getConnection();
DataBaseType dataBaseType = TSQL.getDataBaseType(connection);
if (dataBaseType.equals(DataBaseType.Mariadb) || dataBaseType.equals(DataBaseType.MySql)) {
return "`"+sqlField+"`";
} else if (dataBaseType.equals(DataBaseType.Oracle)) {
return "\""+sqlField+"\"";
} else if (dataBaseType.equals(DataBaseType.Postage)) {
return "`"+sqlField+"`";
} else {
return sqlField;
}
} catch (SQLException e) {
Logger.error("wrap sql field error", e);
return sqlField;
}
}
/**
* Mysql sql
* @param sql Sql
* @param pageNumber
* @param pageSize
* @return
*/
public static String genMysqlPageSql(String sql, int pageNumber, int pageSize){
int pageStart = (pageNumber-1) * pageSize;
if(pageSize<0 || pageNumber<0) {
return sql;
}
return sql + " limit " + pageStart + ", " + pageSize;
}
/**
* Postage sql
* @param sql Sql
* @param pageNumber
* @param pageSize
* @return
*/
public static String genPostagePageSql(String sql, int pageNumber, int pageSize){
int pageStart = (pageNumber-1) * pageSize;
if(pageSize<0 || pageNumber<0) {
return sql;
}
return sql + " limit " + pageSize + " offset " + pageStart;
}
/**
* Oracle sql
* @param sql Sql
* @param pageNumber
* @param pageSize
* @return
*/
public static String genOraclePageSql(String sql, int pageNumber, int pageSize){
int pageStart = (pageNumber-1) * pageSize;
int pageEnd = pageStart + pageSize;
if(pageSize<0 || pageNumber<0) {
return sql;
}
sql = sql.replaceFirst("select", "select rownum rn,");
sql = "select pageSql.* from (" + sql + " ) pageSql where rn between " + pageStart + " and " + pageEnd;
return sql;
}
} |
package org.codelibs.fess.suggest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Stream;
import org.codelibs.core.lang.StringUtil;
import org.codelibs.fess.suggest.analysis.SuggestAnalyzer;
import org.codelibs.fess.suggest.constants.FieldNames;
import org.codelibs.fess.suggest.converter.ReadingConverter;
import org.codelibs.fess.suggest.exception.SuggesterException;
import org.codelibs.fess.suggest.index.SuggestIndexer;
import org.codelibs.fess.suggest.normalizer.Normalizer;
import org.codelibs.fess.suggest.request.popularwords.PopularWordsRequestBuilder;
import org.codelibs.fess.suggest.request.suggest.SuggestRequestBuilder;
import org.codelibs.fess.suggest.settings.SuggestSettings;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
public class Suggester {
protected final Client client;
protected final SuggestSettings suggestSettings;
protected final ReadingConverter readingConverter;
protected final ReadingConverter contentsReadingConverter;
protected final Normalizer normalizer;
protected final SuggestAnalyzer analyzer;
protected final String index;
protected final String type;
protected final ExecutorService threadPool;
public Suggester(final Client client, final SuggestSettings settings, final ReadingConverter readingConverter,
final ReadingConverter contentsReadingConverter, final Normalizer normalizer, final SuggestAnalyzer analyzer,
final ExecutorService threadPool) {
this.client = client;
this.suggestSettings = settings;
this.readingConverter = readingConverter;
this.contentsReadingConverter = contentsReadingConverter;
this.normalizer = normalizer;
this.analyzer = analyzer;
this.index = settings.getAsString(SuggestSettings.DefaultKeys.INDEX, StringUtil.EMPTY);
this.type = settings.getAsString(SuggestSettings.DefaultKeys.TYPE, StringUtil.EMPTY);
this.threadPool = threadPool;
}
public SuggestRequestBuilder suggest() {
return new SuggestRequestBuilder(client, readingConverter, normalizer).setIndex(getSearchAlias(index)).setType(type);
}
public PopularWordsRequestBuilder popularWords() {
return new PopularWordsRequestBuilder(client).setIndex(getSearchAlias(index)).setType(type);
}
public RefreshResponse refresh() {
return client.admin().indices().prepareRefresh().execute().actionGet(suggestSettings.getIndexTimeout());
}
public void shutdown() {
threadPool.shutdownNow();
}
public boolean createIndexIfNothing() {
try {
boolean created = false;
final IndicesExistsResponse response =
client.admin().indices().prepareExists(getSearchAlias(index)).execute().actionGet(suggestSettings.getIndicesTimeout());
if (!response.isExists()) {
final String mappingSource = getDefaultMappings();
final String settingsSource = getDefaultIndexSettings();
final String indexName = createIndexName(index);
client.admin().indices().prepareCreate(indexName).setSettings(settingsSource, XContentType.JSON)
.addMapping(type, mappingSource, XContentType.JSON).addAlias(new Alias(getSearchAlias(index)))
.addAlias(new Alias(getUpdateAlias(index))).execute().actionGet(suggestSettings.getIndicesTimeout());
client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet(suggestSettings.getClusterTimeout());
created = true;
}
return created;
} catch (final Exception e) {
throw new SuggesterException("Failed to create index.", e);
}
}
public void createNextIndex() {
try {
final List<String> prevIndices = new ArrayList<>();
final IndicesExistsResponse response =
client.admin().indices().prepareExists(getUpdateAlias(index)).execute().actionGet(suggestSettings.getIndicesTimeout());
if (response.isExists()) {
GetAliasesResponse getAliasesResponse =
client.admin().indices().prepareGetAliases(getUpdateAlias(index)).execute()
.actionGet(suggestSettings.getIndicesTimeout());
getAliasesResponse.getAliases().keysIt().forEachRemaining(prevIndices::add);
}
final String mappingSource = getDefaultMappings();
final String settingsSource = getDefaultIndexSettings();
final String indexName = createIndexName(index);
CreateIndexResponse createIndexResponse =
client.admin().indices().prepareCreate(indexName).setSettings(settingsSource, XContentType.JSON)
.addMapping(type, mappingSource, XContentType.JSON).execute().actionGet(suggestSettings.getIndicesTimeout());
if (!createIndexResponse.isAcknowledged()) {
throw new SuggesterException("Failed to create index");
}
client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet(suggestSettings.getClusterTimeout());
final IndicesAliasesRequestBuilder aliasesRequestBuilder =
client.admin().indices().prepareAliases().addAlias(indexName, getUpdateAlias(index));
for (final String prevIndex : prevIndices) {
aliasesRequestBuilder.removeAlias(prevIndex, getUpdateAlias(index));
}
aliasesRequestBuilder.execute().actionGet(suggestSettings.getIndicesTimeout());
} catch (final Exception e) {
throw new SuggesterException("Failed to create index.", e);
}
}
public void switchIndex() {
try {
final List<String> updateIndices = new ArrayList<>();
final String updateAlias = getUpdateAlias(index);
final IndicesExistsResponse updateIndicesResponse =
client.admin().indices().prepareExists(updateAlias).execute().actionGet(suggestSettings.getIndicesTimeout());
if (updateIndicesResponse.isExists()) {
GetAliasesResponse getAliasesResponse =
client.admin().indices().prepareGetAliases(updateAlias).execute().actionGet(suggestSettings.getIndicesTimeout());
getAliasesResponse.getAliases().forEach(
x -> x.value.stream().filter(y -> updateAlias.equals(y.alias())).forEach(y -> updateIndices.add(x.key)));
}
if (updateIndices.size() != 1) {
throw new SuggesterException("Unexpected update indices num:" + updateIndices.size());
}
final String updateIndex = updateIndices.get(0);
final List<String> searchIndices = new ArrayList<>();
final String searchAlias = getSearchAlias(index);
final IndicesExistsResponse searchIndicesResponse =
client.admin().indices().prepareExists(searchAlias).execute().actionGet(suggestSettings.getIndicesTimeout());
if (searchIndicesResponse.isExists()) {
GetAliasesResponse getAliasesResponse =
client.admin().indices().prepareGetAliases(searchAlias).execute().actionGet(suggestSettings.getIndicesTimeout());
getAliasesResponse.getAliases().forEach(
x -> x.value.stream().filter(y -> searchAlias.equals(y.alias())).forEach(y -> searchIndices.add(x.key)));
}
if (searchIndices.size() != 1) {
throw new SuggesterException("Unexpected search indices num:" + searchIndices.size());
}
final String searchIndex = searchIndices.get(0);
if (updateIndex.equals(searchIndex)) {
return;
}
client.admin().indices().prepareAliases().removeAlias(searchIndex, searchAlias).addAlias(updateIndex, searchAlias).execute()
.actionGet(suggestSettings.getIndicesTimeout());
} catch (final Exception e) {
throw new SuggesterException("Failed to create index.", e);
}
}
public void removeDisableIndices() {
GetIndexResponse response = client.admin().indices().prepareGetIndex().execute().actionGet(suggestSettings.getIndicesTimeout());
Stream.of(response.getIndices()).filter(s -> {
if (!isSuggestIndex(s)) {
return false;
}
final List<AliasMetaData> list = response.getAliases().get(s);
if (list == null) {
return true;
}
return list.isEmpty();
}).forEach(s -> client.admin().indices().prepareDelete(s).execute().actionGet(suggestSettings.getIndicesTimeout()));
}
public SuggestIndexer indexer() {
return createDefaultIndexer();
}
public static SuggesterBuilder builder() {
return new SuggesterBuilder();
}
//getter
public SuggestSettings settings() {
return suggestSettings;
}
public ReadingConverter getReadingConverter() {
return readingConverter;
}
public Normalizer getNormalizer() {
return normalizer;
}
protected SuggestIndexer createDefaultIndexer() {
return new SuggestIndexer(client, getUpdateAlias(index), type, readingConverter, contentsReadingConverter, normalizer, analyzer,
suggestSettings, threadPool);
}
public String getIndex() {
return index;
}
public String getType() {
return type;
}
public long getAllWordsNum() {
return getNum(QueryBuilders.matchAllQuery());
}
public long getDocumentWordsNum() {
return getNum(QueryBuilders.rangeQuery(FieldNames.DOC_FREQ).gte(1));
}
public long getQueryWordsNum() {
return getNum(QueryBuilders.rangeQuery(FieldNames.QUERY_FREQ).gte(1));
}
private long getNum(final QueryBuilder queryBuilder) {
final SearchResponse searchResponse =
client.prepareSearch().setIndices(getSearchAlias(index)).setTypes(type).setSize(0).setQuery(queryBuilder).execute()
.actionGet(suggestSettings.getSearchTimeout());
return searchResponse.getHits().getTotalHits();
}
private String getSearchAlias(final String index) {
return index;
}
private String getUpdateAlias(final String index) {
return index + ".update";
}
private String createIndexName(final String index) {
return index + '.' + ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
}
private String getDefaultMappings() throws IOException {
final StringBuilder mappingSource = new StringBuilder();
try (BufferedReader br =
new BufferedReader(new InputStreamReader(this.getClass().getClassLoader()
.getResourceAsStream("suggest_indices/suggest/mappings-default.json")))) {
String line;
while ((line = br.readLine()) != null) {
mappingSource.append(line);
}
}
return mappingSource.toString();
}
private String getDefaultIndexSettings() throws IOException {
final StringBuilder settingsSource = new StringBuilder();
try (BufferedReader br =
new BufferedReader(new InputStreamReader(this.getClass().getClassLoader()
.getResourceAsStream("suggest_indices/suggest.json")))) {
String line;
while ((line = br.readLine()) != null) {
settingsSource.append(line);
}
}
return settingsSource.toString();
}
private boolean isSuggestIndex(final String indexName) {
return indexName.startsWith(index);
}
} |
package org.pentaho.ui.xul.swt.tags;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnViewerEditor;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.TreeViewerEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.DefaultBinding;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.XulTree;
import org.pentaho.ui.xul.containers.XulTreeChildren;
import org.pentaho.ui.xul.containers.XulTreeCols;
import org.pentaho.ui.xul.containers.XulTreeItem;
import org.pentaho.ui.xul.containers.XulTreeRow;
import org.pentaho.ui.xul.dnd.DropEffectType;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dnd.DropPosition;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.swt.AbstractSwtXulContainer;
import org.pentaho.ui.xul.swt.TableSelection;
import org.pentaho.ui.xul.swt.tags.treeutil.TableColumnSorter;
import org.pentaho.ui.xul.swt.tags.treeutil.TreeColumnSorter;
import org.pentaho.ui.xul.swt.tags.treeutil.XulSortProperties;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnLabelProvider;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnModifier;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTableContentProvider;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeCellLabelProvider;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeColumnModifier;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeContentProvider;
import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeTextCellEditor;
import org.pentaho.ui.xul.util.ColumnType;
import org.pentaho.ui.xul.util.SortDirection;
import org.pentaho.ui.xul.util.SwtDragManager;
import org.pentaho.ui.xul.util.TreeCellEditor;
import org.pentaho.ui.xul.util.TreeCellRenderer;
public class SwtTree extends AbstractSwtXulContainer implements XulTree {
// Tables and trees
// share so much of the same API, I wrapped their common methods
// into an interface (TabularWidget) and set the component to two
// separate member variables here so that I don't have to reference
// them separately.
private static final Log logger = LogFactory.getLog( SwtTree.class );
protected XulTreeCols columns = null;
protected XulTreeChildren rootChildren = null;
protected XulComponent parentComponent = null;
private Object data = null;
private boolean disabled = false;
private boolean enableColumnDrag = false;
private boolean editable = false;
private String onedit;
private String onSelect = null;
private int rowsToDisplay = 0;
private TableSelection selType = TableSelection.SINGLE;
private boolean isHierarchical = false;
private ColumnType[] currentColumnTypes = null;
private int activeRow = -1;
private int activeColumn = -1;
private XulDomContainer domContainer;
private TableViewer table;
private TreeViewer tree;
private int selectedIndex = -1;
protected boolean controlDown;
private int[] selectedRows;
private boolean hiddenRoot = true;
private String command;
private boolean preserveExpandedState;
private boolean linesVisible = true;
private XulSortProperties sortProperties = new XulSortProperties();
private List<Binding> elementBindings = new ArrayList<Binding>();
private String newItemBinding;
private boolean autoCreateNewRows;
private boolean preserveSelection;
private Collection currentSelectedItems = null;
private Method dropVetoerMethod;
private Object dropVetoerController;
private PropertyChangeListener cellChangeListener = new PropertyChangeListener() {
public void propertyChange( PropertyChangeEvent arg0 ) {
SwtTree.this.update();
}
};
public SwtTree( Element self, XulComponent parent, XulDomContainer container, String tagName ) {
super( tagName );
this.parentComponent = parent;
// According to XUL spec, in order for a hierarchical tree to be rendered, a
// primary column must be identified AND at least one treeitem must be
// listed as a container.
// Following code does not work with the current instantiation routine. When
// transitioned to onDomReady() instantiation this should work.
domContainer = container;
}
@Override
public void layout() {
XulComponent primaryColumn = this.getElementByXPath( "treecols/treecol[@primary='true']" );
XulComponent isaContainer = this.getElementByXPath( "treechildren/treeitem[@container='true']" );
isHierarchical = ( primaryColumn != null ) || ( isaContainer != null );
if ( isHierarchical ) {
int style = ( this.selType == TableSelection.MULTIPLE ) ? SWT.MULTI : SWT.None;
style |= SWT.BORDER;
tree = new TreeViewer( (Composite) parentComponent.getManagedObject(), style );
setManagedObject( tree );
} else {
table =
new TableViewer( (Composite) parentComponent.getManagedObject(), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.BORDER );
setManagedObject( table );
}
if ( isHierarchical ) {
setupTree();
} else {
setupTable();
}
if ( getOndrag() != null ) {
DropEffectType effect = DropEffectType.COPY;
if ( getDrageffect() != null ) {
effect = DropEffectType.valueOfIgnoreCase( getDrageffect() );
}
super.enableDrag( effect );
}
if ( getOndrop() != null ) {
super.enableDrop();
}
this.initialized = true;
}
private void resizeTreeColumn() {
final Composite parentComposite = ( (Composite) parentComponent.getManagedObject() );
Rectangle area = parentComposite.getClientArea();
Point preferredSize = tree.getTree().computeSize( SWT.DEFAULT, SWT.DEFAULT );
int width = area.width - 2 * tree.getTree().getBorderWidth();
if ( preferredSize.y > area.height + tree.getTree().getHeaderHeight() ) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
Point vBarSize = tree.getTree().getVerticalBar().getSize();
width -= vBarSize.x;
}
width -= 20;
tree.getTree().getColumn( 0 ).setWidth( width );
}
private void setupTree() {
final Composite parentComposite = ( (Composite) parentComponent.getManagedObject() );
parentComposite.addControlListener( new ControlAdapter() {
public void controlResized( ControlEvent e ) {
resizeTreeColumn();
}
} );
TreeViewerColumn treeCol = new TreeViewerColumn( tree, SWT.LEFT );
treeCol.getColumn().setMoveable( true );
treeCol.getColumn().setText( "Column 3" );
treeCol.setLabelProvider( new XulTreeCellLabelProvider( this, this.domContainer ) );
ColumnViewerToolTipSupport.enableFor( tree );
tree.setCellEditors( new CellEditor[] { new XulTreeTextCellEditor( tree.getTree() ) } );
tree.setCellModifier( new XulTreeColumnModifier( this ) );
// tree.setLabelProvider(new XulTreeLabelProvider(this, this.domContainer));
tree.setContentProvider( new XulTreeContentProvider( this ) );
tree.setInput( this );
tree.getTree().setLayoutData( new GridData( GridData.FILL_BOTH ) );
tree.setColumnProperties( new String[] { "0" } );
TreeViewerEditor.create( tree, new ColumnViewerEditorActivationStrategy( tree ) {
@Override
protected boolean isEditorActivationEvent( ColumnViewerEditorActivationEvent event ) {
return super.isEditorActivationEvent( event );
}
}, ColumnViewerEditor.DEFAULT );
tree.getTree().addKeyListener( new KeyAdapter() {
public void keyPressed( KeyEvent event ) {
switch ( event.keyCode ) {
case SWT.CTRL:
SwtTree.this.controlDown = true;
break;
case SWT.ESC:
// End editing session
tree.getTree().deselectAll();
setSelectedRows( new int[] {} );
break;
}
}
@Override
public void keyReleased( KeyEvent event ) {
switch ( event.keyCode ) {
case SWT.CTRL:
SwtTree.this.controlDown = false;
break;
}
}
} );
// Add a focus listener to clear the contol down selector
tree.getTree().addFocusListener( new FocusListener() {
public void focusGained( FocusEvent arg0 ) {
}
public void focusLost( FocusEvent arg0 ) {
if ( tree.getCellEditors()[0].isActivated() == false ) {
SwtTree.this.controlDown = false;
}
}
} );
tree.addTreeListener( new ITreeViewerListener() {
public void treeCollapsed( TreeExpansionEvent arg0 ) {
if ( arg0.getElement() instanceof XulTreeItem ) {
XulTreeItem t = (XulTreeItem) arg0.getElement();
t.setExpanded( false );
}
}
public void treeExpanded( TreeExpansionEvent arg0 ) {
if ( arg0.getElement() instanceof XulTreeItem ) {
XulTreeItem t = (XulTreeItem) arg0.getElement();
t.setExpanded( true );
}
}
} );
tree.addDoubleClickListener( new IDoubleClickListener() {
public void doubleClick( DoubleClickEvent arg0 ) {
if ( command != null ) {
if ( elements != null ) {
// Invoke with selected elements as parameter
invoke( command, new Object[] { getSelectedItems().toArray() } );
} else {
// Invoke with selected indexes as parameter
invoke( command, new Object[] { getSelectedRows() } );
}
}
}
} );
tree.addSelectionChangedListener( new ISelectionChangedListener() {
public void selectionChanged( SelectionChangedEvent event ) {
// if the selection is empty clear the label
if ( event.getSelection().isEmpty() ) {
SwtTree.this.setSelectedIndex( -1 );
return;
}
if ( event.getSelection() instanceof IStructuredSelection ) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
int[] selected = new int[selection.size()];
List selectedItems = new ArrayList();
int i = 0;
for ( Object o : selection.toArray() ) {
XulTreeItem selectedItem = (XulTreeItem) o;
SearchBundle b = findSelectedIndex( new SearchBundle(), getRootChildren(), selectedItem );
selected[i++] = b.curPos;
selectedItems.add( b.selectedItem );
}
if ( selected.length == 0 ) {
setSelectedIndex( -1 );
} else {
setSelectedIndex( selected[0] );
}
int[] selectedRows = null;
if ( SwtTree.this.controlDown && Arrays.equals( selected, selectedRows )
&& tree.getCellEditors()[0].isActivated() == false ) {
tree.getTree().deselectAll();
selectedRows = new int[] {};
} else {
selectedRows = selected;
}
changeSupport.firePropertyChange( "selectedRows", null, selectedRows );
changeSupport.firePropertyChange( "absoluteSelectedRows", null, selectedRows );
changeSupport.firePropertyChange( "selectedItems", null, selectedItems );
currentSelectedItems = selectedItems;
// Single selection binding.
Object selectedItem = ( selectedItems.size() > 0 ) ? selectedItems.get( 0 ) : null;
changeSupport.firePropertyChange( "selectedItem", null, selectedItem );
}
}
} );
sortProperties.setSortColumn( null );
sortProperties.setSortable( false );
for ( XulComponent col : this.columns.getChildNodes() ) {
XulTreeCol xulCol = (XulTreeCol) col;
// Only process the first column that is deemed sortActive,
// since only one column is allowed sortActive at a time
if ( xulCol.isSortActive() && sortProperties.getSortColumn() == null ) {
sortProperties.setSortColumn( treeCol.getColumn() );
sortProperties.setSortDirection( SortDirection.valueOf( xulCol.getSortDirection() ) );
}
sortProperties.setSortMethod( treeCol.getColumn(), toGetter( xulCol.getComparatorbinding() ) );
}
TreeColumnSorter sorter = new TreeColumnSorter( tree, sortProperties );
}
private class SearchBundle {
int curPos;
boolean found;
Object selectedItem;
}
private SearchBundle findSelectedIndex( SearchBundle bundle, XulTreeChildren children, XulTreeItem selectedItem ) {
for ( XulComponent c : children.getChildNodes() ) {
if ( c == selectedItem ) {
bundle.found = true;
if ( elements != null ) {
bundle.selectedItem = findBoundTreeItem( bundle.curPos );
}
return bundle;
}
bundle.curPos++;
if ( c.getChildNodes().size() > 1 ) {
SearchBundle b = findSelectedIndex( bundle, (XulTreeChildren) c.getChildNodes().get( 1 ), selectedItem );
if ( b.found ) {
return b;
}
}
}
return bundle;
}
private Object findBoundTreeItem( int pos ) {
if ( this.isHierarchical && this.elements != null ) {
if ( elements == null || ( this.hiddenRoot && elements.size() == 0 ) ) {
return null;
}
String method = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
if ( pos == -1 ) {
return null;
}
FindSelectedItemTuple tuple =
findSelectedItem( this.elements, method, new FindSelectedItemTuple( pos, this.isHiddenrootnode() ) );
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private void setupTable() {
table.setContentProvider( new XulTableContentProvider( this ) );
table.setLabelProvider( new XulTableColumnLabelProvider( this, domContainer ) );
table.setCellModifier( new XulTableColumnModifier( this ) );
Table baseTable = table.getTable();
baseTable.setLayoutData( new GridData( GridData.FILL_BOTH ) );
setupColumns();
table.addSelectionChangedListener( new ISelectionChangedListener() {
public void selectionChanged( SelectionChangedEvent event ) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
setSelectedIndex( getRootChildren().getChildNodes().indexOf( selection.getFirstElement() ) );
int[] selectedRows = new int[selection.size()];
int i = 0;
for ( Iterator it = selection.iterator(); it.hasNext(); ) {
Object sel = it.next();
selectedRows[i] = getRootChildren().getChildNodes().indexOf( sel );
i++;
}
changeSupport.firePropertyChange( "selectedRows", null, selectedRows );
changeSupport.firePropertyChange( "absoluteSelectedRows", null, selectedRows );
Collection selectedItems = findSelectedTableRows( selectedRows );
changeSupport.firePropertyChange( "selectedItems", null, selectedItems );
// Single selection binding.
Object selectedItem = ( selectedItems.size() > 0 ) ? selectedItems.toArray()[0] : null;
changeSupport.firePropertyChange( "selectedItem", null, selectedItem );
}
} );
MouseAdapter lsMouseT = new MouseAdapter() {
public void mouseDown( MouseEvent event ) {
if ( event.button == 1 ) {
boolean shift = ( event.stateMask & SWT.SHIFT ) != 0;
boolean control = ( event.stateMask & SWT.CONTROL ) != 0;
if ( !shift && !control ) {
Rectangle clientArea = table.getTable().getClientArea();
Point pt = new Point( event.x, event.y );
int index = table.getTable().getTopIndex();
while ( index < table.getTable().getItemCount() ) {
boolean visible = false;
final TableItem item = table.getTable().getItem( index );
for ( int i = 0; i < table.getTable().getColumnCount(); i++ ) {
Rectangle rect = item.getBounds( i );
if ( !rect.contains( pt ) ) {
if ( i == table.getTable().getColumnCount() - 1 && // last column
pt.x > rect.x + rect.width && // to the right
pt.y >= rect.y && pt.y <= rect.y + rect.height // same height as this visible item
) {
return; // don't do anything when clicking to the right of the grid.
}
} else {
return;
}
if ( !visible && rect.intersects( clientArea ) ) {
visible = true;
}
}
if ( !visible ) {
return;
}
index++;
}
insertRowAtLast();
}
}
}
};
table.getTable().addMouseListener( lsMouseT );
table.getTable().addTraverseListener( new TraverseListener() {
public void keyTraversed( TraverseEvent arg0 ) {
if ( arg0.keyCode == SWT.ARROW_DOWN ) {
int[] rows = getSelectedRows();
if ( rows != null && rows.length > 0 && rows[0] == table.getTable().getItemCount() - 1 ) {
insertRowAtLast();
}
}
}
} );
table.addDoubleClickListener( new IDoubleClickListener() {
public void doubleClick( DoubleClickEvent arg0 ) {
if ( command != null ) {
if ( elements != null ) {
// Invoke with selected elements as parameter
invoke( command, new Object[] { getSelectedItems().toArray() } );
} else {
// Invoke with selected indexes as parameter
invoke( command, new Object[] { getSelectedRows() } );
}
}
}
} );
// Turn on the header and the lines
baseTable.setHeaderVisible( true );
baseTable.setLinesVisible( isTreeLines() );
table.setInput( this );
final Composite parentComposite = ( (Composite) parentComponent.getManagedObject() );
parentComposite.addControlListener( new ControlAdapter() {
public void controlResized( ControlEvent e ) {
resizeColumns();
}
} );
TableColumnSorter sorter = new TableColumnSorter( table, sortProperties );
table.getTable().setEnabled( !this.disabled );
table.refresh();
}
private void insertRowAtLast() {
if ( this.elements != null && newItemBinding != null ) { // Bound table.
invoke( newItemBinding );
} else if ( autoCreateNewRows ) {
getRootChildren().addNewRow();
update();
}
}
private Collection findSelectedTableRows( int[] selectedRows ) {
if ( elements == null ) {
return Collections.emptyList();
}
List selectedItems = new ArrayList();
for ( int i = 0; i < selectedRows.length; i++ ) {
if ( selectedRows[i] >= 0 && selectedRows[i] < elements.size() ) {
selectedItems.add( elements.toArray()[selectedRows[i]] );
}
}
return selectedItems;
}
private void resizeColumns() {
final Composite parentComposite = ( (Composite) parentComponent.getManagedObject() );
Rectangle area = parentComposite.getClientArea();
Point preferredSize = table.getTable().computeSize( SWT.DEFAULT, SWT.DEFAULT );
int width = area.width - 2 * table.getTable().getBorderWidth();
if ( preferredSize.y > area.height + table.getTable().getHeaderHeight() ) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
Point vBarSize = table.getTable().getVerticalBar().getSize();
width -= vBarSize.x;
}
width -= 20;
double totalFlex = 0;
for ( XulComponent col : getColumns().getChildNodes() ) {
totalFlex += ( (XulTreeCol) col ).getFlex();
}
int colIdx = 0;
for ( XulComponent col : getColumns().getChildNodes() ) {
if ( colIdx >= table.getTable().getColumnCount() ) {
break;
}
TableColumn c = table.getTable().getColumn( colIdx );
int colFlex = ( (XulTreeCol) col ).getFlex();
int colWidth = ( (XulTreeCol) col ).getWidth();
if ( totalFlex == 0 ) {
if ( colWidth > 0 ) {
c.setWidth( colWidth );
} else {
c.setWidth( Math.round( width / getColumns().getColumnCount() ) );
}
} else if ( colFlex > 0 ) {
if ( colWidth > 0 ) {
c.setWidth( colWidth );
} else {
c.setWidth( Integer.parseInt( "" + Math.round( width * ( colFlex / totalFlex ) ) ) );
}
}
colIdx++;
}
}
private void setSelectedIndex( int idx ) {
this.selectedIndex = idx;
changeSupport.firePropertyChange( "selectedRows", null, new int[] { idx } );
changeSupport.firePropertyChange( "absoluteSelectedRows", null, new int[] { idx } );
if ( this.onSelect != null ) {
invoke( this.onSelect, new Object[] { new Integer( idx ) } );
}
}
private void createColumnTypesSnapshot() {
if ( this.columns.getChildNodes().size() > 0 ) {
Object[] xulTreeColArray = this.columns.getChildNodes().toArray();
currentColumnTypes = new ColumnType[xulTreeColArray.length];
for ( int i = 0; i < xulTreeColArray.length; i++ ) {
currentColumnTypes[i] = ColumnType.valueOf( ( (XulTreeCol) xulTreeColArray[i] ).getType() );
}
} else {
// Create an empty array to indicate that it has been processed, but contains 0 columns
currentColumnTypes = new ColumnType[0];
}
}
private boolean columnsNeedUpdate() {
// Differing number of columsn
if ( table.getTable().getColumnCount() != this.columns.getColumnCount() ) {
return true;
}
// First run, always update
if ( currentColumnTypes == null ) {
return true;
}
// Column Types have changed
Object[] xulTreeColArray = this.columns.getChildNodes().toArray();
for ( int i = 0; i < xulTreeColArray.length; i++ ) {
XulTreeCol xulTreeCol = (XulTreeCol) xulTreeColArray[i];
if ( !currentColumnTypes[i].toString().equalsIgnoreCase( ( (XulTreeCol) xulTreeColArray[i] ).getType() ) ) {
// A column has changed its type. Columns need updating
return true;
}
if ( ( table.getTable().getColumn( i ).getWidth() > 0 && !xulTreeCol.isVisible() )
|| table.getTable().getColumn( i ).getWidth() == 0 && xulTreeCol.isVisible() ) {
// A column has changed its visible status
return true;
}
}
// Columns have not changed and do not need updating
return false;
}
private void setupColumns() {
if ( columnsNeedUpdate() ) {
sortProperties.setSortColumn( null );
while ( table.getTable().getColumnCount() > 0 ) {
table.getTable().getColumn( 0 ).dispose();
}
// Add Columns
for ( XulComponent col : this.columns.getChildNodes() ) {
TableColumn tc = new TableColumn( table.getTable(), SWT.LEFT );
XulTreeCol column = (XulTreeCol) col;
String lbl = column.getLabel();
tc.setText( lbl != null ? lbl : "" ); //$NON-NLS-1$
// Only process the first column that is deemed sortActive,
// since only one column is allowed sortActive at a time
if ( column.isSortActive() && sortProperties.getSortColumn() == null ) {
sortProperties.setSortColumn( tc );
sortProperties.setSortDirection( SortDirection.valueOf( column.getSortDirection() ) );
}
sortProperties.setSortMethod( tc, toGetter( column.getComparatorbinding() ) );
}
// Pack the columns
for ( int i = 0; i < table.getTable().getColumnCount(); i++ ) {
if ( this.columns.getColumn( i ).isVisible() ) {
table.getTable().getColumn( i ).pack();
}
}
}
if ( table.getCellEditors() != null ) {
for ( int i = 0; i < table.getCellEditors().length; i++ ) {
table.getCellEditors()[i].dispose();
}
}
CellEditor[] editors = new CellEditor[this.columns.getChildNodes().size()];
String[] names = new String[getColumns().getColumnCount()];
int i = 0;
for ( XulComponent c : this.columns.getChildNodes() ) {
XulTreeCol col = (XulTreeCol) c;
final int colIdx = i;
CellEditor editor;
ColumnType type = col.getColumnType();
switch ( type ) {
case CHECKBOX:
editor = new CheckboxCellEditor( table.getTable() );
break;
case COMBOBOX:
editor = new ComboBoxCellEditor( table.getTable(), new String[] {}, SWT.READ_ONLY );
break;
case EDITABLECOMBOBOX:
editor = new ComboBoxCellEditor( table.getTable(), new String[] {} );
final CCombo editableControl = (CCombo) ( (ComboBoxCellEditor) editor ).getControl();
editableControl.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent modifyEvent ) {
domContainer.invokeLater( new Runnable() {
@Override public void run() {
XulTreeCell cell = getCell( colIdx );
cell.setLabel( editableControl.getText() );
}
} );
}
} );
break;
case PASSWORD:
editor = new TextCellEditor( table.getTable() );
( (Text) editor.getControl() ).setEchoChar( '*' );
break;
case TEXT:
default:
editor = new TextCellEditor( table.getTable() );
final Text textControl = (Text) ( (TextCellEditor) editor ).getControl();
textControl.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent modifyEvent ) {
XulTreeCell cell = getCell( colIdx );
cell.setLabel( textControl.getText() );
}
} );
break;
}
// Create selection listener for comboboxes.
if ( type == ColumnType.EDITABLECOMBOBOX || type == ColumnType.COMBOBOX ) {
final CCombo editableControl = (CCombo) ( (ComboBoxCellEditor) editor ).getControl();
editableControl.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetDefaultSelected( SelectionEvent arg0 ) {
// TODO Auto-generated method stub
super.widgetDefaultSelected( arg0 );
}
@Override
public void widgetSelected( SelectionEvent arg0 ) {
super.widgetSelected( arg0 );
XulTreeCell cell = getCell( colIdx );
cell.setSelectedIndex( editableControl.getSelectionIndex() );
}
} );
}
editors[i] = editor;
names[i] = "" + i; //$NON-NLS-1$
i++;
}
table.setCellEditors( editors );
table.setColumnProperties( names );
resizeColumns();
createColumnTypesSnapshot();
}
private XulTreeCell getCell( int colIdx ) {
return ( (XulTreeItem) ( table.getTable().getSelection()[0] ).getData() ).getRow().getCell( colIdx );
}
public boolean isHierarchical() {
return isHierarchical;
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled( boolean disabled ) {
this.disabled = disabled;
if ( this.isHierarchical() == false && table != null ) {
table.getTable().setEnabled( !disabled );
}
}
public int getRows() {
return rowsToDisplay;
}
public void setRows( int rowsToDisplay ) {
this.rowsToDisplay = rowsToDisplay;
if ( table != null && ( !table.getTable().isDisposed() ) && ( rowsToDisplay > 0 ) ) {
int ht = rowsToDisplay * table.getTable().getItemHeight();
if ( table.getTable().getLayoutData() != null ) {
// tree.setSize(tree.getSize().x,height);
( (GridData) table.getTable().getLayoutData() ).heightHint = ht;
( (GridData) table.getTable().getLayoutData() ).minimumHeight = ht;
table.getTable().getParent().layout( true );
}
}
}
public enum SELECTION_MODE {
SINGLE, CELL, MULTIPLE
};
public String getSeltype() {
return selType.toString();
}
public void setSeltype( String selType ) {
if ( selType.equalsIgnoreCase( getSeltype() ) ) {
return; // nothing has changed
}
this.selType = TableSelection.valueOf( selType.toUpperCase() );
}
public TableSelection getTableSelection() {
return selType;
}
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
return enableColumnDrag;
}
public void setEditable( boolean edit ) {
editable = edit;
}
public void setEnableColumnDrag( boolean drag ) {
enableColumnDrag = drag;
}
public String getOnselect() {
return onSelect;
}
public void setOnselect( final String method ) {
if ( method == null ) {
return;
}
onSelect = method;
}
public void setColumns( XulTreeCols columns ) {
this.columns = columns;
}
public XulTreeCols getColumns() {
return columns;
}
public XulTreeChildren getRootChildren() {
if ( rootChildren == null ) {
rootChildren = (XulTreeChildren) this.getChildNodes().get( 1 );
}
return rootChildren;
}
public void setRootChildren( XulTreeChildren rootChildren ) {
this.rootChildren = rootChildren;
}
public int[] getActiveCellCoordinates() {
return new int[] { activeRow, activeColumn };
}
public void setActiveCellCoordinates( int row, int column ) {
activeRow = row;
activeColumn = column;
}
public Object[][] getValues() {
Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()];
int y = 0;
for ( XulComponent item : getRootChildren().getChildNodes() ) {
int x = 0;
for ( XulComponent tempCell : ( (XulTreeItem) item ).getRow().getChildNodes() ) {
XulTreeCell cell = (XulTreeCell) tempCell;
switch ( columns.getColumn( x ).getColumnType() ) {
case CHECKBOX:
Boolean flag = (Boolean) cell.getValue();
if ( flag == null ) {
flag = Boolean.FALSE;
}
data[y][x] = flag;
break;
case COMBOBOX:
Vector values = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
data[y][x] = values.get( idx );
break;
default: // label
data[y][x] = cell.getLabel();
break;
}
x++;
}
y++;
}
return data;
}
public Object getData() {
return data;
}
public void setData( Object data ) {
this.data = data;
}
public int[] getSelectedRows() {
if ( selectedIndex > -1 ) {
return new int[] { selectedIndex };
} else {
return new int[] {};
}
}
public int[] getAbsoluteSelectedRows() {
return getSelectedRows();
}
public Collection getSelectedItems() {
if ( elements == null ) {
return null;
}
if ( isHierarchical() ) {
List selectedItems = new ArrayList();
IStructuredSelection selection = (IStructuredSelection) tree.getSelection();
int i = 0;
for ( Object o : selection.toArray() ) {
XulTreeItem selectedItem = (XulTreeItem) o;
SearchBundle b = findSelectedIndex( new SearchBundle(), getRootChildren(), selectedItem );
selectedItems.add( b.selectedItem );
}
return selectedItems;
} else {
IStructuredSelection selection = (IStructuredSelection) table.getSelection();
setSelectedIndex( getRootChildren().getChildNodes().indexOf( selection.getFirstElement() ) );
int[] selectedRows = new int[selection.size()];
int i = 0;
for ( Iterator it = selection.iterator(); it.hasNext(); ) {
Object sel = it.next();
selectedRows[i] = getRootChildren().getChildNodes().indexOf( sel );
i++;
}
return findSelectedTableRows( selectedRows );
}
}
public void addTreeRow( XulTreeRow row ) {
this.addChild( row );
XulTreeItem item = new SwtTreeItem( this.getRootChildren() );
row.setParentTreeItem( item );
( (SwtTreeRow) row ).layout();
}
public void removeTreeRows( int[] rows ) {
// TODO Auto-generated method stub
}
public void update() {
if ( settingElements.get() ) {
return;
}
if ( this.isHierarchical ) {
this.tree.refresh();
if ( "true".equals( getAttributeValue( "expanded" ) ) ) {
tree.expandAll();
} else if ( expandBindings.size() > 0 && this.suppressEvents == false ) {
for ( Binding expBind : expandBindings ) {
try {
expBind.fireSourceChanged();
} catch ( Exception e ) {
logger.error( e );
}
}
expandBindings.clear();
}
resizeTreeColumn();
} else {
setupColumns();
this.table.setInput( this );
this.table.refresh();
}
this.selectedIndex = -1;
}
public void clearSelection() {
}
public void setSelectedRows( int[] rows ) {
if ( this.isHierarchical ) {
Object selected = getSelectedTreeItem( rows );
int prevSelected = -1;
if ( selectedRows != null && selectedRows.length > 0 ) {
prevSelected = selectedRows[0]; // single selection only for now
}
// tree.setSelection(new StructuredSelection(getSelectedTreeItems(rows)));
changeSupport.firePropertyChange( "selectedItem", prevSelected, selected );
} else {
table.getTable().setSelection( rows );
}
if ( rows.length > 0 ) {
this.selectedIndex = rows[0]; // single selection only for now
}
changeSupport.firePropertyChange( "selectedRows", this.selectedRows, rows );
changeSupport.firePropertyChange( "absoluteSelectedRows", this.selectedRows, rows );
this.selectedRows = rows;
}
public String getOnedit() {
return onedit;
}
public void setOnedit( String onedit ) {
this.onedit = onedit;
}
private Collection elements;
private boolean suppressEvents = false;
private final AtomicBoolean settingElements = new AtomicBoolean( false );
private String childrenBinding;
private String getChildrenBinding() {
if ( childrenBinding == null ) {
childrenBinding = ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding();
}
return childrenBinding;
}
int[] expandCache;
private void cacheExpandedState() {
Object[] expandedTreeItems = tree.getExpandedElements();
expandCache = new int[expandedTreeItems.length];
for ( int i = 0; i < expandedTreeItems.length; i++ ) {
XulTreeItem item = (XulTreeItem) expandedTreeItems[i];
SearchBundle b = findSelectedIndex( new SearchBundle(), getRootChildren(), item );
expandCache[i] = b.curPos;
}
}
private void restoreExpandedState() {
for ( int i = 0; i < expandCache.length; i++ ) {
XulTreeItem item = findTreeItemForPos( expandCache[i] );
if ( item != null ) {
tree.setExpandedState( item, true );
}
}
}
private XulTreeItem findTreeItemForPos( int pos ) {
if ( !isHierarchical() ) {
return (XulTreeItem) getTreeChildren( this ).getChildNodes().get( pos );
} else {
FindTreeItemForPosTuple tuple = new FindTreeItemForPosTuple( pos, this );
findTreeItemAtPosFunc( tuple );
return tuple.treeItem;
}
}
private void findTreeItemAtPosFunc( FindTreeItemForPosTuple bundle ) {
if ( bundle.curPos == bundle.pos ) {
bundle.found = true;
bundle.treeItem = (XulTreeItem) bundle.curComponent;
return;
}
XulTreeChildren children = getTreeChildren( bundle.curComponent );
if ( children == null ) {
return;
}
for ( XulComponent c : getTreeChildren( bundle.curComponent ).getChildNodes() ) {
bundle.curPos++;
bundle.curComponent = c;
findTreeItemAtPosFunc( bundle );
if ( bundle.found ) {
return;
}
}
}
private static class FindTreeItemForPosTuple {
int pos;
int curPos = -1;
XulComponent curComponent;
XulTreeItem treeItem;
boolean found;
public FindTreeItemForPosTuple( int pos, XulComponent curComponent ) {
this.pos = pos;
this.curComponent = curComponent;
}
}
private void destroyPreviousBindings() {
for ( Binding bind : elementBindings ) {
bind.destroyBindings();
}
elementBindings.clear();
}
public <T> void setElements( Collection<T> elements ) {
settingElements.set( true );
try {
// If preserveselection is set to true in the xul file. We will honor that and save the selection before
// setting the elements. After the setElements is done we will set the current selected selection
int scrollPos = -1;
if ( this.isHierarchical ) {
if ( isPreserveexpandedstate() ) {
cacheExpandedState();
}
scrollPos = tree.getTree().getVerticalBar().getSelection();
}
destroyPreviousBindings();
this.elements = elements;
this.getRootChildren().removeAll();
if ( elements == null ) {
update();
changeSupport.firePropertyChange( "selectedRows", null, getSelectedRows() );
changeSupport.firePropertyChange( "absoluteSelectedRows", null, getAbsoluteSelectedRows() );
return;
}
try {
if ( this.isHierarchical == false ) {
for ( T o : elements ) {
XulTreeRow row = this.getRootChildren().addNewRow();
// Give the Xul Element a reference back to the domain object
( (XulTreeItem) row.getParent() ).setBoundObject( o );
for ( int x = 0; x < this.getColumns().getChildNodes().size(); x++ ) {
XulComponent col = this.getColumns().getColumn( x );
final XulTreeCell cell = (XulTreeCell) getDocument().createElement( "treecell" );
XulTreeCol column = (XulTreeCol) col;
for ( InlineBindingExpression exp : ( (XulTreeCol) col ).getBindingExpressions() ) {
if ( logger.isDebugEnabled() ) {
logger
.debug( "applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + o
+ "]" );
}
String colType = column.getType();
if ( StringUtils.isEmpty( colType ) == false && colType.equals( "dynamic" ) ) {
colType = extractDynamicColType( o, x );
}
if ( ( colType.equalsIgnoreCase( "combobox" ) || colType.equalsIgnoreCase( "editablecombobox" ) )
&& column.getCombobinding() != null ) {
Binding binding = createBinding( (XulEventSource) o, column.getCombobinding(), cell, "value" );
elementBindings.add( binding );
binding.setBindingType( Binding.Type.ONE_WAY );
domContainer.addBinding( binding );
binding.fireSourceChanged();
binding =
createBinding( (XulEventSource) o, ( (XulTreeCol) col ).getBinding(), cell, "selectedIndex" );
elementBindings.add( binding );
binding.setConversion( new BindingConvertor<Object, Integer>() {
@Override
public Integer sourceToTarget( Object value ) {
int index = ( (Vector) cell.getValue() ).indexOf( value );
return index > -1 ? index : 0;
}
@Override
public Object targetToSource( Integer value ) {
return ( (Vector) cell.getValue() ).get( value );
}
} );
domContainer.addBinding( binding );
binding.fireSourceChanged();
if ( colType.equalsIgnoreCase( "editablecombobox" ) ) {
binding = createBinding( (XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr() );
elementBindings.add( binding );
if ( !this.editable ) {
binding.setBindingType( Binding.Type.ONE_WAY );
} else {
binding.setBindingType( Binding.Type.BI_DIRECTIONAL );
}
domContainer.addBinding( binding );
}
} else if ( colType.equalsIgnoreCase( "checkbox" ) ) {
if ( StringUtils.isNotEmpty( exp.getModelAttr() ) ) {
Binding binding = createBinding( (XulEventSource) o, exp.getModelAttr(), cell, "value" );
elementBindings.add( binding );
if ( !column.isEditable() ) {
binding.setBindingType( Binding.Type.ONE_WAY );
}
domContainer.addBinding( binding );
binding.fireSourceChanged();
}
} else {
if ( StringUtils.isNotEmpty( exp.getModelAttr() ) ) {
Binding binding =
createBinding( (XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr() );
elementBindings.add( binding );
if ( !column.isEditable() ) {
binding.setBindingType( Binding.Type.ONE_WAY );
}
domContainer.addBinding( binding );
binding.fireSourceChanged();
} else {
cell.setLabel( o.toString() );
}
}
}
if ( column.getDisabledbinding() != null ) {
String prop = column.getDisabledbinding();
Binding bind = createBinding( (XulEventSource) o, column.getDisabledbinding(), cell, "disabled" );
elementBindings.add( bind );
bind.setBindingType( Binding.Type.ONE_WAY );
domContainer.addBinding( bind );
bind.fireSourceChanged();
}
Method imageMethod;
String imageSrc = null;
String method = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( x ) ).getImagebinding() );
if ( method != null ) {
imageMethod = o.getClass().getMethod( method );
imageSrc = (String) imageMethod.invoke( o );
SwtTreeItem item = (SwtTreeItem) row.getParent();
item.setXulDomContainer( this.domContainer );
( (XulTreeItem) row.getParent() ).setImage( imageSrc );
}
row.addCell( cell );
}
}
} else {
// tree
suppressEvents = true;
if ( isHiddenrootnode() == false ) {
SwtTreeItem item = new SwtTreeItem( this.getRootChildren() );
item.setXulDomContainer( this.domContainer );
item.setBoundObject( elements );
SwtTreeRow newRow = new SwtTreeRow( item );
item.setRow( newRow );
this.getRootChildren().addChild( item );
addTreeChild( elements, newRow );
} else {
for ( T o : elements ) {
SwtTreeItem item = new SwtTreeItem( this.getRootChildren() );
item.setXulDomContainer( this.domContainer );
item.setBoundObject( o );
SwtTreeRow newRow = new SwtTreeRow( item );
item.setRow( newRow );
this.getRootChildren().addChild( item );
addTreeChild( o, newRow );
}
}
suppressEvents = false;
}
update();
if ( this.isHierarchical ) {
if ( isPreserveexpandedstate() ) {
restoreExpandedState();
}
final int fScrollPos = scrollPos;
}
// Now since we are done with setting the elements, we will now see if preserveselection was set to be true
// then we will set the selected items to the currently saved one
if ( isPreserveselection() && currentSelectedItems != null && currentSelectedItems.size() > 0 ) {
setSelectedItems( currentSelectedItems );
suppressEvents = false;
} else {
// treat as a selection change
suppressEvents = false;
changeSupport.firePropertyChange( "selectedRows", null, getSelectedRows() );
changeSupport.firePropertyChange( "absoluteSelectedRows", null, getAbsoluteSelectedRows() );
changeSupport.firePropertyChange( "selectedItems", null, Collections.EMPTY_LIST );
changeSupport.firePropertyChange( "selectedItem", "", null );
}
} catch ( XulException e ) {
logger.error( "error adding elements", e );
} catch ( Exception e ) {
logger.error( "error adding elements", e );
}
} finally {
settingElements.set( false );
update();
}
}
private List<Binding> expandBindings = new ArrayList<Binding>();
private TreeLabelBindingConvertor treeLabelConvertor = new TreeLabelBindingConvertor( this );
private <T> void addTreeChild( T element, XulTreeRow row ) {
try {
SwtTreeCell cell = (SwtTreeCell) getDocument().createElement( "treecell" );
for ( InlineBindingExpression exp : ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) )
.getBindingExpressions() ) {
if ( logger.isDebugEnabled() ) {
logger
.debug( "applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + element
+ "]" );
}
// Tree Bindings are one-way for now as you cannot edit tree nodes
Binding binding = createBinding( (XulEventSource) element, exp.getModelAttr(), cell, exp.getXulCompAttr() );
elementBindings.add( binding );
binding.setConversion( treeLabelConvertor );
if ( this.isEditable() ) {
binding.setBindingType( Binding.Type.BI_DIRECTIONAL );
} else {
binding.setBindingType( Binding.Type.ONE_WAY );
}
domContainer.addBinding( binding );
binding.fireSourceChanged();
}
// TODO: migrate this into the XulComponent
cell.addPropertyChangeListener( "label", cellChangeListener );
XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get( 0 );
String expBind = column.getExpandedbinding();
if ( expBind != null ) {
Binding binding = createBinding( (XulEventSource) element, expBind, row.getParent(), "expanded" );
elementBindings.add( binding );
binding.setBindingType( Binding.Type.BI_DIRECTIONAL );
domContainer.addBinding( binding );
expandBindings.add( binding );
}
if ( column.getDisabledbinding() != null ) {
String prop = column.getDisabledbinding();
Binding bind =
createBinding( (XulEventSource) element, column.getDisabledbinding(), row.getParent(), "disabled" );
elementBindings.add( bind );
bind.setBindingType( Binding.Type.ONE_WAY );
domContainer.addBinding( bind );
bind.fireSourceChanged();
}
if ( column.getTooltipbinding() != null ) {
String prop = column.getTooltipbinding();
Binding bind =
createBinding( (XulEventSource) element, column.getTooltipbinding(), row.getParent(), "tooltiptext" );
elementBindings.add( bind );
bind.setBindingType( Binding.Type.ONE_WAY );
domContainer.addBinding( bind );
bind.fireSourceChanged();
}
row.addCell( cell );
// find children
String method = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
Method childrenMethod = null;
try {
childrenMethod = element.getClass().getMethod( method, new Class[] {} );
} catch ( NoSuchMethodException e ) {
logger.debug( "Could not find children binding method for object: " + element.getClass().getSimpleName() );
}
method = ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getImagebinding();
if ( method != null ) {
Binding binding = createBinding( (XulEventSource) element, method, row.getParent(), "image" );
elementBindings.add( binding );
binding.setBindingType( Binding.Type.ONE_WAY );
domContainer.addBinding( binding );
binding.fireSourceChanged();
}
Collection<T> children = null;
if ( childrenMethod != null ) {
children = (Collection<T>) childrenMethod.invoke( element, new Object[] {} );
} else if ( element instanceof Collection ) {
children = (Collection<T>) element;
}
XulTreeChildren treeChildren = null;
if ( children != null && children.size() > 0 ) {
treeChildren = (XulTreeChildren) getDocument().createElement( "treechildren" );
row.getParent().addChild( treeChildren );
}
if ( children == null ) {
return;
}
for ( T child : children ) {
SwtTreeItem item = new SwtTreeItem( treeChildren );
item.setXulDomContainer( this.domContainer );
SwtTreeRow newRow = new SwtTreeRow( item );
item.setRow( newRow );
item.setBoundObject( child );
treeChildren.addChild( item );
addTreeChild( child, newRow );
}
} catch ( Exception e ) {
logger.error( "error adding elements", e );
}
}
public <T> Collection<T> getElements() {
return null;
}
private String extractDynamicColType( Object row, int columnPos ) {
try {
Method method = row.getClass().getMethod( this.columns.getColumn( columnPos ).getColumntypebinding() );
return (String) method.invoke( row, new Object[] {} );
} catch ( Exception e ) {
logger.debug( "Could not extract column type from binding" );
}
return "text"; // default //$NON-NLS-1$
}
private static String toGetter( String property ) {
if ( property == null ) {
return null;
}
return "get" + ( property.substring( 0, 1 ).toUpperCase() + property.substring( 1 ) );
}
public Object getSelectedItem() {
Collection c = getSelectedItems();
if ( c != null && c.size() > 0 ) {
return c.toArray()[0];
}
return null;
}
// private List<Object> getSelectedTreeItems(int[] currentSelection) {
// if (this.isHierarchical && this.elements != null) {
// int[] vals = currentSelection;
// if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) {
// return null;
// String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding());
// List<Object> selection = new ArrayList<Object>();
// for(int pos : currentSelection){
// FindBoundItemTuple tuple = new FindBoundItemTuple(pos);
// findBoundItem(this.elements, this, property, tuple);
// selection.add(tuple.treeItem);
// return selection;
// return null;
private Object getSelectedTreeItem( int[] currentSelection ) {
if ( this.isHierarchical && this.elements != null ) {
int[] vals = currentSelection;
if ( vals == null || vals.length == 0 || elements == null || elements.size() == 0 ) {
return null;
}
String property = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
int selectedIdx = vals[0];
if ( selectedIdx == -1 ) {
return null;
}
FindSelectedItemTuple tuple =
findSelectedItem( this.elements, property, new FindSelectedItemTuple( selectedIdx, this.isHiddenrootnode() ) );
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private void fireSelectedItem() {
this.changeSupport.firePropertyChange( "selectedItem", null, getSelectedItem() );
}
private static class FindSelectedItemTuple {
Object selectedItem = null;
int curpos = -1; // ignores first element (root)
int selectedIndex;
public FindSelectedItemTuple( int selectedIndex, boolean rootHidden ) {
this.selectedIndex = selectedIndex;
if ( rootHidden == false ) {
curpos = 0;
}
}
}
private void removeItemFromElements( Object item, DropEvent event ) {
String method = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
removeItem( elements, method, item, event );
}
private void removeItem( Object parent, String childrenMethodProperty, Object toRemove, DropEvent event ) {
Collection children = getChildCollection( parent, childrenMethodProperty );
if ( children == null ) {
return;
}
Iterator iter = children.iterator();
int pos = 0;
while ( iter.hasNext() ) {
Object next = iter.next();
if ( next == toRemove ) {
// check to see if DnD is same origin, if so index needs to be adjusted
if ( event.getDropParent() == children && event.getDropIndex() > pos ) {
event.setDropIndex( event.getDropIndex() - 1 );
}
children.remove( toRemove );
return;
}
removeItem( next, childrenMethodProperty, toRemove, event );
pos++;
}
}
private FindSelectedItemTuple findSelectedItem( Object parent, String childrenMethodProperty,
FindSelectedItemTuple tuple ) {
if ( tuple.curpos == tuple.selectedIndex ) {
tuple.selectedItem = parent;
return tuple;
}
Collection children = getChildCollection( parent, childrenMethodProperty );
if ( children == null || children.size() == 0 ) {
return null;
}
for ( Object child : children ) {
tuple.curpos++;
findSelectedItem( child, childrenMethodProperty, tuple );
if ( tuple.selectedItem != null ) {
return tuple;
}
}
return null;
}
public void registerCellEditor( String key, TreeCellEditor editor ) {
// TODO Auto-generated method stub
}
public void registerCellRenderer( String key, TreeCellRenderer renderer ) {
// TODO Auto-generated method stub
}
public void collapseAll() {
if ( this.isHierarchical ) {
tree.collapseAll();
}
}
public void expandAll() {
if ( this.isHierarchical ) {
tree.expandAll();
}
}
private static class FindBoundItemTuple {
Object item = null;
XulComponent treeItem;
public FindBoundItemTuple( Object item ) {
this.item = item;
}
}
private static Collection getChildCollection( Object obj, String childrenMethodProperty ) {
Collection children = null;
Method childrenMethod = null;
try {
childrenMethod = obj.getClass().getMethod( childrenMethodProperty, new Class[] {} );
} catch ( NoSuchMethodException e ) {
if ( obj instanceof Collection ) {
children = (Collection) obj;
}
}
try {
if ( childrenMethod != null ) {
children = (Collection) childrenMethod.invoke( obj, new Object[] {} );
}
} catch ( Exception e ) {
logger.error( e );
return null;
}
return children;
}
private XulTreeChildren getTreeChildren( XulComponent parent ) {
// Top node is an exception when showing root
if ( parent == this && this.isHiddenrootnode() == false ) {
List<XulComponent> childNodes = this.getRootChildren().getChildNodes();
if ( childNodes.size() > 0 ) {
parent = childNodes.get( 0 );
} else {
return null;
}
}
for ( XulComponent c : parent.getChildNodes() ) {
if ( c instanceof XulTreeChildren ) {
return (XulTreeChildren) c;
}
}
return null;
}
private FindBoundItemTuple findBoundItem( Object obj, XulComponent parent, String childrenMethodProperty,
FindBoundItemTuple tuple ) {
if ( obj.equals( tuple.item ) ) {
tuple.treeItem = parent;
return tuple;
}
Collection children = getChildCollection( obj, childrenMethodProperty );
if ( children == null || children.size() == 0 ) {
return null;
}
XulTreeChildren xulChildren = getTreeChildren( parent );
Object[] childrenArry = children.toArray();
for ( int i = 0; i < children.size(); i++ ) {
findBoundItem( childrenArry[i], xulChildren.getChildNodes().get( i ), childrenMethodProperty, tuple );
if ( tuple.treeItem != null ) {
return tuple;
}
}
return null;
}
public void setBoundObjectExpanded( Object o, boolean expanded ) {
FindBoundItemTuple tuple = new FindBoundItemTuple( o );
String property = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
findBoundItem( this.elements, this, property, tuple );
if ( tuple.treeItem != null ) {
setTreeItemExpanded( (XulTreeItem) tuple.treeItem, expanded );
}
}
public void setTreeItemExpanded( XulTreeItem item, boolean expanded ) {
if ( this.isHierarchical ) {
tree.setExpandedState( item, expanded );
}
}
@Override
public void setPopup( final IMenuManager menuMgr ) {
final Control control;
if ( isHierarchical() ) {
control = tree.getControl();
} else {
control = table.getControl();
}
Menu menu = ( (MenuManager) menuMgr ).createContextMenu( control );
control.setMenu( menu );
control.addListener( SWT.MenuDetect, new Listener() {
public void handleEvent( Event evt ) {
Point pt = control.getDisplay().map( control, null, new Point( evt.x, evt.y ) );
Menu menu = control.getMenu();
menu.setLocation( evt.x, evt.y );
menu.setVisible( true );
}
} );
}
protected Control getDndObject() {
Control control;
if ( isHierarchical() ) {
control = (Control) tree.getControl();
} else {
control = (Control) table.getControl();
}
return control;
}
protected List<Object> cachedDndItems;
@Override
protected List<Object> getSwtDragData() {
// if bound, return a list of bound objects, otherwise return strings.
// note, all of these elements must be serializable.
if ( elements != null ) {
cachedDndItems = (List<Object>) getSelectedItems();
} else {
IStructuredSelection selection;
if ( !isHierarchical ) {
selection = (IStructuredSelection) tree.getSelection();
} else {
selection = (IStructuredSelection) table.getSelection();
}
List<Object> list = new ArrayList<Object>();
int i = 0;
for ( Object o : selection.toArray() ) {
list.add( ( (XulTreeItem) o ).getRow().getCell( 0 ).getLabel() );
}
cachedDndItems = list;
}
return cachedDndItems;
}
@Override
protected void resolveDndParentAndIndex( DropEvent xulEvent ) {
Object parentObj = null;
int index = -1;
if ( !isHierarchical ) {
DropTargetEvent event = (DropTargetEvent) xulEvent.getNativeEvent();
if ( event.item != null ) {
TableItem item = (TableItem) event.item;
if ( item != null ) {
if ( elements != null ) {
// swt -> xul -> element
if ( item.getData() instanceof SwtTreeItem ) {
SwtTreeItem treeItem = (SwtTreeItem) item.getData();
parentObj = treeItem.getBoundObject();
}
} else {
parentObj = item.getText();
}
}
index = 0;
}
} else {
TreeItem parent = null;
DropTargetEvent event = (DropTargetEvent) xulEvent.getNativeEvent();
if ( event.item != null ) {
TreeItem item = (TreeItem) event.item;
Point pt = tree.getControl().getDisplay().map( null, tree.getControl(), event.x, event.y );
Rectangle bounds = item.getBounds();
parent = item.getParentItem();
if ( parent != null ) {
TreeItem[] items = parent.getItems();
index = 0;
for ( int i = 0; i < items.length; i++ ) {
if ( items[i] == item ) {
index = i;
break;
}
}
if ( pt.y > bounds.y + 2 * bounds.height / 3 ) {
// HANDLE parent, index + 1
index++;
} else {
parent = item;
index = 0;
}
} else {
TreeItem[] items = tree.getTree().getItems();
index = 0;
for ( int i = 0; i < items.length; i++ ) {
if ( items[i] == item ) {
index = i;
break;
}
}
if ( pt.y > bounds.y + 2 * bounds.height / 3 ) {
index++;
} else {
// item is parent
parent = item;
index = 0;
}
}
}
if ( parent != null ) {
if ( elements != null ) {
// swt -> xul -> element
SearchBundle b = findSelectedIndex( new SearchBundle(), getRootChildren(), (XulTreeItem) parent.getData() );
parentObj = b.selectedItem;
} else {
parentObj = parent.getText();
}
}
}
xulEvent.setDropParent( parentObj );
xulEvent.setDropIndex( index );
}
@Override
protected void onSwtDragDropAccepted( DropEvent xulEvent ) {
List results = xulEvent.getDataTransfer().getData();
if ( elements != null ) {
// place the new elements in the new location
Collection insertInto = elements;
if ( xulEvent.getDropParent() != null ) {
String method = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
insertInto = getChildCollection( xulEvent.getDropParent(), method );
}
if ( insertInto instanceof List ) {
List list = (List) insertInto;
if ( xulEvent.getDropIndex() == -1 ) {
for ( Object o : results ) {
list.add( o );
}
} else {
for ( int i = results.size() - 1; i >= 0; i
list.add( xulEvent.getDropIndex(), results.get( i ) );
}
}
}
// todo, can i trigger this through another mechanism?
setElements( elements );
}
}
@Override
protected void onSwtDragFinished( DropEffectType effect, DropEvent event ) {
if ( effect == DropEffectType.MOVE ) {
// ISelection sel = tree.getSelection();
if ( elements != null ) {
// remove cachedDndItems from the tree.. traverse
for ( Object item : cachedDndItems ) {
removeItemFromElements( item, event );
}
cachedDndItems = null;
setElements( elements );
} else {
if ( isHierarchical() ) {
tree.remove( tree.getSelection() );
} else {
table.remove( table.getSelection() );
}
}
}
}
@Override
public void setDropvetoer( String dropVetoMethod ) {
if ( StringUtils.isEmpty( dropVetoMethod ) ) {
return;
}
super.setDropvetoer( dropVetoMethod );
}
private void resolveDropVetoerMethod() {
if ( dropVetoerMethod == null && getDropvetoer() != null ) {
String id = getDropvetoer().substring( 0, getDropvetoer().indexOf( "." ) );
try {
XulEventHandler controller = this.domContainer.getEventHandler( id );
this.dropVetoerMethod =
controller.getClass().getMethod(
getDropvetoer().substring( getDropvetoer().indexOf( "." ) + 1, getDropvetoer().indexOf( "(" ) ),
new Class[] { DropEvent.class } );
this.dropVetoerController = controller;
} catch ( XulException e ) {
e.printStackTrace();
} catch ( NoSuchMethodException e ) {
e.printStackTrace();
}
}
}
private DropPosition curPos;
protected void onSwtDragOver( DropTargetEvent dropEvent ) {
dropEvent.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
if ( dropEvent.item != null ) {
Rectangle bounds = null;
Point pt = null;
if ( isHierarchical() ) {
TreeItem item = (TreeItem) dropEvent.item;
pt = tree.getControl().getDisplay().map( null, tree.getControl(), dropEvent.x, dropEvent.y );
bounds = item.getBounds();
} else {
TableItem item = (TableItem) dropEvent.item;
pt = table.getControl().getDisplay().map( null, table.getControl(), dropEvent.x, dropEvent.y );
bounds = item.getBounds();
}
if ( pt.y < bounds.y + bounds.height / 3 ) {
curPos = DropPosition.ABOVE;
} else if ( pt.y > bounds.y + 2 * ( bounds.height / 3 ) ) {
curPos = DropPosition.BELOW;
} else {
curPos = DropPosition.MIDDLE;
}
resolveDropVetoerMethod();
DropEvent event = SwtDragManager.getInstance().getCurrentDropEvent();
if ( dropVetoerMethod != null ) {
XulTreeItem xulItem = (XulTreeItem) dropEvent.item.getData();
if ( curPos == DropPosition.MIDDLE ) {
event.setDropParent( xulItem.getBoundObject() );
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if ( parent instanceof SwtTree ) {
parentObj = SwtTree.this.elements;
} else {
parentObj = ( (XulTreeItem) parent ).getBoundObject();
}
event.setDropParent( parentObj );
}
event.setNativeEvent( dropEvent );
event.setAccepted( true );
resolveDndParentAndIndex( event );
event.setDropPosition( curPos );
// if(curPos == DropPosition.MIDDLE){
// event.setDropParent(xulItem.getBoundObject());
// } else {
// XulComponent parent = xulItem.getParent().getParent();
// Object parentObj;
// if(parent instanceof GwtTree){
// parentObj = GwtTree.this.elements;
// } else {
// parentObj = ((XulTreeItem) parent).getBoundObject();
// event.setDropParent(parentObj);
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke( dropVetoerController, new Object[] { event } );
} catch ( InvocationTargetException e ) {
e.printStackTrace();
} catch ( IllegalAccessException e ) {
e.printStackTrace();
}
}
if ( event.isAccepted() == false ) {
dropEvent.feedback = DND.FEEDBACK_NONE;
} else if ( pt.y < bounds.y + bounds.height / 3 ) {
dropEvent.feedback |= DND.FEEDBACK_INSERT_BEFORE;
} else if ( pt.y > bounds.y + 2 * ( bounds.height / 3 ) ) {
dropEvent.feedback |= DND.FEEDBACK_INSERT_AFTER;
} else {
dropEvent.feedback |= DND.FEEDBACK_SELECT;
}
}
}
public <T> void setSelectedItems( Collection<T> items ) {
int[] selIndexes = new int[items.size()];
if ( this.isHierarchical && this.elements != null ) {
List<Object> selection = new ArrayList<Object>();
String property = toGetter( ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding() );
for ( T t : items ) {
FindBoundItemTuple tuple = new FindBoundItemTuple( t );
findBoundItem( this.elements, this, property, tuple );
XulComponent bItem = tuple.treeItem;
if ( tuple.treeItem == this ) { // Selecting top-level handled specially.
bItem = this.getRootChildren().getChildNodes().get( 0 );
}
if ( bItem != null ) {
selection.add( bItem );
}
}
tree.setSelection( new StructuredSelection( selection ) );
} else {
int pos = 0;
for ( T t : items ) {
selIndexes[pos++] = findIndexOfItem( t );
}
this.setSelectedRows( selIndexes );
}
}
public int findIndexOfItem( Object o ) {
String property = ( (XulTreeCol) this.getColumns().getChildNodes().get( 0 ) ).getChildrenbinding();
property = "get" + ( property.substring( 0, 1 ).toUpperCase() + property.substring( 1 ) );
Method childrenMethod = null;
try {
childrenMethod = elements.getClass().getMethod( property, new Class[] {} );
} catch ( NoSuchMethodException e ) {
// Since this tree is built recursively, when at a leaf it will throw this exception.
logger.debug( e );
}
FindSelectedIndexTuple tuple = findSelectedItem( this.elements, childrenMethod, new FindSelectedIndexTuple( o ) );
return tuple.selectedIndex;
}
private static class FindSelectedIndexTuple {
Object selectedItem = null;
Object currentItem = null; // ignores first element (root)
int curpos = -1; // ignores first element (root)
int selectedIndex = -1;
public FindSelectedIndexTuple( Object selectedItem ) {
this.selectedItem = selectedItem;
}
}
private FindSelectedIndexTuple findSelectedItem( Object parent, Method childrenMethod, FindSelectedIndexTuple tuple ) {
if ( tuple.selectedItem == parent ) {
tuple.selectedIndex = tuple.curpos;
return tuple;
}
Collection children = null;
if ( childrenMethod != null ) {
try {
children = (Collection) childrenMethod.invoke( parent, new Object[] {} );
} catch ( Exception e ) {
logger.error( e );
return tuple;
}
} else if ( parent instanceof List ) {
children = (List) parent;
}
if ( children == null || children.size() == 0 ) {
return null;
}
for ( Object child : children ) {
tuple.curpos++;
findSelectedItem( child, childrenMethod, tuple );
if ( tuple.selectedIndex > -1 ) {
return tuple;
}
}
return tuple;
}
public boolean isHiddenrootnode() {
return hiddenRoot;
}
public void setHiddenrootnode( boolean hidden ) {
this.hiddenRoot = hidden;
}
public String getCommand() {
return command;
}
public void setCommand( String command ) {
this.command = command;
}
public boolean isPreserveexpandedstate() {
return preserveExpandedState;
}
public void setPreserveexpandedstate( boolean preserve ) {
this.preserveExpandedState = preserve;
}
private static class TreeLabelBindingConvertor extends BindingConvertor<String, String> {
private SwtTree tree;
public TreeLabelBindingConvertor( SwtTree tree ) {
this.tree = tree;
}
@Override
public String sourceToTarget( String value ) {
return value;
}
@Override
public String targetToSource( String value ) {
tree.update();
return value;
}
}
public boolean isSortable() {
return sortProperties.isSortable();
}
public void setSortable( boolean sortable ) {
sortProperties.setSortable( sortable );
}
public boolean isTreeLines() {
return linesVisible;
}
public void setTreeLines( boolean visible ) {
linesVisible = visible;
}
public void setNewitembinding( String binding ) {
newItemBinding = binding;
}
public String getNewitembinding() {
return newItemBinding;
}
public void setAutocreatenewrows( boolean auto ) {
this.autoCreateNewRows = auto;
}
public boolean getAutocreatenewrows() {
return autoCreateNewRows;
}
public boolean isPreserveselection() {
return preserveSelection;
}
public void setPreserveselection( boolean preserve ) {
preserveSelection = preserve;
}
private Binding createBinding( XulEventSource source, String prop1, XulEventSource target, String prop2 ) {
if ( bindingProvider != null ) {
return bindingProvider.getBinding( source, prop1, target, prop2 );
}
return new DefaultBinding( source, prop1, target, prop2 );
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.