answer
stringlengths
17
10.2M
package pixy.meta.jpeg; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import pixy.image.tiff.IFD; import pixy.image.tiff.TiffTag; import pixy.image.jpeg.COMBuilder; import pixy.image.jpeg.Component; import pixy.image.jpeg.DHTReader; import pixy.image.jpeg.DQTReader; import pixy.image.jpeg.HTable; import pixy.image.jpeg.Marker; import pixy.image.jpeg.QTable; import pixy.image.jpeg.SOFReader; import pixy.image.jpeg.SOSReader; import pixy.image.jpeg.Segment; import pixy.image.jpeg.UnknownSegment; import pixy.io.FileCacheRandomAccessInputStream; import pixy.io.IOUtils; import pixy.io.RandomAccessInputStream; import pixy.string.Base64; import pixy.string.StringUtils; import pixy.string.XMLUtils; import pixy.util.ArrayUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import pixy.meta.Metadata; import pixy.meta.MetadataType; import pixy.meta.Thumbnail; import pixy.meta.adobe.IRB; import pixy.meta.adobe.ImageResourceID; import pixy.meta.adobe._8BIM; import pixy.meta.exif.Exif; import pixy.meta.exif.ExifThumbnail; import pixy.meta.adobe.ThumbnailResource; import pixy.meta.icc.ICCProfile; import pixy.meta.image.ImageMetadata; import pixy.meta.image.Comments; import pixy.meta.iptc.IPTC; import pixy.meta.iptc.IPTCDataSet; import pixy.meta.iptc.IPTCTag; import pixy.meta.xmp.XMP; import pixy.util.MetadataUtils; /** * JPEG image tweaking tool * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 01/25/2013 */ public class JPGMeta { // Constants public static final String XMP_ID = "http://ns.adobe.com/xap/1.0/\0"; // This is a non_standard XMP identifier which sometimes found in images from GettyImages public static final String NON_STANDARD_XMP_ID = "XMP\0://ns.adobe.com/xap/1.0/\0"; public static final String XMP_EXT_ID = "http://ns.adobe.com/xmp/extension/\0"; // Photoshop IRB identification with trailing byte [0x00]. public static final String PHOTOSHOP_IRB_ID = "Photoshop 3.0\0"; // EXIF identifier with trailing bytes [0x00, 0x00]. public static final String EXIF_ID = "Exif\0\0"; // ICC_PROFILE identifier with trailing byte [0x00]. public static final String ICC_PROFILE_ID = "ICC_PROFILE\0"; public static final String JFIF_ID = "JFIF\0"; // JFIF public static final String JFXX_ID = "JFXX\0"; // JFXX public static final String DUCKY_ID = "Ducky"; // no trailing NULL public static final String PICTURE_INFO_ID = "[picture info]"; // no trailing NULL public static final String ADOBE_ID = "Adobe"; // no trailing NULL public static final EnumSet<Marker> APPnMarkers = EnumSet.range(Marker.APP0, Marker.APP15); // Obtain a logger instance private static final Logger LOGGER = LoggerFactory.getLogger(JPGMeta.class); private static short copySegment(short marker, InputStream is, OutputStream os) throws IOException { int length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, buf); return (IOUtils.readShortMM(is)); } /** Copy a single SOS segment */ @SuppressWarnings("unused") private static short copySOS(InputStream is, OutputStream os) throws IOException { // Need special treatment. int nextByte = 0; short marker = 0; while((nextByte = IOUtils.read(is)) != -1) { if(nextByte == 0xff) { nextByte = IOUtils.read(is); if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } if (nextByte != 0x00) { // This is a marker marker = (short)((0xff<<8)|nextByte); switch (Marker.fromShort(marker)) { case RST0: case RST1: case RST2: case RST3: case RST4: case RST5: case RST6: case RST7: IOUtils.writeShortMM(os, marker); continue; default: } break; } IOUtils.write(os, 0xff); IOUtils.write(os, nextByte); } else { IOUtils.write(os, nextByte); } } if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } return marker; } private static void copyToEnd(InputStream is, OutputStream os) throws IOException { byte[] buffer = new byte[10240]; // 10k buffer int bytesRead = -1; while((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } public static byte[] extractICCProfile(InputStream is) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); // Flag when we are done boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.EOI) { finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. marker = IOUtils.readShortMM(is); break; case PADDING: int nextByte = 0; while((nextByte = IOUtils.read(is)) == 0xff) {;} marker = (short)((0xff<<8)|nextByte); break; case SOS: //marker = skipSOS(is); finished = true; break; case APP2: readAPP2(is, bo); marker = IOUtils.readShortMM(is); break; default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); marker = IOUtils.readShortMM(is); } } } return bo.toByteArray(); } public static void extractICCProfile(InputStream is, String pathToICCProfile) throws IOException { byte[] icc_profile = extractICCProfile(is); if(icc_profile != null && icc_profile.length > 0) { String outpath = ""; if(pathToICCProfile.endsWith("\\") || pathToICCProfile.endsWith("/")) outpath = pathToICCProfile + "icc_profile"; else outpath = pathToICCProfile.replaceFirst("[.][^.]+$", ""); OutputStream os = new FileOutputStream(outpath + ".icc"); os.write(icc_profile); os.close(); } } // Extract depth map from google phones and cardboard camera audio & stereo pair public static void extractDepthMap(InputStream is, String pathToDepthMap) throws IOException { Map<MetadataType, Metadata> meta = readMetadata(is); XMP xmp = (XMP)meta.get(MetadataType.XMP); if(xmp != null) { Document xmpDocument = xmp.getMergedDocument(); String depthMapMime = XMLUtils.getAttribute(xmpDocument, "rdf:Description", "GDepth:Mime"); String depthData = "GDepth:Data"; String audioMime = XMLUtils.getAttribute(xmpDocument, "rdf:Description", "GAudio:Mime"); if(StringUtils.isNullOrEmpty(depthMapMime)) { depthMapMime = XMLUtils.getAttribute(xmpDocument, "rdf:Description", "GImage:Mime"); depthData = "GImage:Data"; } if(!StringUtils.isNullOrEmpty(depthMapMime)) { String data = XMLUtils.getAttribute(xmpDocument, "rdf:Description", depthData); if(!StringUtils.isNullOrEmpty(data)) { String outpath = ""; if(pathToDepthMap.endsWith("\\") || pathToDepthMap.endsWith("/")) outpath = pathToDepthMap + "google_depthmap"; else outpath = pathToDepthMap.replaceFirst("[.][^.]+$", "") + "_depthmap"; if(depthMapMime.equalsIgnoreCase("image/png")) { outpath += ".png"; } else if(depthMapMime.equalsIgnoreCase("image/jpeg")) { outpath += ".jpg"; } try { byte[] image = Base64.decodeToByteArray(data); FileOutputStream fout = new FileOutputStream(new File(outpath)); fout.write(image); fout.close(); } catch (Exception e) { e.printStackTrace(); } } } if(!StringUtils.isNullOrEmpty(audioMime)) { // Cardboard Camera Audio String data = XMLUtils.getAttribute(xmpDocument, "rdf:Description", "GAudio:Data"); if(!StringUtils.isNullOrEmpty(data)) { String outpath = ""; if(pathToDepthMap.endsWith("\\") || pathToDepthMap.endsWith("/")) outpath = pathToDepthMap + "google_cardboard_audio"; else outpath = pathToDepthMap.replaceFirst("[.][^.]+$", "") + "_cardboard_audio"; if(audioMime.equalsIgnoreCase("audio/mp4a-latm")) { outpath += ".mp4"; } try { byte[] image = Base64.decodeToByteArray(data); FileOutputStream fout = new FileOutputStream(new File(outpath)); fout.write(image); fout.close(); } catch (Exception e) { e.printStackTrace(); } } } } } /** * Extracts thumbnail images from JFIF/APP0, Exif APP1 and/or Adobe APP13 segment if any. * * @param is InputStream for the JPEG image. * @param pathToThumbnail a path or a path and name prefix combination for the extracted thumbnails. * @throws IOException */ public static void extractThumbnails(InputStream is, String pathToThumbnail) throws IOException { // Flag when we are done boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.EOI) { finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. marker = IOUtils.readShortMM(is); break; case PADDING: int nextByte = 0; while((nextByte = IOUtils.read(is)) == 0xff) {;} marker = (short)((0xff<<8)|nextByte); break; case SOS: finished = true; break; case APP0: length = IOUtils.readUnsignedShortMM(is); byte[] jfif_buf = new byte[length - 2]; IOUtils.readFully(is, jfif_buf); // EXIF segment if(new String(jfif_buf, 0, JFIF_ID.length()).equals(JFIF_ID) || new String(jfif_buf, 0, JFXX_ID.length()).equals(JFXX_ID)) { int thumbnailWidth = jfif_buf[12]&0xff; int thumbnailHeight = jfif_buf[13]&0xff; String outpath = ""; if(pathToThumbnail.endsWith("\\") || pathToThumbnail.endsWith("/")) outpath = pathToThumbnail + "jfif_thumbnail"; else outpath = pathToThumbnail.replaceFirst("[.][^.]+$", "") + "_jfif_t"; if(thumbnailWidth != 0 && thumbnailHeight != 0) { // There is a thumbnail // Extract the thumbnail //Create a BufferedImage int size = 3*thumbnailWidth*thumbnailHeight; int[] colors = MetadataUtils.toARGB(ArrayUtils.subArray(jfif_buf, 14, size)); Bitmap bmp = Bitmap.createBitmap(colors, thumbnailWidth, thumbnailHeight, Bitmap.Config.ARGB_8888); FileOutputStream fout = new FileOutputStream(outpath + ".jpg"); try { bmp.compress(CompressFormat.JPEG, 100, fout); } catch (Exception e) { e.printStackTrace(); } fout.close(); } } marker = IOUtils.readShortMM(is); break; case APP1: // EXIF identifier with trailing bytes [0x00,0x00]. byte[] exif_buf = new byte[EXIF_ID.length()]; length = IOUtils.readUnsignedShortMM(is); IOUtils.readFully(is, exif_buf); // EXIF segment. if (Arrays.equals(exif_buf, EXIF_ID.getBytes())) { exif_buf = new byte[length - 8]; IOUtils.readFully(is, exif_buf); Exif exif = new JpegExif(exif_buf); if(exif.containsThumbnail()) { String outpath = ""; if(pathToThumbnail.endsWith("\\") || pathToThumbnail.endsWith("/")) outpath = pathToThumbnail + "exif_thumbnail"; else outpath = pathToThumbnail.replaceFirst("[.][^.]+$", "") + "_exif_t"; Thumbnail thumbnail = exif.getThumbnail(); OutputStream fout = null; if(thumbnail.getDataType() == ExifThumbnail.DATA_TYPE_KJpegRGB) {// JPEG format, save as JPEG fout = new FileOutputStream(outpath + ".jpg"); } else { // Uncompressed, save as TIFF fout = new FileOutputStream(outpath + ".tif"); } fout.write(thumbnail.getCompressedImage()); fout.close(); } } else { IOUtils.skipFully(is, length - 8); } marker = IOUtils.readShortMM(is); break; case APP13: length = IOUtils.readUnsignedShortMM(is); byte[] data = new byte[length - 2]; IOUtils.readFully(is, data, 0, length - 2); int i = 0; while(data[i] != 0) i++; if(new String(data, 0, i++).equals("Photoshop 3.0")) { IRB irb = new IRB(ArrayUtils.subArray(data, i, data.length - i)); if(irb.containsThumbnail()) { Thumbnail thumbnail = irb.getThumbnail(); // Create output path String outpath = ""; if(pathToThumbnail.endsWith("\\") || pathToThumbnail.endsWith("/")) outpath = pathToThumbnail + "photoshop_thumbnail.jpg"; else outpath = pathToThumbnail.replaceFirst("[.][^.]+$", "") + "_photoshop_t.jpg"; FileOutputStream fout = new FileOutputStream(outpath); if(thumbnail.getDataType() == Thumbnail.DATA_TYPE_KJpegRGB) { fout.write(thumbnail.getCompressedImage()); } else { Bitmap bmp = thumbnail.getRawImage(); try { bmp.compress(Bitmap.CompressFormat.JPEG, 100, fout); } catch (Exception e) { throw new IOException("Writing thumbnail failed!"); } } fout.close(); } } marker = IOUtils.readShortMM(is); break; default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); marker = IOUtils.readShortMM(is); } } } } public static ICCProfile getICCProfile(InputStream is) throws IOException { ICCProfile profile = null; byte[] buf = extractICCProfile(is); if(buf.length > 0) profile = new ICCProfile(buf); return profile; } public static void insertComments(InputStream is, OutputStream os, List<String> comments) throws IOException { boolean finished = false; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.SOS) { // Write comment for(String comment : comments) writeComment(comment, os); // Copy the rest of the data IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // No more marker to read, we are done. finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. IOUtils.writeShortMM(os, marker); marker = IOUtils.readShortMM(is); break; case PADDING: IOUtils.writeShortMM(os, marker); int nextByte = 0; while ((nextByte = IOUtils.read(is)) == 0xff) { IOUtils.write(os, nextByte); } marker = (short) ((0xff << 8) | nextByte); break; default: marker = copySegment(marker, is, os); } } } } /** * @param is input image stream * @param os output image stream * @param exif Exif instance * @param update True to keep the original data, otherwise false * @throws Exception */ public static void insertExif(InputStream is, OutputStream os, Exif exif, boolean update) throws IOException { // We need thumbnail image but don't have one, create one from the current image input stream if(exif.isThumbnailRequired() && !exif.containsThumbnail()) { is = new FileCacheRandomAccessInputStream(is); // Insert thumbnail into EXIF wrapper exif.setThumbnailImage(MetadataUtils.createThumbnail(is)); } Exif oldExif = null; int app0Index = -1; // Copy the original image and insert EXIF data boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) { throw new IOException("Invalid JPEG image, expected SOI marker not found!"); } IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); // Create a list to hold the temporary Segments List<Segment> segments = new ArrayList<Segment>(); while (!finished) { // Read through and add the segments to a list until SOS if (Marker.fromShort(marker) == Marker.SOS) { // Write the items in segments list excluding the old EXIF for(int i = 0; i <= app0Index; i++) { segments.get(i).write(os); } // Now we insert the EXIF data IFD newExifSubIFD = exif.getExifIFD(); IFD newGpsSubIFD = exif.getGPSIFD(); IFD newImageIFD = exif.getImageIFD(); ExifThumbnail newThumbnail = exif.getThumbnail(); // Define new IFDs IFD exifSubIFD = null; IFD gpsSubIFD = null; IFD imageIFD = null; // Got to do something to keep the old data if(update && oldExif != null) { IFD oldImageIFD = oldExif.getImageIFD(); IFD oldExifSubIFD = oldExif.getExifIFD(); IFD oldGpsSubIFD = oldExif.getGPSIFD(); ExifThumbnail thumbnail = oldExif.getThumbnail(); if(oldImageIFD != null) { imageIFD = new IFD(); imageIFD.addFields(oldImageIFD.getFields()); } if(thumbnail != null) { if(newThumbnail == null) newThumbnail = thumbnail; } if(oldExifSubIFD != null) { exifSubIFD = new IFD(); exifSubIFD.addFields(oldExifSubIFD.getFields()); } if(oldGpsSubIFD != null) { gpsSubIFD = new IFD(); gpsSubIFD.addFields(oldGpsSubIFD.getFields()); } } if(newImageIFD != null) { if(imageIFD == null) imageIFD = new IFD(); imageIFD.addFields(newImageIFD.getFields()); } if(exifSubIFD != null) { if(newExifSubIFD != null) exifSubIFD.addFields(newExifSubIFD.getFields()); } else exifSubIFD = newExifSubIFD; if(gpsSubIFD != null) { if(newGpsSubIFD != null) gpsSubIFD.addFields(newGpsSubIFD.getFields()); } else gpsSubIFD = newGpsSubIFD; // If we have ImageIFD, set Image IFD attached with EXIF and GPS if(imageIFD != null) { if(exifSubIFD != null) imageIFD.addChild(TiffTag.EXIF_SUB_IFD, exifSubIFD); if(gpsSubIFD != null) imageIFD.addChild(TiffTag.GPS_SUB_IFD, gpsSubIFD); exif.setImageIFD(imageIFD); } else { // Otherwise, set EXIF and GPS IFD separately exif.setExifIFD(exifSubIFD); exif.setGPSIFD(gpsSubIFD); } exif.setThumbnail(newThumbnail); // Now insert the new EXIF to the JPEG exif.write(os); // Copy the remaining segments for(int i = app0Index + 1; i < segments.size(); i++) { segments.get(i).write(os); } // Copy the leftover stuff IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // We are done finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. segments.add(new Segment(emarker, 0, null)); marker = IOUtils.readShortMM(is); break; case APP1: // Read and remove the old EXIF data length = IOUtils.readUnsignedShortMM(is); byte[] exifBytes = new byte[length - 2]; IOUtils.readFully(is, exifBytes); // Add data to segment list segments.add(new Segment(emarker, length, exifBytes)); // Read the EXIF data. if(exifBytes.length >= EXIF_ID.length() && new String(exifBytes, 0, EXIF_ID.length()).equals(EXIF_ID)) { // We assume EXIF data exist only in one APP1 oldExif = new JpegExif(ArrayUtils.subArray(exifBytes, EXIF_ID.length(), length - EXIF_ID.length() - 2)); segments.remove(segments.size() - 1); } marker = IOUtils.readShortMM(is); break; case APP0: app0Index = segments.size(); default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker == Marker.UNKNOWN) segments.add(new UnknownSegment(marker, length, buf)); else segments.add(new Segment(emarker, length, buf)); marker = IOUtils.readShortMM(is); } } } // Close the input stream in case it's an instance of RandomAccessInputStream if(is instanceof RandomAccessInputStream) ((FileCacheRandomAccessInputStream)is).shallowClose(); } /** * Insert ICC_Profile as one or more APP2 segments * * @param is input stream for the original image * @param os output stream to write the ICC_Profile * @param data ICC_Profile data array to be inserted * @throws IOException */ public static void insertICCProfile(InputStream is, OutputStream os, byte[] data) throws IOException { // Copy the original image and insert ICC_Profile data byte[] icc_profile_id = {0x49, 0x43, 0x43, 0x5f, 0x50, 0x52, 0x4f, 0x46, 0x49, 0x4c, 0x45, 0x00}; boolean finished = false; int length = 0; short marker; Marker emarker; int app0Index = -1; int app1Index = -1; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); // Create a list to hold the temporary Segments List<Segment> segments = new ArrayList<Segment>(); while (!finished) { if (Marker.fromShort(marker) == Marker.SOS) { int index = Math.max(app0Index, app1Index); // Write the items in segments list excluding the APP13 for(int i = 0; i <= index; i++) segments.get(i).write(os); writeICCProfile(os, data); // Copy the remaining segments for(int i = (index < 0 ? 0 : index + 1); i < segments.size(); i++) { segments.get(i).write(os); } // Copy the rest of the data IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // No more marker to read, we are done. finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. segments.add(new Segment(emarker, 0, null)); marker = IOUtils.readShortMM(is); break; case APP2: // Remove old ICC_Profile byte[] icc_profile_buf = new byte[12]; length = IOUtils.readUnsignedShortMM(is); if(length < 14) { // This is not an ICC_Profile segment, copy it icc_profile_buf = new byte[length - 2]; IOUtils.readFully(is, icc_profile_buf); segments.add(new Segment(emarker, length, icc_profile_buf)); } else { IOUtils.readFully(is, icc_profile_buf); // ICC_PROFILE segment. if (Arrays.equals(icc_profile_buf, icc_profile_id)) { IOUtils.skipFully(is, length - 14); } else {// Not an ICC_Profile segment, copy it IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short)length); IOUtils.write(os, icc_profile_buf); byte[] temp = new byte[length - ICC_PROFILE_ID.length() - 2]; IOUtils.readFully(is, temp); segments.add(new Segment(emarker, length, ArrayUtils.concat(icc_profile_buf, temp))); } } marker = IOUtils.readShortMM(is); break; case APP0: app0Index = segments.size(); case APP1: app1Index = segments.size(); default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker == Marker.UNKNOWN) segments.add(new UnknownSegment(marker, length, buf)); else segments.add(new Segment(emarker, length, buf)); marker = IOUtils.readShortMM(is); } } } } public static void insertICCProfile(InputStream is, OutputStream os, ICCProfile icc_profile) throws Exception { insertICCProfile(is, os, icc_profile.getData()); } /** * Inserts a list of IPTCDataSet into a JPEG APP13 Photoshop IRB segment * * @param is InputStream for the original image * @param os OutputStream for the image with IPTC inserted * @param iptcs a collection of IPTCDataSet to be inserted * @param update boolean if true, keep the original IPTC data; otherwise, replace it completely with the new IPTC data * @throws IOException */ public static void insertIPTC(InputStream is, OutputStream os, Collection<IPTCDataSet> iptcs, boolean update) throws IOException { // Copy the original image and insert Photoshop IRB data boolean finished = false; int length = 0; short marker; Marker emarker; int app0Index = -1; int app1Index = -1; Map<Short, _8BIM> bimMap = null; // Used to read multiple segment Adobe APP13 ByteArrayOutputStream eightBIMStream = null; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) { is.close(); os.close(); throw new IOException("Invalid JPEG image, expected SOI marker not found!"); } IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); // Create a list to hold the temporary Segments List<Segment> segments = new ArrayList<Segment>(); while (!finished) { if (Marker.fromShort(marker) == Marker.SOS) { if(eightBIMStream != null) { IRB irb = new IRB(eightBIMStream.toByteArray()); // Shallow copy the map. bimMap = new HashMap<Short, _8BIM>(irb.get8BIM()); _8BIM iptcBIM = bimMap.remove(ImageResourceID.IPTC_NAA.getValue()); if(iptcBIM != null && update) { // Keep the original values IPTC iptc = new IPTC(iptcBIM.getData()); // Shallow copy the map Map<IPTCTag, List<IPTCDataSet>> dataSetMap = new HashMap<IPTCTag, List<IPTCDataSet>>(iptc.getDataSets()); for(IPTCDataSet set : iptcs) if(!set.allowMultiple()) dataSetMap.remove(set.getName()); for(List<IPTCDataSet> iptcList : dataSetMap.values()) iptcs.addAll(iptcList); } } int index = Math.max(app0Index, app1Index); // Write the items in segments list excluding the APP13 for(int i = 0; i <= index; i++) segments.get(i).write(os); ByteArrayOutputStream bout = new ByteArrayOutputStream(); // Insert IPTC data as one of IRB 8BIM block for(IPTCDataSet iptc : iptcs) iptc.write(bout); // Create 8BIM for IPTC _8BIM newBIM = new _8BIM(ImageResourceID.IPTC_NAA.getValue(), "iptc", bout.toByteArray()); if(bimMap != null) { bimMap.put(newBIM.getID(), newBIM); // Add the IPTC_NAA 8BIM to the map writeIRB(os, bimMap.values()); // Write the whole thing as one APP13 } else { writeIRB(os, newBIM); // Write the one and only one 8BIM as one APP13 } // Copy the remaining segments for(int i = (index < 0 ? 0 : index + 1); i < segments.size(); i++) { segments.get(i).write(os); } // Copy the rest of the data IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // No more marker to read, we are done. finished = true; } else {// Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. segments.add(new Segment(emarker, 0, null)); marker = IOUtils.readShortMM(is); break; case APP13: if(eightBIMStream == null) eightBIMStream = new ByteArrayOutputStream(); readAPP13(is, eightBIMStream); marker = IOUtils.readShortMM(is); break; case APP0: app0Index = segments.size(); case APP1: app1Index = segments.size(); default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker == Marker.UNKNOWN) segments.add(new UnknownSegment(marker, length, buf)); else segments.add(new Segment(emarker, length, buf)); marker = IOUtils.readShortMM(is); } } } } /** * Inserts a collection of _8BIM into a JPEG APP13 Photoshop IRB segment * * @param is InputStream for the original image * @param os OutputStream for the image with _8BIMs inserted * @param bims a collection of _8BIM to be inserted * @param update boolean if true, keep the other _8BIMs; otherwise, replace the whole IRB with the inserted _8BIMs * @throws IOException */ public static void insertIRB(InputStream is, OutputStream os, Collection<_8BIM> bims, boolean update) throws IOException { // Copy the original image and insert Photoshop IRB data boolean finished = false; int length = 0; short marker; Marker emarker; int app0Index = -1; int app1Index = -1; // Used to read multiple segment Adobe APP13 ByteArrayOutputStream eightBIMStream = null; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) { is.close(); os.close(); throw new IOException("Invalid JPEG image, expected SOI marker not found!"); } IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); // Create a list to hold the temporary Segments List<Segment> segments = new ArrayList<Segment>(); while (!finished) { if (Marker.fromShort(marker) == Marker.SOS) { if(eightBIMStream != null) { IRB irb = new IRB(eightBIMStream.toByteArray()); // Shallow copy the map. Map<Short, _8BIM> bimMap = new HashMap<Short, _8BIM>(irb.get8BIM()); for(_8BIM bim : bims) // Replace the original data bimMap.put(bim.getID(), bim); // In case we have two ThumbnailResource IRB, remove the Photoshop4.0 one if(bimMap.containsKey(ImageResourceID.THUMBNAIL_RESOURCE_PS4.getValue()) && bimMap.containsKey(ImageResourceID.THUMBNAIL_RESOURCE_PS5.getValue())) bimMap.remove(ImageResourceID.THUMBNAIL_RESOURCE_PS4.getValue()); bims = bimMap.values(); } int index = Math.max(app0Index, app1Index); // Write the items in segments list excluding the APP13 for(int i = 0; i <= index; i++) segments.get(i).write(os); writeIRB(os, bims); // Copy the remaining segments for(int i = (index < 0 ? 0 : index + 1); i < segments.size(); i++) { segments.get(i).write(os); } // Copy the rest of the data IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // No more marker to read, we are done. finished = true; } else {// Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. segments.add(new Segment(emarker, 0, null)); marker = IOUtils.readShortMM(is); break; case APP13: // We will keep the other IRBs from the original APP13 if(update) { if(eightBIMStream == null) eightBIMStream = new ByteArrayOutputStream(); readAPP13(is, eightBIMStream); } else { length = IOUtils.readUnsignedShortMM(is); IOUtils.skipFully(is, length - 2); } marker = IOUtils.readShortMM(is); break; case APP0: app0Index = segments.size(); case APP1: app1Index = segments.size(); default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker == Marker.UNKNOWN) segments.add(new UnknownSegment(marker, length, buf)); else segments.add(new Segment(emarker, length, buf)); marker = IOUtils.readShortMM(is); } } } } public static void insertIRBThumbnail(InputStream is, OutputStream os, Bitmap thumbnail) throws IOException { // Sanity check if(thumbnail == null) throw new IllegalArgumentException("Input thumbnail is null"); _8BIM bim = new ThumbnailResource(thumbnail); insertIRB(is, os, Arrays.asList(bim), true); // Set true to keep other IRB blocks } /** * Insert a XMP instance into the image. * The XMP instance must be able to fit into one APP1. * * @param is InputStream for the image. * @param os OutputStream for the image. * @param xmp XMP instance * @throws IOException */ public static void insertXMP(InputStream is, OutputStream os, XMP xmp) throws IOException { boolean finished = false; int length = 0; short marker; Marker emarker; int app0Index = -1; int exifIndex = -1; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) { throw new IOException("Invalid JPEG image, expected SOI marker not found!"); } IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); // Create a list to hold the temporary Segments List<Segment> segments = new ArrayList<Segment>(); while (!finished) { if (Marker.fromShort(marker) == Marker.SOS) { int index = Math.max(app0Index, exifIndex); // Write the items in segments list excluding the old XMP for(int i = 0; i <= index; i++) segments.get(i).write(os); // Now we insert the XMP data xmp.write(os); // Copy the remaining segments for(int i = (index < 0 ? 0 : index + 1); i < segments.size(); i++) { segments.get(i).write(os); } // Copy the leftover stuff IOUtils.writeShortMM(os, marker); copyToEnd(is, os); // Copy the rest of the data finished = true; // No more marker to read, we are done. } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. segments.add(new Segment(emarker, 0, null)); marker = IOUtils.readShortMM(is); break; case APP1: // Read and remove the old XMP data length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // Remove XMP and ExtendedXMP segments. if(temp.length >= XMP_EXT_ID.length() && new String(temp, 0, XMP_EXT_ID.length()).equals(XMP_EXT_ID)) { ; } else if (temp.length >= XMP_ID.length() && new String(temp, 0, XMP_ID.length()).equals(XMP_ID)) { ; } else { segments.add(new Segment(emarker, length, temp)); // If it's EXIF, we keep the index if(temp.length >= EXIF_ID.length() && new String(temp, 0, EXIF_ID.length()).equals(EXIF_ID)) { exifIndex = segments.size() - 1; } } marker = IOUtils.readShortMM(is); break; case APP0: app0Index = segments.size(); default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker == Marker.UNKNOWN) segments.add(new UnknownSegment(marker, length, buf)); else segments.add(new Segment(emarker, length, buf)); marker = IOUtils.readShortMM(is); } } } } /** * Insert XMP into single APP1 or multiple segments. Support ExtendedXMP. * The standard part of the XMP must be a valid XMP with packet wrapper and, * should already include the GUID for the ExtendedXMP in case of ExtendedXMP. * <p> * When converted to bytes, the XMP part should be able to fit into one APP1. * * @param is InputStream for the image. * @param os OutputStream for the image. * @param xmp XML string for the XMP - Assuming in UTF-8 format. * @param extendedXmp XML string for the extended XMP - Assuming in UTF-8 format * * @throws IOException */ public static void insertXMP(InputStream is, OutputStream os, String xmp, String extendedXmp) throws IOException { insertXMP(is, os, new JpegXMP(xmp, extendedXmp)); } private static String hTablesToString(List<HTable> hTables) { final String[] HT_class_table = {"DC Component", "AC Component"}; StringBuilder hufTable = new StringBuilder(); hufTable.append("Huffman table information =>:\n"); for(HTable table : hTables ) { hufTable.append("Class: " + table.getClazz() + " (" + HT_class_table[table.getClazz()] + ")\n"); hufTable.append("Huffman table #: " + table.getID() + "\n"); byte[] bits = table.getBits(); byte[] values = table.getValues(); int count = 0; for (int i = 0; i < bits.length; i++) { count += (bits[i]&0xff); } hufTable.append("Number of codes: " + count + "\n"); if (count > 256) throw new RuntimeException("Invalid huffman code count: " + count); int j = 0; for (int i = 0; i < 16; i++) { hufTable.append("Codes of length " + (i+1) + " (" + (bits[i]&0xff) + " total): [ "); for (int k = 0; k < (bits[i]&0xff); k++) { hufTable.append((values[j++]&0xff) + " "); } hufTable.append("]\n"); } hufTable.append("<<End of Huffman table information>>\n"); } return hufTable.toString(); } private static String qTablesToString(List<QTable> qTables) { StringBuilder qtTables = new StringBuilder(); qtTables.append("Quantization table information =>:\n"); int count = 0; for(QTable table : qTables) { int QT_precision = table.getPrecision(); int[] qTable = table.getData(); qtTables.append("precision of QT is " + QT_precision + "\n"); qtTables.append("Quantization table #" + table.getID() + ":\n"); if(QT_precision == 0) { for (int j = 0; j < 64; j++) { if (j != 0 && j%8 == 0) { qtTables.append("\n"); } qtTables.append(qTable[j] + " "); } } else { // 16 bit big-endian for (int j = 0; j < 64; j++) { if (j != 0 && j%8 == 0) { qtTables.append("\n"); } qtTables.append(qTable[j] + " "); } } count++; qtTables.append("\n"); qtTables.append("***************************\n"); } qtTables.append("Total number of Quantation tables: " + count + "\n"); qtTables.append("End of quantization table information\n"); return qtTables.toString(); } private static String sofToString(SOFReader reader) { StringBuilder sof = new StringBuilder(); sof.append("SOF information =>\n"); sof.append("Precision: " + reader.getPrecision() + "\n"); sof.append("Image height: " + reader.getFrameHeight() +"\n"); sof.append("Image width: " + reader.getFrameWidth() + "\n"); sof.append("# of Components: " + reader.getNumOfComponents() + "\n"); sof.append("(1 = grey scaled, 3 = color YCbCr or YIQ, 4 = color CMYK)\n"); for(Component component : reader.getComponents()) { sof.append("\n"); sof.append("Component ID: " + component.getId() + "\n"); sof.append("Herizontal sampling factor: " + component.getHSampleFactor() + "\n"); sof.append("Vertical sampling factor: " + component.getVSampleFactor() + "\n"); sof.append("Quantization table #: " + component.getQTableNumber() + "\n"); sof.append("DC table number: " + component.getDCTableNumber() + "\n"); sof.append("AC table number: " + component.getACTableNumber() + "\n"); } sof.append("<= End of SOF information"); return sof.toString(); } private static void readAPP13(InputStream is, OutputStream os) throws IOException { int length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); if (new String(temp, 0, PHOTOSHOP_IRB_ID.length()).equals(PHOTOSHOP_IRB_ID)) { os.write(ArrayUtils.subArray(temp, PHOTOSHOP_IRB_ID.length(), temp.length - PHOTOSHOP_IRB_ID.length())); } } private static void readAPP2(InputStream is, OutputStream os) throws IOException { byte[] icc_profile_buf = new byte[ICC_PROFILE_ID.length()]; int length = IOUtils.readUnsignedShortMM(is); IOUtils.readFully(is, icc_profile_buf); // ICC_PROFILE segment. if (Arrays.equals(icc_profile_buf, ICC_PROFILE_ID.getBytes())) { icc_profile_buf = new byte[length - ICC_PROFILE_ID.length() - 2]; IOUtils.readFully(is, icc_profile_buf); os.write(icc_profile_buf, 2, length - ICC_PROFILE_ID.length() - 4); } else { IOUtils.skipFully(is, length - ICC_PROFILE_ID.length() - 2); } } private static void readDHT(InputStream is, List<HTable> m_acTables, List<HTable> m_dcTables) throws IOException { int len = IOUtils.readUnsignedShortMM(is); byte buf[] = new byte[len - 2]; IOUtils.readFully(is, buf); DHTReader reader = new DHTReader(new Segment(Marker.DHT, len, buf)); List<HTable> dcTables = reader.getDCTables(); List<HTable> acTables = reader.getACTables(); m_acTables.addAll(acTables); m_dcTables.addAll(dcTables); } // Process define Quantization table private static void readDQT(InputStream is, List<QTable> m_qTables) throws IOException { int len = IOUtils.readUnsignedShortMM(is); byte buf[] = new byte[len - 2]; IOUtils.readFully(is, buf); DQTReader reader = new DQTReader(new Segment(Marker.DQT, len, buf)); List<QTable> qTables = reader.getTables(); m_qTables.addAll(qTables); } public static Map<MetadataType, Metadata> readMetadata(InputStream is) throws IOException { Map<MetadataType, Metadata> metadataMap = new HashMap<MetadataType, Metadata>(); Map<String, Thumbnail> thumbnails = new HashMap<String, Thumbnail>(); // Need to wrap the input stream with a BufferedInputStream to // speed up reading SOS is = new BufferedInputStream(is); // Definitions List<QTable> m_qTables = new ArrayList<QTable>(4); List<HTable> m_acTables = new ArrayList<HTable>(4); List<HTable> m_dcTables = new ArrayList<HTable>(4); // Each SOFReader is associated with a single SOF segment // Usually there is only one SOF segment, but for hierarchical // JPEG, there could be more than one SOF List<SOFReader> readers = new ArrayList<SOFReader>(); // Used to read multiple segment ICCProfile ByteArrayOutputStream iccProfileStream = null; // Used to read multiple segment Adobe APP13 ByteArrayOutputStream eightBIMStream = null; // Used to read multiple segment XMP byte[] extendedXMP = null; String xmpGUID = ""; // 32 byte ASCII hex string Comments comments = null; List<Segment> appnSegments = new ArrayList<Segment>(); boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IllegalArgumentException("Invalid JPEG image, expected SOI marker not found!"); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.EOI) { finished = true; } else {// Read markers emarker = Marker.fromShort(marker); switch (emarker) { case APP0: case APP1: case APP2: case APP3: case APP4: case APP5: case APP6: case APP7: case APP8: case APP9: case APP10: case APP11: case APP12: case APP13: case APP14: case APP15: byte[] appBytes = readSegmentData(is); appnSegments.add(new Segment(emarker, appBytes.length + 2, appBytes)); marker = IOUtils.readShortMM(is); break; case COM: if(comments == null) comments = new Comments(); comments.addComment(readSegmentData(is)); marker = IOUtils.readShortMM(is); break; case DHT: readDHT(is, m_acTables, m_dcTables); marker = IOUtils.readShortMM(is); break; case DQT: readDQT(is, m_qTables); marker = IOUtils.readShortMM(is); break; case SOF0: case SOF1: case SOF2: case SOF3: case SOF5: case SOF6: case SOF7: case SOF9: case SOF10: case SOF11: case SOF13: case SOF14: case SOF15: readers.add(readSOF(is, emarker)); marker = IOUtils.readShortMM(is); break; case SOS: SOFReader reader = readers.get(readers.size() - 1); marker = readSOS(is, reader); LOGGER.debug("\n{}", sofToString(reader)); break; case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone mark besides SOI, EOI, and RSTn. marker = IOUtils.readShortMM(is); break; case PADDING: int nextByte = 0; while((nextByte = IOUtils.read(is)) == 0xff) {;} marker = (short)((0xff<<8)|nextByte); break; default: length = IOUtils.readUnsignedShortMM(is); IOUtils.skipFully(is, length - 2); marker = IOUtils.readShortMM(is); } } } is.close(); // Debugging LOGGER.debug("\n{}", qTablesToString(m_qTables)); LOGGER.debug("\n{}", hTablesToString(m_acTables)); LOGGER.debug("\n{}", hTablesToString(m_dcTables)); for(Segment segment : appnSegments) { byte[] data = segment.getData(); length = segment.getLength(); if(segment.getMarker() == Marker.APP0) { if (new String(data, 0, JFIF_ID.length()).equals(JFIF_ID)) { metadataMap.put(MetadataType.JPG_JFIF, new JFIF(ArrayUtils.subArray(data, JFIF_ID.length(), length - JFIF_ID.length() - 2))); } } else if(segment.getMarker() == Marker.APP1) { // Check for EXIF if(new String(data, 0, EXIF_ID.length()).equals(EXIF_ID)) { // We found EXIF JpegExif exif = new JpegExif(ArrayUtils.subArray(data, EXIF_ID.length(), length - EXIF_ID.length() - 2)); metadataMap.put(MetadataType.EXIF, exif); } else if(new String(data, 0, XMP_ID.length()).equals(XMP_ID) || new String(data, 0, NON_STANDARD_XMP_ID.length()).equals(NON_STANDARD_XMP_ID)) { // We found XMP, add it to metadata list (We may later revise it if we have ExtendedXMP) XMP xmp = new JpegXMP(ArrayUtils.subArray(data, XMP_ID.length(), length - XMP_ID.length() - 2)); metadataMap.put(MetadataType.XMP, xmp); // Retrieve and remove XMP GUID if available xmpGUID = XMLUtils.getAttribute(xmp.getXmpDocument(), "rdf:Description", "xmpNote:HasExtendedXMP"); } else if(new String(data, 0, XMP_EXT_ID.length()).equals(XMP_EXT_ID)) { // We found ExtendedXMP, add the data to ExtendedXMP memory buffer int i = XMP_EXT_ID.length(); // 128-bit MD5 digest of the full ExtendedXMP serialization byte[] guid = ArrayUtils.subArray(data, i, 32); if(Arrays.equals(guid, xmpGUID.getBytes())) { // We have matched the GUID, copy it i += 32; long extendedXMPLength = IOUtils.readUnsignedIntMM(data, i); i += 4; if(extendedXMP == null) extendedXMP = new byte[(int)extendedXMPLength]; // Offset for the current segment long offset = IOUtils.readUnsignedIntMM(data, i); i += 4; byte[] xmpBytes = ArrayUtils.subArray(data, i, length - XMP_EXT_ID.length() - 42); System.arraycopy(xmpBytes, 0, extendedXMP, (int)offset, xmpBytes.length); } } } else if(segment.getMarker() == Marker.APP2) { // We're only interested in ICC_Profile if (new String(data, 0, ICC_PROFILE_ID.length()).equals(ICC_PROFILE_ID)) { if(iccProfileStream == null) iccProfileStream = new ByteArrayOutputStream(); iccProfileStream.write(ArrayUtils.subArray(data, ICC_PROFILE_ID.length() + 2, length - ICC_PROFILE_ID.length() - 4)); } } else if(segment.getMarker() == Marker.APP12) { if (new String(data, 0, DUCKY_ID.length()).equals(DUCKY_ID)) { metadataMap.put(MetadataType.JPG_DUCKY, new Ducky(ArrayUtils.subArray(data, DUCKY_ID.length(), length - DUCKY_ID.length() - 2))); } } else if(segment.getMarker() == Marker.APP13) { if (new String(data, 0, PHOTOSHOP_IRB_ID.length()).equals(PHOTOSHOP_IRB_ID)) { if(eightBIMStream == null) eightBIMStream = new ByteArrayOutputStream(); eightBIMStream.write(ArrayUtils.subArray(data, PHOTOSHOP_IRB_ID.length(), length - PHOTOSHOP_IRB_ID.length() - 2)); } } else if(segment.getMarker() == Marker.APP14) { if (new String(data, 0, ADOBE_ID.length()).equals(ADOBE_ID)) { metadataMap.put(MetadataType.JPG_ADOBE, new Adobe(ArrayUtils.subArray(data, ADOBE_ID.length(), length - ADOBE_ID.length() - 2))); } } } // Now it's time to join multiple segments ICC_PROFILE and/or XMP if(iccProfileStream != null) { // We have ICCProfile data ICCProfile icc_profile = new ICCProfile(iccProfileStream.toByteArray()); metadataMap.put(MetadataType.ICC_PROFILE, icc_profile); } if(eightBIMStream != null) { IRB irb = new IRB(eightBIMStream.toByteArray()); metadataMap.put(MetadataType.PHOTOSHOP_IRB, irb); _8BIM iptc = irb.get8BIM(ImageResourceID.IPTC_NAA.getValue()); // Extract IPTC as stand-alone meta if(iptc != null) { metadataMap.put(MetadataType.IPTC, new IPTC(iptc.getData())); } } if(extendedXMP != null) { XMP xmp = ((XMP)metadataMap.get(MetadataType.XMP)); if(xmp != null) xmp.setExtendedXMPData(extendedXMP); } if(comments != null) metadataMap.put(MetadataType.COMMENT, comments); // Extract thumbnails to ImageMetadata Metadata meta = metadataMap.get(MetadataType.EXIF); if(meta != null) { Exif exif = (Exif)meta; if(!exif.isDataRead()) exif.read(); if(exif.containsThumbnail()) { thumbnails.put("EXIF", exif.getThumbnail()); } } meta = metadataMap.get(MetadataType.PHOTOSHOP_IRB); if(meta != null) { IRB irb = (IRB)meta; if(!irb.isDataRead()) irb.read(); if(irb.containsThumbnail()) { thumbnails.put("PHOTOSHOP_IRB", irb.getThumbnail()); } } metadataMap.put(MetadataType.IMAGE, new ImageMetadata(thumbnails)); return metadataMap; } private static byte[] readSegmentData(InputStream is) throws IOException { int length = IOUtils.readUnsignedShortMM(is); byte[] data = new byte[length - 2]; IOUtils.readFully(is, data); return data; } private static SOFReader readSOF(InputStream is, Marker marker) throws IOException { int len = IOUtils.readUnsignedShortMM(is); byte buf[] = new byte[len - 2]; IOUtils.readFully(is, buf); Segment segment = new Segment(marker, len, buf); SOFReader reader = new SOFReader(segment); return reader; } // This method is very slow if not wrapped in some kind of cache stream but it works for multiple // SOSs in case of progressive JPEG private static short readSOS(InputStream is, SOFReader sofReader) throws IOException { int len = IOUtils.readUnsignedShortMM(is); byte buf[] = new byte[len - 2]; IOUtils.readFully(is, buf); Segment segment = new Segment(Marker.SOS, len, buf); new SOSReader(segment, sofReader); // Actual image data follow. int nextByte = 0; short marker = 0; while((nextByte = IOUtils.read(is)) != -1) { if(nextByte == 0xff) { nextByte = IOUtils.read(is); if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } if (nextByte != 0x00) { marker = (short)((0xff<<8)|nextByte); switch (Marker.fromShort(marker)) { case RST0: case RST1: case RST2: case RST3: case RST4: case RST5: case RST6: case RST7: continue; default: } break; } } } if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } return marker; } // Remove APPn segment public static void removeAPPn(Marker APPn, InputStream is, OutputStream os) throws IOException { if(APPn.getValue() < (short)0xffe0 || APPn.getValue() > (short)0xffef) throw new IllegalArgumentException("Input marker is not an APPn marker"); // Flag when we are done boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if(Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.EOI) { IOUtils.writeShortMM(os, Marker.EOI.getValue()); finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. IOUtils.writeShortMM(os, marker); marker = IOUtils.readShortMM(is); break; case PADDING: IOUtils.writeShortMM(os, marker); int nextByte = 0; while((nextByte = IOUtils.read(is)) == 0xff) { IOUtils.write(os, nextByte); } marker = (short)((0xff<<8)|nextByte); break; case SOS: IOUtils.writeShortMM(os, marker); // use copyToEnd instead for multiple SOS //marker = copySOS(is, os); copyToEnd(is, os); finished = true; break; default: length = IOUtils.readUnsignedShortMM(is); byte[] buf = new byte[length - 2]; IOUtils.readFully(is, buf); if(emarker != APPn) { // Copy the data IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short)length); IOUtils.write(os, buf); } marker = IOUtils.readShortMM(is); } } } } public static void removeMetadata(InputStream is, OutputStream os, MetadataType ... metadataTypes) throws IOException { removeMetadata(new HashSet<MetadataType>(Arrays.asList(metadataTypes)), is, os); } // Remove meta data segments public static void removeMetadata(Set<MetadataType> metadataTypes, InputStream is, OutputStream os) throws IOException { // Flag when we are done boolean finished = false; int length = 0; short marker; Marker emarker; // The very first marker should be the start_of_image marker! if (Marker.fromShort(IOUtils.readShortMM(is)) != Marker.SOI) throw new IOException("Invalid JPEG image, expected SOI marker not found!"); IOUtils.writeShortMM(os, Marker.SOI.getValue()); marker = IOUtils.readShortMM(is); while (!finished) { if (Marker.fromShort(marker) == Marker.EOI) { IOUtils.writeShortMM(os, Marker.EOI.getValue()); finished = true; } else { // Read markers emarker = Marker.fromShort(marker); switch (emarker) { case JPG: // JPG and JPGn shouldn't appear in the image. case JPG0: case JPG13: case TEM: // The only stand alone marker besides SOI, EOI, and RSTn. IOUtils.writeShortMM(os, marker); marker = IOUtils.readShortMM(is); break; case PADDING: IOUtils.writeShortMM(os, marker); int nextByte = 0; while ((nextByte = IOUtils.read(is)) == 0xff) { IOUtils.write(os, nextByte); } marker = (short) ((0xff << 8) | nextByte); break; case SOS: // There should be no meta data after this segment IOUtils.writeShortMM(os, marker); copyToEnd(is, os); finished = true; break; case COM: if(metadataTypes.contains(MetadataType.COMMENT)) { length = IOUtils.readUnsignedShortMM(is); IOUtils.skipFully(is, length - 2); marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP0: if(metadataTypes.contains(MetadataType.JPG_JFIF)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // Not JFIF segment if (temp.length < JFIF_ID.length() || ! JFIF_ID.equals(new String(temp, 0, JFIF_ID.length()))) { IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP1: // We are only interested in EXIF and XMP if(metadataTypes.contains(MetadataType.EXIF) || metadataTypes.contains(MetadataType.XMP)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // XMP or EXIF segment if((metadataTypes.contains(MetadataType.XMP) && temp.length >= XMP_EXT_ID.length() && new String(temp, 0, XMP_EXT_ID.length()).equals(XMP_EXT_ID)) || (metadataTypes.contains(MetadataType.XMP) && temp.length >= XMP_ID.length() && new String(temp, 0, XMP_ID.length()).equals(XMP_ID)) || (metadataTypes.contains(MetadataType.XMP) && temp.length >= NON_STANDARD_XMP_ID.length() && new String(temp, 0, NON_STANDARD_XMP_ID.length()).equals(NON_STANDARD_XMP_ID)) || (metadataTypes.contains(MetadataType.EXIF) && temp.length >= EXIF_ID.length() && new String(temp, 0, EXIF_ID.length()).equals(EXIF_ID))) { // EXIF // We don't need to do anything } else { // We don't want to remove any of them IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP2: if(metadataTypes.contains(MetadataType.ICC_PROFILE)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // Not ICC_Profile segment if (temp.length < ICC_PROFILE_ID.length() || ! ICC_PROFILE_ID.equals(new String(temp, 0, ICC_PROFILE_ID.length()))) { IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP12: if(metadataTypes.contains(MetadataType.JPG_DUCKY)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // Not Ducky segment if (temp.length < DUCKY_ID.length() || ! DUCKY_ID.equals(new String(temp, 0, DUCKY_ID.length()))) { IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP13: if(metadataTypes.contains(MetadataType.PHOTOSHOP_IRB) || metadataTypes.contains(MetadataType.IPTC) || metadataTypes.contains(MetadataType.XMP) || metadataTypes.contains(MetadataType.EXIF)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // PHOTOSHOP IRB segment if (temp.length >= PHOTOSHOP_IRB_ID.length() && new String(temp, 0, PHOTOSHOP_IRB_ID.length()).equals(PHOTOSHOP_IRB_ID)) { IRB irb = new IRB(ArrayUtils.subArray(temp, PHOTOSHOP_IRB_ID.length(), temp.length - PHOTOSHOP_IRB_ID.length())); // Shallow copy the map. Map<Short, _8BIM> bimMap = new HashMap<Short, _8BIM>(irb.get8BIM()); if(!metadataTypes.contains(MetadataType.PHOTOSHOP_IRB)) { if(metadataTypes.contains(MetadataType.IPTC)) { // We only remove IPTC_NAA and keep the other IRB data untouched. bimMap.remove(ImageResourceID.IPTC_NAA.getValue()); } if(metadataTypes.contains(MetadataType.XMP)) { // We only remove XMP and keep the other IRB data untouched. bimMap.remove(ImageResourceID.XMP_METADATA.getValue()); } if(metadataTypes.contains(MetadataType.EXIF)) { // We only remove EXIF and keep the other IRB data untouched. bimMap.remove(ImageResourceID.EXIF_DATA1.getValue()); bimMap.remove(ImageResourceID.EXIF_DATA3.getValue()); } // Write back the IRB writeIRB(os, bimMap.values()); } } else { IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; case APP14: if(metadataTypes.contains(MetadataType.JPG_ADOBE)) { length = IOUtils.readUnsignedShortMM(is); byte[] temp = new byte[length - 2]; IOUtils.readFully(is, temp); // Not Adobe segment if (temp.length < ADOBE_ID.length() || ! ADOBE_ID.equals(new String(temp, 0, ADOBE_ID.length()))) { IOUtils.writeShortMM(os, marker); IOUtils.writeShortMM(os, (short) length); IOUtils.write(os, temp); } marker = IOUtils.readShortMM(is); } else marker = copySegment(marker, is, os); break; default: marker = copySegment(marker, is, os); } } } } @SuppressWarnings("unused") private static short skipSOS(InputStream is) throws IOException { int nextByte = 0; short marker = 0; while((nextByte = IOUtils.read(is)) != -1) { if(nextByte == 0xff) { nextByte = IOUtils.read(is); if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } if (nextByte != 0x00) { // This is a marker marker = (short)((0xff<<8)|nextByte); switch (Marker.fromShort(marker)) { case RST0: case RST1: case RST2: case RST3: case RST4: case RST5: case RST6: case RST7: continue; default: } break; } } } if (nextByte == -1) { throw new IOException("Premature end of SOS segment!"); } return marker; } private static void writeComment(String comment, OutputStream os) throws IOException { new COMBuilder().comment(comment).build().write(os); } /** * Write ICC_Profile as one or more APP2 segments * <p> * Due to the JPEG segment length limit, we have * to split ICC_Profile data and put them into * different APP2 segments if the data can not fit * into one segment. * * @param os output stream to write the ICC_Profile * @param data ICC_Profile data * @throws IOException */ private static void writeICCProfile(OutputStream os, byte[] data) throws IOException { // ICC_Profile ID int maxSegmentLen = 65535; int maxICCDataLen = 65519; int numOfSegment = data.length/maxICCDataLen; int leftOver = data.length%maxICCDataLen; int totalSegment = (numOfSegment == 0)? 1: ((leftOver == 0)? numOfSegment: (numOfSegment + 1)); for(int i = 0; i < numOfSegment; i++) { IOUtils.writeShortMM(os, Marker.APP2.getValue()); IOUtils.writeShortMM(os, maxSegmentLen); IOUtils.write(os, ICC_PROFILE_ID.getBytes()); IOUtils.writeShortMM(os, totalSegment|(i+1)<<8); IOUtils.write(os, data, i*maxICCDataLen, maxICCDataLen); } if(leftOver != 0) { IOUtils.writeShortMM(os, Marker.APP2.getValue()); IOUtils.writeShortMM(os, leftOver + 16); IOUtils.write(os, ICC_PROFILE_ID.getBytes()); IOUtils.writeShortMM(os, totalSegment|totalSegment<<8); IOUtils.write(os, data, data.length - leftOver, leftOver); } } private static void writeIRB(OutputStream os, _8BIM ... bims) throws IOException { if(bims != null && bims.length > 0) writeIRB(os, Arrays.asList(bims)); } private static void writeIRB(OutputStream os, Collection<_8BIM> bims) throws IOException { if(bims != null && bims.size() > 0) { IOUtils.writeShortMM(os, Marker.APP13.getValue()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); for(_8BIM bim : bims) bim.write(bout); // Write segment length IOUtils.writeShortMM(os, 14 + 2 + bout.size()); // Write segment data os.write(PHOTOSHOP_IRB_ID.getBytes()); os.write(bout.toByteArray()); } } // Prevent from instantiation private JPGMeta() {} }
package org.goplayer.game; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.goplayer.go.Goban; import org.goplayer.go.Stone; import org.goplayer.go.StoneColor; import org.goplayer.util.Coord; public class Block implements Iterable<Stone> { private final Set<Stone> stones; public Block(Collection<Stone> stones) { this.stones = Collections.unmodifiableSet(new HashSet<Stone>(stones)); } public Block(Stone... stones) { this(Arrays.asList(stones)); } public Collection<Stone> getStones() { return stones; } public Integer size() { return getStones().size(); } public StoneColor getColor() { return stones.iterator().next().getColor(); } public boolean contains(Stone stone) { return stones.contains(stone); } public static Block generateFrom(Goban goban, int startRow, int startCol) { final List<Stone> stones = new ArrayList<Stone>(); final Stone reference = goban.getCoordContent(startRow, startCol); if (reference == null) { // do not fill anything } else { final List<Coord> check = new ArrayList<Coord>(); final Set<Coord> explored = new HashSet<Coord>(); for (int row = 0; row < goban.getRowCount(); row++) { explored.add(new Coord(row, -1)); explored.add(new Coord(row, goban.getColCount())); } for (int col = 0; col < goban.getColCount(); col++) { explored.add(new Coord(-1, col)); explored.add(new Coord(goban.getRowCount(), col)); } check.add(new Coord(startRow, startCol)); StoneColor refColor = reference.getColor(); while (!check.isEmpty()) { Coord coord = check.remove(0); int row = coord.getRow(); int col = coord.getCol(); Stone stone = goban.getCoordContent(row, col); if (stone != null && stone.getColor() == refColor) { stones.add(stone); explored.add(coord); check.add(new Coord(row + 1, col)); check.add(new Coord(row - 1, col)); check.add(new Coord(row, col + 1)); check.add(new Coord(row, col - 1)); check.removeAll(explored); } else { continue; } } } return new Block(stones); } @Override public Iterator<Stone> iterator() { return stones.iterator(); } }
package authoring.concretefeatures.menus; import gamedata.gamecomponents.Game; import gamedata.gamecomponents.Grid; import gamedata.gamecomponents.Level; import gamedata.gamecomponents.SquareGrid; import gamedata.goals.Goal; import gamedata.goals.PlayerPiecesRemovedGoal; import gamedata.rules.MoveCountRule; import gamedata.rules.Rule; import gameengine.engine.GameBuilder; import gameengine.player.Player; import java.util.ArrayList; import java.util.List; /** * Tester for JSON file writer * @author Rica * */ public class JSONBobTester { public JSONBobTester() { createNewGame(); } /** * Create a new game to test * @return */ public Game createNewGame () { System.out.println("JSONBobTester is running"); List<Player> myPlayers = new ArrayList<Player>(); Player myPlayer1 = new Player(); Player myPlayer2 = new Player(); myPlayers.add(myPlayer1); myPlayers.add(myPlayer2); Grid grid1 = new SquareGrid(); Rule rule1 = new MoveCountRule(3); List<Level> myLevels = new ArrayList<Level>(); List<Rule> myRules = new ArrayList<Rule>(); List<Goal> myGoals = new ArrayList<Goal>(); // testing if subclasses of goal abstract class is initialized properly Goal goal1 = new PlayerPiecesRemovedGoal(myPlayer2); myGoals.add(goal1); Goal goal2 = new PlayerPiecesRemovedGoal(myPlayer1); myGoals.add(goal2); myRules.add(rule1); Level level1 = new Level(grid1, myGoals, myRules); Level level2 = new Level(grid1, myGoals, myRules); myLevels.add(level1); myLevels.add(level2); Player myPlayer3 = new Player(); myPlayers.add(myPlayer3); Game myGame = new Game(myPlayers, myLevels); return myGame; } }
package org.catacombae.io; public class ConcatenatedStream extends BasicConcatenatedStream<RandomAccessStream> implements RandomAccessStream { public ConcatenatedStream(RandomAccessStream firstPart, long startOffset, long length) { super(firstPart, startOffset, length); } public void write(byte[] data) throws RuntimeIOException { BasicWritable.defaultWrite(this, data); } public void write(byte[] data, int off, int len) throws RuntimeIOException { int bytesWritten = 0; // First: Look up the position represented by our virtual file pointer. long bytesToSkip = virtualFP; int requestedPartIndex = 0; for(Part p : parts) { if(bytesToSkip < p.length) { /* The first byte of virtualFP is within this part. */ break; } ++requestedPartIndex; bytesToSkip -= p.length; } if(requestedPartIndex >= parts.size()) { throw new RuntimeIOException("Tried to write beyond end of " + "stream."); } // Loop as long as we still have data to fill, and we still have parts to process. while(bytesWritten < len && requestedPartIndex < parts.size()) { Part requestedPart = parts.get(requestedPartIndex++); long bytesToSkipInPart = bytesToSkip; bytesToSkip = 0; int bytesLeftToWrite = len - bytesWritten; int bytesToWrite = (int) ((bytesLeftToWrite < requestedPart.length) ? bytesLeftToWrite : requestedPart.length); requestedPart.file.seek(bytesToSkipInPart); requestedPart.file.write(data, off + bytesWritten, bytesToWrite); bytesWritten += bytesToWrite; } if(bytesWritten < len) throw new RuntimeIOException("Could not write all data requested (wrote: " + bytesWritten + " requested:" + len + "."); if(bytesWritten > len) // Debug check. throw new RuntimeException("Wrote more than I was supposed to (" + bytesWritten + " / " + len + " bytes)! This can't happen."); } public void write(int data) throws RuntimeIOException { BasicWritable.defaultWrite(this, data); } }
package caris.framework.embedbuilders; import caris.framework.library.Constants; import caris.framework.library.UserInfo; import caris.framework.tokens.Mail; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.EmbedBuilder; public class MailCheckBuilder extends Builder { public UserInfo userInfo; public IUser user; public MailCheckBuilder(UserInfo userInfo) { super(); this.userInfo = userInfo; this.user = userInfo.user; } @Override public void buildEmbeds() { embeds.add(new EmbedBuilder()); embeds.get(0).withAuthorName(user.getName() + "#" + user.getDiscriminator() + "'s Mailbox"); embeds.get(0).withDescription("Type `" + Constants.INVOCATION_PREFIX + " mailbox open <#>` to open a message!" + "\n" + "Type `" + Constants.INVOCATION_PREFIX + " mailbox delete <#>` to delete a message!" + "\n" + "Type `" + Constants.INVOCATION_PREFIX + " mailbox send <@user> \"message\"` to send a message!"); if( userInfo.mailbox.isEmpty() ) { embeds.get(0).withTitle(":mailbox_with_no_mail: *Your mailbox is empty!*"); } else { embeds.get(0).withTitle(":mailbox_with_mail: *You've got mail!*"); } int count = 0; for( Mail mail : userInfo.mailbox.getMail() ) { if( count != 0 && count%25 == 0 ) { embeds.add(new EmbedBuilder()); embeds.get(count/25).withAuthorName(user.getName() + "#" + user.getDiscriminator() + "'s Mailbox"); } if( mail.read ) { embeds.get(count/25).appendField("**" + (count+1) + ". " + mail.user.getName() + "#" + mail.user.getDiscriminator() + "**", ">> *" + mail.getPreview() + "*", false); } else { embeds.get(count/25).appendField((count+1) + ". " + mail.user.getName() + "#" + mail.user.getDiscriminator(), ">> *" + mail.getPreview() + "*", false); } count++; } for( int f=0; f<embeds.size(); f++ ) { embeds.get(f).withFooterText("Page " + (f+1) + " / " + embeds.size()); } } }
package com.plugin.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.content.WakefulBroadcastReceiver; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.json.JSONException; import org.json.JSONObject; import java.util.Random; /* * Implementation of GCMBroadcastReceiver that hard-wires the intent service to be * com.plugin.gcm.GcmntentService, instead of your_package.GcmIntentService */ public class CordovaGCMBroadcastReceiver extends WakefulBroadcastReceiver { private static final String TAG = "GcmIntentService"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onHandleIntent - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String messageType = gcm.getMessageType(intent); if (extras != null) { try { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "error"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "deleted"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } catch (JSONException exception) { Log.d(TAG, "JSON Exception was had!"); } } } public void createNotification(Context context, Bundle extras) { int notId = 0; try { notId = Integer.parseInt(extras.getString("notId", "0")); } catch (NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } if (notId == 0) { // no notId passed, so assume we want to show all notifications, so make it a random number notId = new Random().nextInt(100000); Log.d(TAG, "Generated random notId: " + notId); } else { Log.d(TAG, "Received notId: " + notId); } NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(context); Intent notificationIntent = new Intent(context, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException e) { } } Bitmap bm = BitmapFactory.decodeResource(getResources(), context.getApplicationInfo().icon); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(getSmallIcon(context, extras)) .setLargeIcon(bm) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } String soundName = extras.getString("sound"); if (soundName != null) { Resources r = context.getResources(); int resourceId = r.getIdentifier(soundName, "raw", context.getPackageName()); Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceId); mBuilder.setSound(soundUri); defaults &= ~Notification.DEFAULT_SOUND; mBuilder.setDefaults(defaults); } mNotificationManager.notify(appName, notId, mBuilder.build()); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String) appName; } private int getSmallIcon(Context context, Bundle extras) { int smallIcon = -1; // first try an iconname possible passed in the server payload final String smallIconNameFromServer = extras.getString("smallIcon"); if (smallIconNameFromServer != null) { smallIcon = getIconValue(context.getPackageName(), smallIconNameFromServer); } // try a custom included icon in our bundle named ic_stat_notify(.png) if (smallIcon == -1) { smallIcon = getIconValue(context.getPackageName(), "ic_stat_notify"); } // fall back to the regular app icon if (smallIcon == -1) { smallIcon = context.getApplicationInfo().icon; } return smallIcon; } private int getIconValue(String className, String iconName) { try { Class<?> clazz = Class.forName(className + ".R$drawable"); return (Integer) clazz.getDeclaredField(iconName).get(Integer.class); } catch (Exception ignore) {} return -1; } }
package cc.adjusting.piece; import cc.moveable_type.piece.PieceMovableTypeTzu; import cc.moveable_type.rectangular_area.RectangularArea; /** * * * @author Ihc */ public class extends { /** * * * @param * */ public (MergePieceAdjuster ) { super(); .add(""); .add(""); .add(""); .add(""); // TODO } @Override public void (PieceMovableTypeTzu ) { = new (); = new (); = new (, , , false); RectangularArea[] = .(.()); .getPiece().(); return; } }
package com.awsmithson.tcx2nikeplus.convert; import com.awsmithson.tcx2nikeplus.util.Log; import com.awsmithson.tcx2nikeplus.util.Util; import flanagan.interpolation.CubicSpline; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone; import java.util.logging.Level; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.logging.impl.Log4JLogger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ConvertTcx { private static final double D_METRES_PER_MILE = 1609.344; private static final int MILLIS_PER_HOUR = 60 * 1000 * 60; private static final String DATE_TIME_FORMAT_NIKE = "yyyy-MM-dd'T'HH:mm:ssZ"; private static final String DATE_TIME_FORMAT_HUMAN = "d MMM yyyy HH:mm:ss z"; // The minimum amount of millis between Trackpoints that I am prepared to create a potential pause/resume for. private static final int MILLIS_POTENTIAL_PAUSE_THRESHOLD = 0; private long _totalDuration; private double _totalDistance; private boolean _forceExcludeHeartRateData; private boolean _includeHeartRateData = false; private TimeZone _workoutTimeZone; private Calendar _calStart; private Calendar _calEnd; private String _startTimeString; private String _startTimeStringHuman; private static final Log log = Log.getInstance(); /** * Converts a garmin tcx file to a nike+ workout xml document. * <p> * This class is a hacky mess just now but it does the job. * @author angus */ public ConvertTcx() { } public Document generateNikePlusXml(File tcxFile, String empedID) throws Throwable { return generateNikePlusXml(tcxFile, empedID, false); } public Document generateNikePlusXml(File tcxFile, String empedID, boolean forceExcludeHeartRateData) throws Throwable { //try { _forceExcludeHeartRateData = forceExcludeHeartRateData; Document tcxDoc = Util.generateDocument(tcxFile); return generateNikePlusXml(tcxDoc, empedID); //catch (Exception e) { // log.out(e); // return null; } public Document generateNikePlusXml(Document inDoc, String empedID) throws Throwable { return generateNikePlusXml(inDoc, empedID, null); } public Document generateNikePlusXml(Document inDoc, String empedID, Integer clientTimeZoneOffset) throws Throwable { return generateNikePlusXml(inDoc, empedID, clientTimeZoneOffset, false); } public Document generateNikePlusXml(Document inDoc, String empedID, Integer clientTimeZoneOffset, boolean forceExcludeHeartRateData) throws Throwable { _forceExcludeHeartRateData = forceExcludeHeartRateData; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //try { // Create output document DocumentBuilder db = dbf.newDocumentBuilder(); Document outDoc = db.newDocument(); // Sports Data (root) Element sportsDataElement = Util.appendElement(outDoc, "sportsData"); // Vers //Util.appendElement(sportsDataElement, "vers", "8"); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Run Summary Element runSummary = appendRunSummary(inDoc, sportsDataElement, clientTimeZoneOffset); // Template appendTemplate(sportsDataElement); // Goal Type appendGoalType(sportsDataElement); // User Info appendUserInfo(inDoc, sportsDataElement, empedID); // Start Time Util.appendElement(sportsDataElement, "startTime", _startTimeString); // Workout Detail appendWorkoutDetail(inDoc, sportsDataElement, runSummary); // Test lap durations //testLapDuration(inDoc); //printDocument(outDoc); //writeDocument(outDoc); //return new String[] { generateString(outDoc), generateFileName() }; return outDoc; //catch (Exception e) { // log.out(e); // return null; } /** * Generates a run summary xml element like: * <pre> * {@code * <runSummary> * <workoutName><![CDATA[Basic]]></workoutName> * <time>2009-06-12T10:00:00-10:00</time> * <duration>1760000</duration> * <durationString>29:20</durationString> * <distance unit="km">6.47</distance> * <distanceString>6.47 km</distanceString> * <pace>4:32 min/km</pace> * <calories>505</calories> * <battery></battery> * <stepCounts> * <walkBegin>0</walkBegin> * <walkEnd>0</walkEnd> * <runBegin>0</runBegin> * <runEnd>0</runEnd> * </stepCounts> * </runSummary> * } * </pre> * @param inDoc The garmin tcx document we are reading the data from. * @param sportsDataElement An xml element we have already created "sportsDataElement" * @param clientTimeZoneOffset The client timezone offset to use in the event we are unable to determine workout timezone from the gps coordinates. * @return The runSummary xml element. * @throws DatatypeConfigurationException * @throws IOException * @throws MalformedURLException * @throws ParserConfigurationException * @throws SAXException */ private Element appendRunSummary(Document inDoc, Element sportsDataElement, Integer clientTimeZoneOffset) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { Element runSummaryElement = Util.appendElement(sportsDataElement, "runSummary"); // Workout Name //Util.appendCDATASection(runSummaryElement, "workoutName", "Basic"); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Start Time appendStartTime(inDoc, runSummaryElement, clientTimeZoneOffset); // Duration, Duration, Pace & Calories appendTotals(inDoc, runSummaryElement); // Battery Util.appendElement(runSummaryElement, "battery"); // Step Counts //appendStepCounts(runSummaryElement); // 2010-09-13: I've noticed this is not included in the iphone xml output. return runSummaryElement; } private void appendStartTime(Document inDoc, Element runSummaryElement, Integer clientTimeZoneOffset) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { // Garmin: 2009-06-03T16:59:27.000Z // Nike: 2009-06-03T17:59:27+01:00 // Get the timezone based on the Latitude, Longitude & Time (UTC) of the first TrackPoint _workoutTimeZone = getWorkoutTimeZone(inDoc, clientTimeZoneOffset); if (_workoutTimeZone == null) _workoutTimeZone = TimeZone.getTimeZone("Etc/UTC"); log.out("Time zone millis offset (vs server): %d", _workoutTimeZone.getRawOffset()); // Set the the SimpleDateFormat object so that it prints the time correctly: // local-time + UTC-difference. SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT_NIKE); df.setTimeZone(_workoutTimeZone); // Get the workout start-time, format for nike+ and add it to the out-document Calendar calStart = Util.getCalendarValue(Util.getSimpleNodeValue(inDoc, "Id")); Date dateStart = calStart.getTime(); _startTimeString = df.format(dateStart); _startTimeString = String.format("%s:%s", _startTimeString.substring(0, 22), _startTimeString.substring(22)); Util.appendElement(runSummaryElement, "time", _startTimeString); // Generate a human readable start-string we can use for debugging. df.applyPattern(DATE_TIME_FORMAT_HUMAN); _startTimeStringHuman = df.format(dateStart); // We need these later. _calStart = calStart; } // deduce in which time zone the workout began. private TimeZone getWorkoutTimeZone(Document inDoc, Integer clientTimeZoneOffset) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { NodeList positions = inDoc.getElementsByTagName("Position"); int positionsLength = positions.getLength(); // Loop through the Position data, we will return as soon as we find one // with the required data (latitude & longitude). for (int i = 0; i < positionsLength; ++i) { Double latitude = null; Double longitude = null; NodeList positionData = positions.item(i).getChildNodes(); int positionDataLength = positionData.getLength(); for (int j = 0; j < positionDataLength; ++j) { Node n = positionData.item(j); String nodeName = n.getNodeName(); // Latitude at this point if (nodeName.equals("LatitudeDegrees")) { latitude = Double.parseDouble(Util.getSimpleNodeValue(n)); } // Longitude at this point else if (nodeName.equals("LongitudeDegrees")) { longitude = Double.parseDouble(Util.getSimpleNodeValue(n)); } if ((latitude != null) && (longitude != null)) { // Send a post to the geonames.org webservice with the lat & lng parameters. String url = "http://ws.geonames.org/timezone"; String parameters = String.format("lat=%s&lng=%s", latitude, longitude); log.out("Looking up time zone for lat/lon: %.4f / %.4f", latitude, longitude); try { Document response = Util.downloadFile(url, parameters); String timeZoneId = Util.getSimpleNodeValue(response, "timezoneId"); log.out(" - %s", timeZoneId); return TimeZone.getTimeZone(timeZoneId); } catch (Throwable t) { // If, for whatever reason we are unable to get the timezone and we have a clientTimeZoneOffset then use that. if (clientTimeZoneOffset != null) { int hours = clientTimeZoneOffset / 60; int minutes = Math.abs(clientTimeZoneOffset) % 60; String mm = String.format(((minutes < 10) ? "0%d" : "%d"), minutes); String tz = String.format("GMT%s%d:%s", (hours < 0) ? "" : "+", hours, mm); log.out("Unable to retrieve workout timezone from http://ws.geonames.org, attempting to use client-timezone %s instead.", tz); return TimeZone.getTimeZone(tz); } else { TimeZone tz = TimeZone.getDefault(); log.out(Level.WARNING, "Unable to retrieve workout timezone (http://ws.geonames.org is not available right now). Using default timezone: %s", tz.getID()); return tz; } } } } } return null; } private void appendTotals(Document inDoc, Node parent) { double totalSeconds = 0d; double totalDistance = 0d; int totalCalories = 0; NodeList laps = inDoc.getElementsByTagName("Lap"); int lapsLength = laps.getLength(); for (int i = 0; i < lapsLength; ++i) { NodeList lapData = laps.item(i).getChildNodes(); int lapInfoLength = lapData.getLength(); for (int j = 0; j < lapInfoLength; ++j) { Node n = lapData.item(j); String nodeName = n.getNodeName(); if (nodeName.equals("TotalTimeSeconds")) totalSeconds += Double.parseDouble(Util.getSimpleNodeValue(n)); else if (nodeName.equals("DistanceMeters")) totalDistance += Double.parseDouble(Util.getSimpleNodeValue(n)); else if (nodeName.equals("Calories")) totalCalories += Integer.parseInt(Util.getSimpleNodeValue(n)); } } long totalDuration = (long)(totalSeconds * 1000); _totalDuration = totalDuration; _totalDistance = totalDistance; // Calculate the end-time of the run (for use late to generate the xml filename). _calEnd = (Calendar)(_calStart.clone()); _calEnd.add(Calendar.MILLISECOND, (int)totalDuration); // Total Duration Util.appendElement(parent, "duration", totalDuration); //Util.appendElement(parent, "durationString", getTimeStringFromMillis(totalDuration)); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Total Distance //totalDistance = totalDistance.divide(BD_1000); totalDistance /= 1000; Util.appendElement(parent, "distance", String.format("%.4f", totalDistance), "unit", "km"); //Util.appendElement(parent, "distanceString", String.format("%.2f km", totalDistance)); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Pace //Util.appendElement(parent, "pace", String.format("%s min/km", getTimeStringFromMillis(calculatePace(totalDuration, totalDistance)))); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Calories - FIXME - calories are not calculated properly yet... Util.appendElement(parent, "calories", totalCalories); } /* // 2010-09-13: I've noticed this is not included in the iphone xml output. private void appendStepCounts(Node parent) { Element stepCountsElement = Util.appendElement(parent, "stepCounts"); Util.appendElement(stepCountsElement, "walkBegin", "0"); Util.appendElement(stepCountsElement, "walkEnd", "0"); Util.appendElement(stepCountsElement, "runBegin", "0"); Util.appendElement(stepCountsElement, "runEnd", "0"); } */ /* <template><templateID>8D495DCE</templateID> <templateName><![CDATA[Basic]]></templateName> </template> */ private void appendTemplate(Element sportsDataElement) { Element templateElement = Util.appendElement(sportsDataElement, "template"); //Util.appendElement(templateElement, "templateID", "8D495DCE"); // 2010-09-13: I've noticed this is not included in the iphone xml output. Util.appendCDATASection(templateElement, "templateName", "Basic"); } // <goal type="" value="" unit=""></goal> private void appendGoalType(Element sportsDataElement) { Util.appendElement(sportsDataElement, "goal", null, "type", "", "value", "", "unit", ""); } /* <userInfo> <empedID>XXXXXXXXXXX</empedID> <weight></weight> <device>iPod</device> <calibration></calibration> </userInfo> */ private void appendUserInfo(Document inDoc, Element sportsDataElement, String empedID) { Element templateElement = Util.appendElement(sportsDataElement, "userInfo"); Util.appendElement(templateElement, "empedID", (empedID == null) ? "XXXXXXXXXXX" : empedID); Util.appendElement(templateElement, "weight"); // Upload goes through fine when "Garmin Forerunner 405 is specified as device but on nikeplus.com website some data shows as "invalid" //Util.appendElement(templateElement, "device", getSimpleNodeValue(inDoc, "Name")); // Garmin Forerunner 405 Util.appendElement(templateElement, "device", "iPod"); // iPod Util.appendElement(templateElement, "calibration"); } private void appendWorkoutDetail(Document inDoc, Element sportsDataElement, Element runSummaryElement) throws DatatypeConfigurationException { // Generate the workout detail from the garmin Trackpoint data. ArrayList<Trackpoint> trackpoints = new ArrayList<Trackpoint>(); ArrayList<Double> onDemandVPDistances = new ArrayList<Double>(); ArrayList<Long> pauseResumeTimes = new ArrayList<Long>(); generateCubicSplineData(inDoc, trackpoints, onDemandVPDistances, pauseResumeTimes); // Generates the following CubicSplines: distanceToDuration, durationToDistance, durationToPace, durationToHeartRate. CubicSpline[] splines = generateCubicSplines(trackpoints); appendSnapShotListAndExtendedData(sportsDataElement, onDemandVPDistances, pauseResumeTimes, splines[0], splines[1], splines[2], splines[3]); // Append heart rate detail to the run summary if required. if (_includeHeartRateData) { Trackpoint min = null; Trackpoint max = null; int average = 0; for (Trackpoint tp : trackpoints) { int heartRate = tp.getHeartRate().intValue(); if ((min == null) || (heartRate < min.getHeartRate())) min = tp; if ((max == null) || (heartRate > max.getHeartRate())) max = tp; average += (heartRate * tp.getDurationSinceLastTrackpoint()); } average /= _totalDuration; Element heartRateElement = Util.appendElement(runSummaryElement, "heartRate"); Util.appendElement(heartRateElement, "average", average); appendHeartRateSummary(heartRateElement, "minimum", min); appendHeartRateSummary(heartRateElement, "maximum", max); //Util.appendElement(heartRateElement, "battery", 3); // 2010-09-13: I've noticed this is not included in the iphone xml output. } } private void appendHeartRateSummary(Element heartRateElement, String type, Trackpoint tp) { Element heartRateTypeElement = Util.appendElement(heartRateElement, type); Util.appendElement(heartRateTypeElement, "duration", tp.getDuration()); Util.appendElement(heartRateTypeElement, "distance", String.format("%.3f", tp.getDistance()/1000)); Util.appendElement(heartRateTypeElement, "pace", tp.getPace()); Util.appendElement(heartRateTypeElement, "bpm", tp.getHeartRate().intValue()); } private void generateCubicSplineData(Document inDoc, ArrayList<Trackpoint> trackpointsStore, ArrayList<Double> onDemandVPDistances, ArrayList<Long> pauseResumeTimes) throws DatatypeConfigurationException { // Setup a trackpoint based on the very start of the run in case there is a long pause right at the start. Trackpoint previousTp = new Trackpoint(0l, 0d, 0d, null); trackpointsStore.add(previousTp); NodeList laps = inDoc.getElementsByTagName("Lap"); int lapsLength = laps.getLength(); long lapStartDuration = 0; for (int i = 0; i < lapsLength; ++i) { Node lap = laps.item(i); long lapStartTime = Util.getCalendarNodeValue(lap.getAttributes().getNamedItem("StartTime")).getTimeInMillis(); long lapDuration = (long)(Double.parseDouble(Util.getSimpleNodeValue(Util.getFirstChildByNodeName(lap, "TotalTimeSeconds"))) * 1000); log.out(Level.FINE, "Start of lap %d\tDuration: %d -> %d.", (i + 1), lapStartDuration, (lapStartDuration + lapDuration)); ArrayList<Trackpoint> lapTrackpointStore = generateLapCubicSplineData(lap, onDemandVPDistances, pauseResumeTimes, getLastTrackpointFromArrayList(trackpointsStore), lapStartTime, lapStartDuration, lapDuration); trackpointsStore.addAll(lapTrackpointStore); lapStartDuration += lapDuration; log.out(Level.FINE, ("End of lap.\n")); } // Remove strange trackpoints (repeat distance/durations). // Also, for each trackpoint, add a heart-rate reading if one is required & update the previous-trackpoints reference. previousTp = null; Iterator<Trackpoint> tpsIt = trackpointsStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); tp.setPreviousTrackpoint(previousTp); if ((tp.getDistance() == null) || (tp.isRepeatDistance())) { log.out(Level.FINE, "Removing invalid distance trackpoint:\t%s", tp); tpsIt.remove(); } else if ((tp.getDuration() == null) || (tp.isRepeatDuration())) { log.out(Level.FINE, "Removing invalid duration trackpoint:\t%s", tp); tpsIt.remove(); } else { if ((_includeHeartRateData) && (tp.getHeartRate() == null)) tp.setHeartRate(previousTp.getHeartRate()); previousTp = tp; log.out(Level.FINER, "Duration: %d\tDistance: %.4f", tp.getDuration(), tp.getDistance()); } } //log.out(Level.FINER, "Workout total duration: %d", _totalDuration); Trackpoint penultimateTp = getTrackpointFromEndofArrayList(trackpointsStore, 1); if (penultimateTp != null) { long pDur = penultimateTp.getDuration(); double pDist = penultimateTp.getDistance(); log.out("Trackpoint reading complete..."); log.out("Penultimate vs Required: Duration (secs): %d -> %d (%d). Distance (m): %.0f -> %.0f (%.0f)", pDur/1000, _totalDuration/1000, ((_totalDuration - pDur)/1000), pDist, _totalDistance, (_totalDistance - pDist)); } } private ArrayList<Trackpoint> generateLapCubicSplineData(Node lap, ArrayList<Double> onDemandVPDistances, ArrayList<Long> pauseResumeTimes, Trackpoint previousTp, long lapStartTime, long lapStartDuration, long lapDuration) throws DatatypeConfigurationException { ArrayList<Trackpoint> lapTrackpointStore = new ArrayList<Trackpoint>(); long lapEndDuration = lapStartDuration + lapDuration; double lapStartDistance = -1; double lapDistance = Double.parseDouble(Util.getSimpleNodeValue(Util.getFirstChildByNodeName(lap, "DistanceMeters"))); Double lapEndDistance = null; // Get the trackpoints for this lap - if there are none then continue to the next lap. Node[] tracks = Util.getChildrenByNodeName(lap, "Track"); if (tracks != null) { for (Node track : tracks) { // Get the trackpoints for this track - if there are none then continue to the next track. Node[] trackpoints = Util.getChildrenByNodeName(track, "Trackpoint"); if (trackpoints == null) continue; for (Node trackpoint : trackpoints) { // Loop through the data for this trackpoint storing the data. Trackpoint tp = new Trackpoint(previousTp); NodeList trackPointData = trackpoint.getChildNodes(); int trackPointDataLength = trackPointData.getLength(); for (int i = 0; i < trackPointDataLength && tp != null; ++i) { Node n = trackPointData.item(i); String nodeName = n.getNodeName(); // Run duration to this point if (nodeName.equals("Time")) tp.setDuration((Util.getCalendarNodeValue(n).getTimeInMillis() - lapStartTime) + lapStartDuration); // Distance to this point else if (nodeName.equals("DistanceMeters")) { double distance = Double.parseDouble(Util.getSimpleNodeValue(n)); // If this is the first trackpoint in the lap with a DistanceMeters value then calculate the start/end distance of the lap. if (lapStartDistance == -1) { lapStartDistance = distance; lapEndDistance = lapStartDistance + lapDistance; } tp.setDistance(distance); } // Heart rate bpm else if ((!_forceExcludeHeartRateData) && (nodeName.equals("HeartRateBpm"))) { NodeList heartRateData = n.getChildNodes(); int heartRateDataLength = heartRateData.getLength(); for (int j = 0; j < heartRateDataLength; ++j) { Node heartRateNode = heartRateData.item(j); if (heartRateNode.getNodeName().equals("Value")) { _includeHeartRateData = true; tp.setHeartRate(Double.parseDouble(Util.getSimpleNodeValue(heartRateNode))); } } } } // Store the trackpoint for validation/conversion later. if ((tp != null) && ((tp.getDistance() != null) || (trackPointDataLength == 3))) { lapTrackpointStore.add(tp); previousTp = tp; log.out(Level.FINEST, "New raw tcx-file Trackpoint, durations: %d -> %d = %d. distance: %.4f.", tp.getPreviousDuration(), tp.getDuration(), tp.getDuration() - tp.getPreviousDuration(), tp.getDistance()); } } } } Trackpoint lastTp = getLastTrackpointFromArrayList(lapTrackpointStore); if (lapEndDistance != null) { // Add a Trackpoint for the end of the lap if we haven't already got one at that distance/duration. if ((lastTp.getMostRecentDistance() < lapEndDistance) && (lastTp.getDuration() < lapEndDuration)) lapTrackpointStore.add(new Trackpoint(lapEndDuration, lapEndDistance, previousTp.getHeartRate(), lastTp)); // If this is not a km or mile distance lap/lap-end then store the end-distance for inserting as a "onDemandVP" click later. if (!(((lapDistance % 1000) == 0) || ((lapDistance % D_METRES_PER_MILE) == 0) || ((lapEndDistance % 1000) == 0) || ((lapEndDistance % D_METRES_PER_MILE) == 0))) onDemandVPDistances.add(lapEndDistance); } validateLapCubicSplineData(lap, lapTrackpointStore, pauseResumeTimes, lapEndDuration); long difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); log.out(Level.FINE, "Lap duration difference after validation:\t%d", difference); return lapTrackpointStore; } private void validateLapCubicSplineData(Node lap, ArrayList<Trackpoint> lapTrackpointStore, ArrayList<Long> pauseResumeDurations, long lapEndDuration) { // If we have no trackpoints then we don't need to validate. if (lapTrackpointStore.size() == 0) return; Node lapTotalTimeSeconds = Util.getFirstChildByNodeName(lap, "TotalTimeSeconds"); if (lapTotalTimeSeconds == null) return; long difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); log.out(Level.FINE, "Lap duration difference before validation:\t%d", difference); boolean paused = false; long durationPaused = 0; long lengthDecrement = 0; Trackpoint previousTp = null; // For pause/resmumes // - 1. Get the duration of the pause trackpoint to use for the pause/resume duration. // - 2. Remove the pause trackpoint. Our cublic splies will work out what the actual distance was up until this point. // - 3. The next trackpoint (or end of lap) will be the resume Trackpoint. // - 4. Use the duration data of this resume Trackpoint to calculate the length we were paused for. // - 5. Deduct the pause-length from all proceeding durations in the lap. Iterator<Trackpoint> tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); tp.decrementDuration(lengthDecrement); // Deal with 3-data pause/resume trackpoints. // If we are not paused already then this is a 'pause' trackpoint: // - 1. Record the duration. // - 2. Set paused=true. // - 3. Remove the trackpoint. // - 4. Loop again (get the next trackpoint). // If we are paused then this is a 'resume' trackpoint: // - 1. Store the pause/resume details, adding the length paused to the lengthDecrement variable. // - 2. Set paused=false // - 3. Remove the trackpoint. // - 4. Loop again (get the next trackpoint). if (tp.getDistance() == null) { if (!paused) durationPaused = tp.getDuration(); else lengthDecrement += addPauseResume(pauseResumeDurations, tp, durationPaused); paused = !paused; tpsIt.remove(); continue; } // Deal with normal trackpoints. // If we are paused then this is a 'resume' trackpoint: // - 1. Store the pause/resume details // - 2. Add the length paused to the lengthDecrement variable. // - 3. Decrement the current trackpoint with the amount we were paused for. // - 4. Set paused = false. if (paused) { long lengthPaused = addPauseResume(pauseResumeDurations, tp, durationPaused); lengthDecrement += lengthPaused; tp.decrementDuration(lengthPaused); paused = false; } tp.setPreviousTrackpoint(previousTp); previousTp = tp; } // After applying the tcx-detailed pause/resumes we still might have trackpoints whose durations exceed // the lap time. I think the primary reason for this is that garmin automatically pauses the device if it is // unable to get a satellite waypoint after a certain amount of seconds (seems to be 8 seconds on the 405 with // 2.50 firmware). To counter this I will basically strip away the slowest-paced (hopefully paused) sections of the // lap until our final trackpoint has a less than or equal to that of the lap duration. difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); // We allow up to 999 millis as due to rounding errors the lap-duration can be up to 1 second out. if (difference > 0) { log.out("Lap duration still invalid by %d millis, manually stripping.", difference); boolean modified = true; do { modified = false; double paceWorst = Double.MAX_VALUE; Trackpoint paceWorstTp = null; tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); // If our previous trackpoint is null then this is the first trackpoint so continue to the next trackpoint. if (tp.getPreviousTrackpoint() == null) continue; long duration = tp.getDuration(); long durationPrevious = tp.getPreviousDuration(); double distance = tp.getDistance(); double distancePrevious = tp.getPreviousDistance(); // Calculate distance & duration differences. double distanceIncrease = distance - distancePrevious; long durationIncrease = duration - tp.getPreviousDuration(); // if we have a distance increase of zero then remove the trackpoint and decrement all future trackpoints/pause-resumes by the duration we didn't increase for. if ((distanceIncrease == 0) && (durationIncrease > 0)) { long decrementLength = (difference > durationIncrease) ? durationIncrease : difference; log.out(Level.FINE, "Zero-distance decrement:\tDuration %d\tDistance %.4f\tLength: %d", durationPrevious, distancePrevious, decrementLength); tpsIt.remove(); if (tpsIt.hasNext()) { Trackpoint nextTp = tpsIt.next(); nextTp.decrementDuration(decrementLength); nextTp.setPreviousTrackpoint(previousTp); } while (tpsIt.hasNext()) tpsIt.next().decrementDuration(decrementLength); decrementPauseResumes(pauseResumeDurations, durationPrevious, decrementLength); modified = true; break; } double pace = (durationIncrease > MILLIS_POTENTIAL_PAUSE_THRESHOLD) ? (distanceIncrease / durationIncrease) : Double.MAX_VALUE; if (pace < paceWorst) { paceWorst = pace; paceWorstTp = tp; } } // If we haven't found any zero-distance trackpiont increases then decrement all future trackpoints/pause-resumes from the slowest pace trackpoint pair of the lap. if ((paceWorstTp != null) && !(modified)) { log.out(Level.FINE, "Slowest-pace decrement:\tDuration %d\tDistance %.4f", paceWorstTp.getPreviousDuration(), paceWorstTp.getPreviousDistance()); modified = true; tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); if (tp.equals(paceWorstTp)) { tp.decrementDuration(1000); while (tpsIt.hasNext()) tpsIt.next().decrementDuration(1000); decrementPauseResumes(pauseResumeDurations, tp.getDuration(), 1000); } } } } while ((modified) && ((difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration)) > 0)); } } /** * Get the difference (in millis) between the duration of the final trackpoint in the trackpoint-store and the expected lap-end-duration. * @param lapTrackpointStore An ArrayList of trackpoints for the lap - the last element in this collection should have duration less than lapEndDuration. * @param lapEndDuration The expected duration at the end of the lap. * @return The difference (positive if the trackpoint store exceeds the expected lap-end-duration). */ private long lapTrackpointDurationVsLapEndDuration(ArrayList<Trackpoint> lapTrackpointStore, long lapEndDuration) { return (lapTrackpointStore.size() == 0) ? 0 : roundToNearestThousand(getLastTrackpointFromArrayList(lapTrackpointStore).getDuration()) - roundToNearestThousand(lapEndDuration) ; } /** * Use this to round lap durations. The duration specified in the <code>&lt;Lap&gt;</code> element is to the nearest * millisecond whereas the data in the <code>&lt;Trackpoint&gt;</code> elements is to the nearest second. * @param n The number to round to the nearest thousand. * @return The rounded number. */ private long roundToNearestThousand(long n) { return (Math.round((double)n / 1000) * 1000); } /** * Decrement pause-resumes which are greater than the durationMinimum. * @param al The ArrayList of pause-resumes to modify. * @param durationMinimum We only modifiy entries with a value greater than this. * @param decrementLength How much to decrement the entries. */ private void decrementPauseResumes(ArrayList<Long> al, long durationMinimum, long decrementLength) { Iterator prdIt = al.iterator(); int index = 0; while (prdIt.hasNext()) { Long prDuration = (Long)prdIt.next(); if (prDuration > durationMinimum) al.set(index, prDuration - decrementLength); index++; } } /** * Call this when we find a 'resume' trackpoint the next trackpoint immeadiately following a 'pause' trackpoint. * We add the pause/resume details to the pauseResumeTImes ArrayList and return the length of time (in millis) that the * device was paused for. * <p> * Nike+ currently just use the same duration/distance to represent both the pause and the resume so I only store the pauseTime. * @param pauseResumeTimes The store of pause/resume times. If not provided then we don't store the times. * @param resumeTp The 'resume' trackpoint. * @param durationPaused The duration of the previous 'pause' trackpoint. * @return The length of time the device was paused for (so we can update decrement future trackpoint durations). */ private long addPauseResume(ArrayList<Long> pauseResumeTimes, Trackpoint resumeTp, long durationPaused) { long durationResume = resumeTp.getDuration(); long pauseLength = (durationResume- durationPaused); if (pauseResumeTimes != null) { pauseResumeTimes.add(durationPaused); log.out(Level.FINER, "Adding pause/resume.\tDuration %d\tDistance %.4f.\tlength %d", durationPaused, resumeTp.getDistance(), pauseLength); } return pauseLength; } /** * Generates the following CubicSplines: distanceToDuration, durationToDistance, durationToPace, durationToHeartRate. * @param trackpoints The Trackpoint data from which to build the CubicSplines. * @return A CubicSpline array in represnting the data listed in the description above. */ private CubicSpline[] generateCubicSplines(ArrayList<Trackpoint> trackpoints) { int tpsSize = trackpoints.size(); double[] durationsArray = new double[tpsSize]; double[] distancesArray = new double[tpsSize]; double[] pacesArray = new double[tpsSize]; double[] heartRatesArray = new double[tpsSize]; populateDurationsAndDistancesArrays(trackpoints, durationsArray, distancesArray, pacesArray, heartRatesArray); // Generate cubic splines for distance -> duration, duration -> distance & distance -> pace. // I'd have thought the flanagan classes would have offered some method of inverting the data, but I've not looked into it and this hack will do for now. CubicSpline distanceToDuration = new CubicSpline(distancesArray, durationsArray); CubicSpline durationToDistance = new CubicSpline(durationsArray, distancesArray); CubicSpline durationToPace = new CubicSpline(durationsArray, pacesArray); // Heartrate cubic spline CubicSpline durationToHeartRate = new CubicSpline(durationsArray, heartRatesArray); return new CubicSpline[] { distanceToDuration, durationToDistance, durationToPace, durationToHeartRate }; } private void appendSnapShotListAndExtendedData(Element sportsDataElement, ArrayList<Double> onDemandVPs, ArrayList<Long> pauseResumeTimes, CubicSpline distanceToDuration, CubicSpline durationToDistance, CubicSpline durationToPace, CubicSpline durationToHeartRate) { Element snapShotKmListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "kmSplit"); Element snapShotMileListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "mileSplit"); Element snapShotClickListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "userClick"); // Create a double array representing the on-demand-vp clicks - ignoring the final one as this is covered by the "stop" event. int odvpsCount = onDemandVPs.size() - 1; double[] odvps = new double[(odvpsCount >= 0) ? odvpsCount : 0]; Iterator<Double> odvpsIt = onDemandVPs.iterator(); int index = 0; while (odvpsIt.hasNext() && (index < odvpsCount)) odvps[index++] = odvpsIt.next(); // Pause/Resume splits. int odvpsIndex = 0; Iterator<Long> prIt = pauseResumeTimes.iterator(); while (prIt.hasNext()) { long pauseDuration = prIt.next(); double distance = interpolate(durationToDistance, pauseDuration); // Add all onDemandVP clicks leading up to this distance. while ((odvpsIndex < odvpsCount) && (odvps[odvpsIndex] <= distance)) { log.out(Level.FINE, "onDemandVP %d\tdistance: %f", odvpsIndex + 1, (odvpsIndex == 0) ? odvps[odvpsIndex] : odvps[odvpsIndex] - odvps[odvpsIndex-1]); double odvpDistance = odvps[odvpsIndex++]; long odvpDuration = (long)(interpolate(distanceToDuration, odvpDistance)); long odvpPace = (long)(interpolate(durationToPace, odvpDuration)); int odvpHeartRateBpm = (int)(interpolate(durationToHeartRate, odvpDuration)); appendSnapShot(snapShotClickListElement, odvpDuration, odvpDistance, odvpPace, odvpHeartRateBpm, "event", "onDemandVP"); } // Sometimes a pause/resume happens at the very end of a workout - if this is the case then we will not have decremented the // durations properly so just leave them out - there's no point in documeting a pause directly before the end of the workout anyway. if (pauseDuration < _totalDuration) { long pace = (long)(interpolate(durationToPace, pauseDuration)); int heartRateBpm = (int)(interpolate(durationToHeartRate, pauseDuration)); // 2009-12-01: Looking at various runs on nike+ it seems the each pause/resume pair now has the same duration/distance // (using the pause event). I can't find my nike+ stuff to check this is 100% accurate but will go with it for now. appendSnapShot(snapShotClickListElement, pauseDuration, distance, pace, heartRateBpm, "event", "pause"); appendSnapShot(snapShotClickListElement, pauseDuration, distance, pace, heartRateBpm, "event", "resume"); } } // Km splits for (int i = 1000; i <= _totalDistance; i += 1000) { double duration = (long)(interpolate(distanceToDuration, i)); appendSnapShot(snapShotKmListElement, (long)duration, i, (long)(interpolate(durationToPace, duration)), (int)(interpolate(durationToHeartRate, duration))); } // Mile splits for (double i = D_METRES_PER_MILE; i <= _totalDistance; i += D_METRES_PER_MILE) { double duration = (long)(interpolate(distanceToDuration, i)); appendSnapShot(snapShotMileListElement, (long)duration, i, (long)(interpolate(durationToPace, duration)), (int)(interpolate(durationToHeartRate, duration))); } // Stop split appendSnapShot(snapShotClickListElement, _totalDuration, _totalDistance, (long)(interpolate(durationToPace, _totalDuration)), (int)(interpolate(durationToHeartRate, _totalDuration)), "event", "stop"); // ExtendedDataLists appendExtendedDataList(sportsDataElement, durationToDistance, durationToPace, durationToHeartRate); } // Copy data from the trackpoint ArrayList into the durations & distances arrays in preparation for creating CubicSplines. private void populateDurationsAndDistancesArrays(ArrayList<Trackpoint> trackpoints, double[] durations, double[] distances, double[] paces, double[] heartRates) { Iterator<Trackpoint> tpsIt = trackpoints.iterator(); int i = 0; while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); if (_includeHeartRateData) heartRates[i] = tp.getHeartRate(); durations[i] = tp.getDuration(); distances[i] = tp.getDistance(); paces[i++] = tp.getPace(); } } /* <extendedDataList> <extendedData dataType="distance" intervalType="time" intervalUnit="s" intervalValue="10">0.0. 1.1, 2.3, 4.7, etc</extendedData> </extendedDataList> */ private void appendExtendedDataList(Element sportsDataElement, CubicSpline durationToDistance, CubicSpline durationToPace, CubicSpline durationToHeartRate) { int finalReading = (int)(durationToDistance.getXmax()); double previousDistance = 0; StringBuilder sbDistance = new StringBuilder("0.0"); StringBuilder sbSpeed = new StringBuilder("0.0"); StringBuilder sbHeartRate = new StringBuilder(); if (_includeHeartRateData) sbHeartRate.append((int)(interpolate(durationToHeartRate, 0d))); for (int i = 10000; i < finalReading; i = i + 10000) { // Distance double distance = (interpolate(durationToDistance, i))/1000; // 2010-06-18: Phillip Purcell emailed me two workouts on 2010-06-14 which did not draw graphs on nikeplus.com // A bit of debugging showed that some of the interpolated distances in these workouts were less than the // previous distance (impossible). Hacked this fix so that this will never happen. if (distance < previousDistance) distance = previousDistance; sbDistance.append(String.format(", %.6f", distance)); previousDistance = distance; // Speed sbSpeed.append(String.format(", %.6f", MILLIS_PER_HOUR/(interpolate(durationToPace, i)))); // Heart Rate if (_includeHeartRateData) sbHeartRate.append(String.format(", %d", (int)(interpolate(durationToHeartRate, i)))); } Element extendedDataListElement = Util.appendElement(sportsDataElement, "extendedDataList"); Util.appendElement(extendedDataListElement, "extendedData", sbDistance, "dataType", "distance", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); Util.appendElement(extendedDataListElement, "extendedData", sbSpeed, "dataType", "speed", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); if (_includeHeartRateData) Util.appendElement(extendedDataListElement, "extendedData", sbHeartRate, "dataType", "heartRate", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); } private void appendSnapShot(Element snapShotListElement, long durationMillis, double distanceMetres, long paceMillisKm, int heartRateBpm, String ... attributes) { Element snapShotElement = Util.appendElement(snapShotListElement, "snapShot", null, attributes); Util.appendElement(snapShotElement, "duration", durationMillis); Util.appendElement(snapShotElement, "distance", String.format("%.3f", distanceMetres/1000)); Util.appendElement(snapShotElement, "pace", paceMillisKm); if (_includeHeartRateData) Util.appendElement(snapShotElement, "bpm", heartRateBpm); } private double interpolate(CubicSpline spline, double x) { if (x < spline.getXmin()) x = spline.getXmin(); else if (x > spline.getXmax()) x = spline.getXmax(); return spline.interpolate(x); } public String generateFileName() { SimpleDateFormat outfileFormat = new SimpleDateFormat("yyyy-MM-dd HH;mm;ss'.xml'"); outfileFormat.setTimeZone(_workoutTimeZone); return outfileFormat.format(_calEnd.getTime()); } public String getStartTimeHumanReadable() { return _startTimeStringHuman; } private Trackpoint getLastTrackpointFromArrayList(ArrayList<Trackpoint> al) { return getTrackpointFromEndofArrayList(al, 0); } private Trackpoint getTrackpointFromEndofArrayList(ArrayList<Trackpoint> al, int placesFromEnd) { return ((al != null) && (al.size() > placesFromEnd)) ? al.get(al.size() - (placesFromEnd + 1)) : null; } public static void main(String[] args) { File inFile = new File(args[0]); String empedID = (args.length >= 2) ? args[1] : null; ConvertTcx c = new ConvertTcx(); try { Document doc = c.generateNikePlusXml(inFile, empedID); Util.writeDocument(doc, c.generateFileName()); } catch (Throwable t) { log.out(t); } } private class Trackpoint { private static final int PACE_MILLIS = 20 * 10000; // How many milli seconds of data to use when calculating pace. private Long _duration; private Double _distance; private Double _heartRate; private Trackpoint _previousTrackpoint; public Trackpoint(Trackpoint previousTrackpoint) { _previousTrackpoint = previousTrackpoint; } /** * A representatino of a garmin <trackpoint> element. * @param duration Current (relative to start of workout) duration in millis. * @param distance Current distance in metres. * @param heartRate Current heartrate in bpm. * @param previousTrackpoint The previously recorded trackpoint, or null if this is the first trackpoint. */ public Trackpoint(long duration, double distance, Double heartRate, Trackpoint previousTrackpoint) { _duration = duration; _distance = distance; _heartRate = heartRate; _previousTrackpoint = previousTrackpoint; } protected Long getDuration() { return _duration; } protected Double getDistance() { return _distance; } protected Double getHeartRate() { return _heartRate; } protected void setDuration(Long duration) { _duration = duration; } protected void setDistance(Double distance) { _distance = distance; } protected void setHeartRate(Double heartRate) { _heartRate = heartRate; } protected void setPreviousTrackpoint(Trackpoint previousTrackpoint) { _previousTrackpoint = previousTrackpoint; } /** * Nike+ uses the number of millis it takes to complete 1km as their pace figure. * @return Nike+ pace. */ protected long getPace() { // This can give skewed pace figures as we might have a trackpoint 2 seconds ago with slightly inaccurate distance resulting in wildly chaotic pace data. //Trackpoint previous = getPreviousDifferentTrackpoint(); // I use PACE_MILLIS previous seconds of data to calculate pace (avoiding the problem caused by getPreviousDifferntTrackpoint). long startDuration = (_duration > PACE_MILLIS) ? _duration - PACE_MILLIS : 0; Trackpoint startTp = getPreviousTrackpoint(); while ((startTp != null) && (startTp.getDuration() > startDuration)) startTp = startTp.getPreviousTrackpoint(); long splitDuration = (startTp == null) ? _duration : (_duration - startTp.getDuration()); double splitDistance = (startTp == null) ? _distance : (_distance - startTp.getDistance()); return (long)((1000d/splitDistance) * splitDuration); } protected Trackpoint getPreviousTrackpoint() { return _previousTrackpoint; } protected Double getMostRecentDistance() { Trackpoint tp = this; while ((tp != null)) { if (tp.getDistance() != null) return tp.getDistance(); tp = tp.getPreviousTrackpoint(); } return 0d; } protected long getDurationSinceLastTrackpoint() { return (_previousTrackpoint == null) ? 0 : (_duration - _previousTrackpoint.getDuration()); } protected boolean isRepeatDuration() { //return (_previousTrackpoint != null) && (_duration.equals(_previousTrackpoint.getDuration())); return (_previousTrackpoint != null) && ((_duration.compareTo(_previousTrackpoint.getDuration())) <= 0); } protected boolean isRepeatDistance() { //return (_previousTrackpoint != null) && (_distance.equals(_previousTrackpoint.getDistance())); return (_previousTrackpoint != null) && ((_distance.compareTo(_previousTrackpoint.getDistance())) <= 0); } protected Long getPreviousDuration() { return (_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDuration(); } protected Double getPreviousDistance() { return (_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDistance(); } protected void incrementDuration(long millis) { _duration += millis; } protected void decrementDuration(long millis) { _duration -= millis; } @Override public String toString() { return String.format("Duration (difference): %d\t(%d)\t\tDistance: %.4f", _duration, (_duration - ((_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDuration())), _distance); } } }
package com.awsmithson.tcx2nikeplus.convert; import com.awsmithson.tcx2nikeplus.util.Log; import com.awsmithson.tcx2nikeplus.util.Util; import flanagan.interpolation.CubicSpline; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone; import java.util.logging.Level; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ConvertTcx { private static final double D_METRES_PER_MILE = 1609.344; private static final double D_METRES_PER_MILE_GARMIN = 1609.35; // Garmin use this as their DistanceMeters for laps of length 1 mile. private static final int MILLIS_PER_HOUR = 60 * 1000 * 60; private static final String DATE_TIME_FORMAT_NIKE = "yyyy-MM-dd'T'HH:mm:ssZ"; private static final String DATE_TIME_FORMAT_HUMAN = "d MMM yyyy HH:mm:ss z"; // The minimum amount of millis between Trackpoints that I am prepared to create a potential pause/resume for. private static final int MILLIS_POTENTIAL_PAUSE_THRESHOLD = 0; private long _totalDuration; private double _totalDistance; private boolean _forceExcludeHeartRateData; private boolean _includeHeartRateData = false; private TimeZone _workoutTimeZone; private Calendar _calStart; private Calendar _calEnd; private String _startTimeString; private String _startTimeStringHuman; private static final Log log = Log.getInstance(); /** * Converts a garmin tcx file to a nike+ workout xml document. * <p> * This class is a hacky mess just now but it does the job. * @author angus */ public ConvertTcx() { } public Document generateNikePlusXml(File tcxFile, String empedID) throws Throwable { return generateNikePlusXml(tcxFile, empedID, false); } public Document generateNikePlusXml(File tcxFile, String empedID, boolean forceExcludeHeartRateData) throws Throwable { //try { _forceExcludeHeartRateData = forceExcludeHeartRateData; Document tcxDoc = Util.generateDocument(tcxFile); return generateNikePlusXml(tcxDoc, empedID); //catch (Exception e) { // log.out(e); // return null; } public Document generateNikePlusXml(Document inDoc, String empedID) throws Throwable { return generateNikePlusXml(inDoc, empedID, null); } public Document generateNikePlusXml(Document inDoc, String empedID, Integer clientTimeZoneOffset) throws Throwable { return generateNikePlusXml(inDoc, empedID, clientTimeZoneOffset, false); } public Document generateNikePlusXml(Document inDoc, String empedID, Integer clientTimeZoneOffset, boolean forceExcludeHeartRateData) throws Throwable { _forceExcludeHeartRateData = forceExcludeHeartRateData; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //try { // Create output document DocumentBuilder db = dbf.newDocumentBuilder(); Document outDoc = db.newDocument(); // Sports Data (root) Element sportsDataElement = Util.appendElement(outDoc, "sportsData"); // Vers //Util.appendElement(sportsDataElement, "vers", "8"); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Run Summary ArrayList<Double> onDemandVPDistances = new ArrayList<Double>(); Element runSummary = appendRunSummary(inDoc, sportsDataElement, clientTimeZoneOffset, onDemandVPDistances); // Template appendTemplate(sportsDataElement); // Goal Type appendGoalType(sportsDataElement); // User Info appendUserInfo(inDoc, sportsDataElement, empedID); // Start Time Util.appendElement(sportsDataElement, "startTime", _startTimeString); // Workout Detail appendWorkoutDetail(inDoc, sportsDataElement, runSummary, onDemandVPDistances); // Test lap durations //testLapDuration(inDoc); //printDocument(outDoc); //writeDocument(outDoc); //return new String[] { generateString(outDoc), generateFileName() }; return outDoc; //catch (Exception e) { // log.out(e); // return null; } /** * Generates a run summary xml element like: * <pre> * {@code * <runSummary> * <workoutName><![CDATA[Basic]]></workoutName> * <time>2009-06-12T10:00:00-10:00</time> * <duration>1760000</duration> * <durationString>29:20</durationString> * <distance unit="km">6.47</distance> * <distanceString>6.47 km</distanceString> * <pace>4:32 min/km</pace> * <calories>505</calories> * <battery></battery> * <stepCounts> * <walkBegin>0</walkBegin> * <walkEnd>0</walkEnd> * <runBegin>0</runBegin> * <runEnd>0</runEnd> * </stepCounts> * </runSummary> * } * </pre> * @param inDoc The garmin tcx document we are reading the data from. * @param sportsDataElement An xml element we have already created "sportsDataElement" * @param clientTimeZoneOffset The client timezone offset to use in the event we are unable to determine workout timezone from the gps coordinates. * @return The runSummary xml element. * @throws DatatypeConfigurationException * @throws IOException * @throws MalformedURLException * @throws ParserConfigurationException * @throws SAXException */ private Element appendRunSummary(Document inDoc, Element sportsDataElement, Integer clientTimeZoneOffset, ArrayList<Double> onDemandVPDistances) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { Element runSummaryElement = Util.appendElement(sportsDataElement, "runSummary"); // Workout Name //Util.appendCDATASection(runSummaryElement, "workoutName", "Basic"); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Start Time appendStartTime(inDoc, runSummaryElement, clientTimeZoneOffset); // Duration, Duration, Pace & Calories appendTotals(inDoc, runSummaryElement, onDemandVPDistances); // Battery Util.appendElement(runSummaryElement, "battery"); // Step Counts //appendStepCounts(runSummaryElement); // 2010-09-13: I've noticed this is not included in the iphone xml output. return runSummaryElement; } private void appendStartTime(Document inDoc, Element runSummaryElement, Integer clientTimeZoneOffset) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { // Garmin: 2009-06-03T16:59:27.000Z // Nike: 2009-06-03T17:59:27+01:00 // Get the timezone based on the Latitude, Longitude & Time (UTC) of the first TrackPoint _workoutTimeZone = getWorkoutTimeZone(inDoc, clientTimeZoneOffset); if (_workoutTimeZone == null) _workoutTimeZone = TimeZone.getTimeZone("Etc/UTC"); log.out("Time zone millis offset (vs server): %d", _workoutTimeZone.getRawOffset()); // Set the the SimpleDateFormat object so that it prints the time correctly: // local-time + UTC-difference. SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT_NIKE); df.setTimeZone(_workoutTimeZone); // Get the workout start-time, format for nike+ and add it to the out-document Calendar calStart = Util.getCalendarValue(Util.getSimpleNodeValue(inDoc, "Id")); Date dateStart = calStart.getTime(); _startTimeString = df.format(dateStart); _startTimeString = String.format("%s:%s", _startTimeString.substring(0, 22), _startTimeString.substring(22)); Util.appendElement(runSummaryElement, "time", _startTimeString); // Generate a human readable start-string we can use for debugging. df.applyPattern(DATE_TIME_FORMAT_HUMAN); _startTimeStringHuman = df.format(dateStart); // We need these later. _calStart = calStart; } // deduce in which time zone the workout began. private TimeZone getWorkoutTimeZone(Document inDoc, Integer clientTimeZoneOffset) throws DatatypeConfigurationException, IOException, MalformedURLException, ParserConfigurationException, SAXException { NodeList positions = inDoc.getElementsByTagName("Position"); int positionsLength = positions.getLength(); // Loop through the Position data, we will return as soon as we find one // with the required data (latitude & longitude). for (int i = 0; i < positionsLength; ++i) { Double latitude = null; Double longitude = null; for (Node n = positions.item(i).getFirstChild(); n != null; n = n.getNextSibling()) { String nodeName = n.getNodeName(); // Latitude at this point if (nodeName.equals("LatitudeDegrees")) { latitude = Double.parseDouble(Util.getSimpleNodeValue(n)); } // Longitude at this point else if (nodeName.equals("LongitudeDegrees")) { longitude = Double.parseDouble(Util.getSimpleNodeValue(n)); } if ((latitude != null) && (longitude != null)) { // Send a post to the geonames.org webservice with the lat & lng parameters. String url = "http://ws.geonames.org/timezone"; String parameters = String.format("lat=%s&lng=%s", latitude, longitude); log.out("Looking up time zone for lat/lon: %.4f / %.4f", latitude, longitude); try { Document response = Util.downloadFile(url, parameters); String timeZoneId = Util.getSimpleNodeValue(response, "timezoneId"); log.out(" - %s", timeZoneId); return TimeZone.getTimeZone(timeZoneId); } catch (Throwable t) { // If, for whatever reason we are unable to get the timezone and we have a clientTimeZoneOffset then use that. if (clientTimeZoneOffset != null) { int hours = clientTimeZoneOffset / 60; int minutes = Math.abs(clientTimeZoneOffset) % 60; String mm = String.format(((minutes < 10) ? "0%d" : "%d"), minutes); String tz = String.format("GMT%s%d:%s", (hours < 0) ? "" : "+", hours, mm); log.out("Unable to retrieve workout timezone from http://ws.geonames.org, attempting to use client-timezone %s instead.", tz); return TimeZone.getTimeZone(tz); } else { TimeZone tz = TimeZone.getDefault(); log.out(Level.WARNING, "Unable to retrieve workout timezone (http://ws.geonames.org is not available right now). Using default timezone: %s", tz.getID()); return tz; } } } } } return null; } private void appendTotals(Document inDoc, Node parent, ArrayList<Double> onDemandVPDistances) { double totalSeconds = 0d; double totalDistance = 0d; int totalCalories = 0; NodeList laps = inDoc.getElementsByTagName("Lap"); int lapsLength = laps.getLength(); for (int i = 0; i < lapsLength; ++i) { for (Node n = laps.item(i).getFirstChild(); n != null; n = n.getNextSibling()) { String nodeName = n.getNodeName(); if (nodeName.equals("TotalTimeSeconds")) totalSeconds += Double.parseDouble(Util.getSimpleNodeValue(n)); else if (nodeName.equals("DistanceMeters")) { totalDistance += Double.parseDouble(Util.getSimpleNodeValue(n)); // If the end of the lap does not fall on a km/mile distance then store for inserting as a "onDemandVP" click later. if (((totalDistance % 1000) != 0) && (totalDistance % D_METRES_PER_MILE_GARMIN) != 0) onDemandVPDistances.add(totalDistance); } else if (nodeName.equals("Calories")) totalCalories += Integer.parseInt(Util.getSimpleNodeValue(n)); } } long totalDuration = (long)(totalSeconds * 1000); _totalDuration = totalDuration; _totalDistance = totalDistance; // Calculate the end-time of the run (for use late to generate the xml filename). _calEnd = (Calendar)(_calStart.clone()); _calEnd.add(Calendar.MILLISECOND, (int)totalDuration); // Total Duration Util.appendElement(parent, "duration", totalDuration); //Util.appendElement(parent, "durationString", getTimeStringFromMillis(totalDuration)); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Total Distance //totalDistance = totalDistance.divide(BD_1000); totalDistance /= 1000; Util.appendElement(parent, "distance", String.format("%.4f", totalDistance), "unit", "km"); //Util.appendElement(parent, "distanceString", String.format("%.2f km", totalDistance)); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Pace //Util.appendElement(parent, "pace", String.format("%s min/km", getTimeStringFromMillis(calculatePace(totalDuration, totalDistance)))); // 2010-09-13: I've noticed this is not included in the iphone xml output. // Calories - FIXME - calories are not calculated properly yet... Util.appendElement(parent, "calories", totalCalories); } /* // 2010-09-13: I've noticed this is not included in the iphone xml output. private void appendStepCounts(Node parent) { Element stepCountsElement = Util.appendElement(parent, "stepCounts"); Util.appendElement(stepCountsElement, "walkBegin", "0"); Util.appendElement(stepCountsElement, "walkEnd", "0"); Util.appendElement(stepCountsElement, "runBegin", "0"); Util.appendElement(stepCountsElement, "runEnd", "0"); } */ /* <template><templateID>8D495DCE</templateID> <templateName><![CDATA[Basic]]></templateName> </template> */ private void appendTemplate(Element sportsDataElement) { Element templateElement = Util.appendElement(sportsDataElement, "template"); //Util.appendElement(templateElement, "templateID", "8D495DCE"); // 2010-09-13: I've noticed this is not included in the iphone xml output. Util.appendCDATASection(templateElement, "templateName", "Basic"); } // <goal type="" value="" unit=""></goal> private void appendGoalType(Element sportsDataElement) { Util.appendElement(sportsDataElement, "goal", null, "type", "", "value", "", "unit", ""); } /* <userInfo> <empedID>XXXXXXXXXXX</empedID> <weight></weight> <device>iPod</device> <calibration></calibration> </userInfo> */ private void appendUserInfo(Document inDoc, Element sportsDataElement, String empedID) { Element templateElement = Util.appendElement(sportsDataElement, "userInfo"); Util.appendElement(templateElement, "empedID", (empedID == null) ? "XXXXXXXXXXX" : empedID); Util.appendElement(templateElement, "weight"); // Upload goes through fine when "Garmin Forerunner 405 is specified as device but on nikeplus.com website some data shows as "invalid" //Util.appendElement(templateElement, "device", getSimpleNodeValue(inDoc, "Name")); // Garmin Forerunner 405 Util.appendElement(templateElement, "device", "iPod"); // iPod Util.appendElement(templateElement, "calibration"); } private void appendWorkoutDetail(Document inDoc, Element sportsDataElement, Element runSummaryElement, ArrayList<Double> onDemandVPDistances) throws DatatypeConfigurationException { // Generate the workout detail from the garmin Trackpoint data. ArrayList<Trackpoint> trackpoints = new ArrayList<Trackpoint>(); ArrayList<Long> pauseResumeTimes = new ArrayList<Long>(); generateCubicSplineData(inDoc, trackpoints, pauseResumeTimes); // Generates the following CubicSplines: distanceToDuration, durationToDistance, durationToPace, durationToHeartRate. CubicSpline[] splines = generateCubicSplines(trackpoints); appendSnapShotListAndExtendedData(sportsDataElement, onDemandVPDistances, pauseResumeTimes, splines[0], splines[1], splines[2], splines[3]); // Append heart rate detail to the run summary if required. if (_includeHeartRateData) { Trackpoint min = null; Trackpoint max = null; int average = 0; for (Trackpoint tp : trackpoints) { int heartRate = tp.getHeartRate().intValue(); if ((min == null) || (heartRate < min.getHeartRate())) min = tp; if ((max == null) || (heartRate > max.getHeartRate())) max = tp; average += (heartRate * tp.getDurationSinceLastTrackpoint()); } average /= _totalDuration; Element heartRateElement = Util.appendElement(runSummaryElement, "heartRate"); Util.appendElement(heartRateElement, "average", average); appendHeartRateSummary(heartRateElement, "minimum", min); appendHeartRateSummary(heartRateElement, "maximum", max); //Util.appendElement(heartRateElement, "battery", 3); // 2010-09-13: I've noticed this is not included in the iphone xml output. } } private void appendHeartRateSummary(Element heartRateElement, String type, Trackpoint tp) { Element heartRateTypeElement = Util.appendElement(heartRateElement, type); Util.appendElement(heartRateTypeElement, "duration", tp.getDuration()); Util.appendElement(heartRateTypeElement, "distance", String.format("%.3f", tp.getDistance()/1000)); Util.appendElement(heartRateTypeElement, "pace", tp.getPace()); Util.appendElement(heartRateTypeElement, "bpm", tp.getHeartRate().intValue()); } private void generateCubicSplineData(Document inDoc, ArrayList<Trackpoint> trackpointsStore, ArrayList<Long> pauseResumeTimes) throws DatatypeConfigurationException { // Create a trackpoint based on the very start of the run. Trackpoint previousTp = new Trackpoint(0l, 0d, 0d, null); trackpointsStore.add(previousTp); NodeList laps = inDoc.getElementsByTagName("Lap"); int lapsLength = laps.getLength(); long lapStartDuration = 0; for (int i = 0; i < lapsLength; ++i) { Node lap = laps.item(i); long lapStartTime = Util.getCalendarNodeValue(lap.getAttributes().getNamedItem("StartTime")).getTimeInMillis(); long lapDuration = (long)(Double.parseDouble(Util.getSimpleNodeValue(Util.getFirstChildByNodeName(lap, "TotalTimeSeconds"))) * 1000); log.out(Level.FINE, "Start of lap %d\tDuration: %d -> %d.", (i + 1), lapStartDuration, (lapStartDuration + lapDuration)); ArrayList<Trackpoint> lapTrackpointStore = generateLapCubicSplineData(lap, pauseResumeTimes, getLastTrackpointFromArrayList(trackpointsStore), lapStartTime, lapStartDuration, lapDuration); trackpointsStore.addAll(lapTrackpointStore); lapStartDuration += lapDuration; log.out(Level.FINE, ("End of lap.\n")); } // Remove strange trackpoints (repeat distance/durations). // Also, for each trackpoint, add a heart-rate reading if one is required & update the previous-trackpoints reference. previousTp = null; Iterator<Trackpoint> tpsIt = trackpointsStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); tp.setPreviousTrackpoint(previousTp); if ((tp.getDistance() == null) || (tp.isRepeatDistance())) { log.out(Level.FINE, "Removing invalid distance trackpoint:\t%s", tp); tpsIt.remove(); } else if ((tp.getDuration() == null) || (tp.isRepeatDuration())) { log.out(Level.FINE, "Removing invalid duration trackpoint:\t%s", tp); tpsIt.remove(); } else { if ((_includeHeartRateData) && (tp.getHeartRate() == null)) tp.setHeartRate(previousTp.getHeartRate()); previousTp = tp; log.out(Level.FINER, "Duration: %d\tDistance: %.4f", tp.getDuration(), tp.getDistance()); } } //log.out(Level.FINER, "Workout total duration: %d", _totalDuration); Trackpoint penultimateTp = getTrackpointFromEndofArrayList(trackpointsStore, 1); if (penultimateTp != null) { long pDur = penultimateTp.getDuration(); double pDist = penultimateTp.getDistance(); log.out("Trackpoint reading complete..."); log.out("Penultimate vs Required: Duration (secs): %d -> %d (%d). Distance (m): %.0f -> %.0f (%.0f)", pDur/1000, _totalDuration/1000, ((_totalDuration - pDur)/1000), pDist, _totalDistance, (_totalDistance - pDist)); } } private ArrayList<Trackpoint> generateLapCubicSplineData(Node lap, ArrayList<Long> pauseResumeTimes, Trackpoint previousTp, long lapStartTime, long lapStartDuration, long lapDuration) throws DatatypeConfigurationException { ArrayList<Trackpoint> lapTrackpointStore = new ArrayList<Trackpoint>(); // Add the last trackpoint of the previous lap so we can calculate pause/resumes that span across laps. // We will remove the first trackpoint (this one) from the store after validating the lap data. lapTrackpointStore.add(previousTp); long lapEndDuration = lapStartDuration + lapDuration; double lapDistance = Double.parseDouble(Util.getSimpleNodeValue(Util.getFirstChildByNodeName(lap, "DistanceMeters"))); Double lapEndDistance = null; // Get the trackpoints for this lap - if there are none then continue to the next lap. Node[] tracks = Util.getChildrenByNodeName(lap, "Track"); if (tracks != null) { for (Node track : tracks) { // Get the trackpoints for this track - if there are none then continue to the next track. Node[] trackpoints = Util.getChildrenByNodeName(track, "Trackpoint"); if (trackpoints == null) continue; for (Node trackpoint : trackpoints) { // Loop through the data for this trackpoint storing the data. Trackpoint tp = new Trackpoint(previousTp); int trackPointDataLength = 0; for (Node n = trackpoint.getFirstChild(); n != null; n = n.getNextSibling(), ++trackPointDataLength) { String nodeName = n.getNodeName(); // Run duration to this point if (nodeName.equals("Time")) tp.setDuration((Util.getCalendarNodeValue(n).getTimeInMillis() - lapStartTime) + lapStartDuration); // Distance to this point else if (nodeName.equals("DistanceMeters")) { double distance = Double.parseDouble(Util.getSimpleNodeValue(n)); // If this is the first trackpoint in the lap with a DistanceMeters value then calculate the start/end distance of the lap. if (lapEndDistance == null) lapEndDistance = distance + lapDistance; tp.setDistance(distance); } // Heart rate bpm else if ((!_forceExcludeHeartRateData) && (nodeName.equals("HeartRateBpm"))) { NodeList heartRateData = n.getChildNodes(); int heartRateDataLength = heartRateData.getLength(); for (int j = 0; j < heartRateDataLength; ++j) { Node heartRateNode = heartRateData.item(j); if (heartRateNode.getNodeName().equals("Value")) { _includeHeartRateData = true; tp.setHeartRate(Double.parseDouble(Util.getSimpleNodeValue(heartRateNode))); } } } } // Store the trackpoint for validation/conversion later. if ((tp != null) && ((tp.getDistance() != null) || (trackPointDataLength == 3))) { lapTrackpointStore.add(tp); previousTp = tp; log.out(Level.FINEST, "New raw tcx-file Trackpoint, durations: %d -> %d = %d. distance: %.4f.", tp.getPreviousDuration(), tp.getDuration(), tp.getDuration() - tp.getPreviousDuration(), tp.getDistance()); } } } } // Add a Trackpoint for the end of the lap if we haven't already got one at that distance/duration. Trackpoint lastTp = getLastTrackpointFromArrayList(lapTrackpointStore); if ((lapEndDistance != null) && ((lastTp.getMostRecentDistance() < lapEndDistance) && (lastTp.getDuration() < lapEndDuration))) lapTrackpointStore.add(new Trackpoint(lapEndDuration, lapEndDistance, previousTp.getHeartRate(), lastTp)); validateLapCubicSplineData(lap, lapTrackpointStore, pauseResumeTimes, lapEndDuration); lapTrackpointStore.remove(0); // Remove the final trackpoint from the previous lap which was added for the purpose of pause/resumes that span across laps. long difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); log.out(Level.FINE, "Lap duration difference after validation:\t%d", difference); return lapTrackpointStore; } private void validateLapCubicSplineData(Node lap, ArrayList<Trackpoint> lapTrackpointStore, ArrayList<Long> pauseResumeDurations, long lapEndDuration) { // If we only have one trackpoint (the final trackpoint from the previous lap) then we don't need to validate. if (lapTrackpointStore.size() == 1) return; Node lapTotalTimeSeconds = Util.getFirstChildByNodeName(lap, "TotalTimeSeconds"); if (lapTotalTimeSeconds == null) return; long difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); log.out(Level.FINE, "Lap duration difference before validation:\t%d", difference); boolean paused = false; long durationPaused = 0; long lengthDecrement = 0; Trackpoint previousTp = null; // For pause/resmumes // - 1. Get the duration of the pause trackpoint to use for the pause/resume duration. // - 2. Remove the pause trackpoint. Our cublic splies will work out what the actual distance was up until this point. // - 3. The next trackpoint (or end of lap) will be the resume Trackpoint. // - 4. Use the duration data of this resume Trackpoint to calculate the length we were paused for. // - 5. Deduct the pause-length from all proceeding durations in the lap. Iterator<Trackpoint> tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); tp.decrementDuration(lengthDecrement); // Deal with 3-data pause/resume trackpoints. // If we are not paused already then this is a 'pause' trackpoint: // - 1. Record the duration. // - 2. Set paused=true. // - 3. Remove the trackpoint. // - 4. Loop again (get the next trackpoint). // If we are paused then this is a 'resume' trackpoint: // - 1. Store the pause/resume details, adding the length paused to the lengthDecrement variable. // - 2. Set paused=false // - 3. Remove the trackpoint. // - 4. Loop again (get the next trackpoint). if (tp.getDistance() == null) { if (!paused) durationPaused = tp.getDuration(); else lengthDecrement += addPauseResume(pauseResumeDurations, tp, durationPaused); paused = !paused; tpsIt.remove(); continue; } // Deal with normal trackpoints. // If we are paused then this is a 'resume' trackpoint: // - 1. Store the pause/resume details // - 2. Add the length paused to the lengthDecrement variable. // - 3. Decrement the current trackpoint with the amount we were paused for. // - 4. Set paused = false. if (paused) { long lengthPaused = addPauseResume(pauseResumeDurations, tp, durationPaused); lengthDecrement += lengthPaused; tp.decrementDuration(lengthPaused); paused = false; } tp.setPreviousTrackpoint(previousTp); previousTp = tp; } // After applying the tcx-detailed pause/resumes we still might have trackpoints whose durations exceed // the lap time. I think the primary reason for this is that garmin automatically pauses the device if it is // unable to get a satellite waypoint after a certain amount of seconds (seems to be 8 seconds on the 405 with // 2.50 firmware). To counter this I will basically strip away the slowest-paced (hopefully paused) sections of the // lap until our final trackpoint has a less than or equal to that of the lap duration. difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration); // We allow up to 999 millis as due to rounding errors the lap-duration can be up to 1 second out. if (difference > 0) { log.out("Lap duration still invalid by %d millis, manually stripping.", difference); boolean modified = true; do { modified = false; double paceWorst = Double.MAX_VALUE; Trackpoint paceWorstTp = null; tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); // If our previous trackpoint is null then this is the first trackpoint so continue to the next trackpoint. if (tp.getPreviousTrackpoint() == null) continue; long duration = tp.getDuration(); long durationPrevious = tp.getPreviousDuration(); double distance = tp.getDistance(); double distancePrevious = tp.getPreviousDistance(); // Calculate distance & duration differences. double distanceIncrease = distance - distancePrevious; long durationIncrease = duration - tp.getPreviousDuration(); // if we have a distance increase of zero then remove the trackpoint and decrement all future trackpoints/pause-resumes by the duration we didn't increase for. if ((distanceIncrease == 0) && (durationIncrease > 0)) { long decrementLength = (difference > durationIncrease) ? durationIncrease : difference; log.out(Level.FINE, "Zero-distance decrement:\tDuration %d\tDistance %.4f\tLength: %d", durationPrevious, distancePrevious, decrementLength); tpsIt.remove(); if (tpsIt.hasNext()) { Trackpoint nextTp = tpsIt.next(); nextTp.decrementDuration(decrementLength); nextTp.setPreviousTrackpoint(previousTp); } while (tpsIt.hasNext()) tpsIt.next().decrementDuration(decrementLength); decrementPauseResumes(pauseResumeDurations, durationPrevious, decrementLength); modified = true; break; } double pace = (durationIncrease > MILLIS_POTENTIAL_PAUSE_THRESHOLD) ? (distanceIncrease / durationIncrease) : Double.MAX_VALUE; if (pace < paceWorst) { paceWorst = pace; paceWorstTp = tp; } } // If we haven't found any zero-distance trackpiont increases then decrement all future trackpoints/pause-resumes from the slowest pace trackpoint pair of the lap. if ((paceWorstTp != null) && !(modified)) { log.out(Level.FINE, "Slowest-pace decrement:\tDuration %d\tDistance %.4f", paceWorstTp.getPreviousDuration(), paceWorstTp.getPreviousDistance()); modified = true; tpsIt = lapTrackpointStore.iterator(); while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); if (tp.equals(paceWorstTp)) { tp.decrementDuration(1000); while (tpsIt.hasNext()) tpsIt.next().decrementDuration(1000); decrementPauseResumes(pauseResumeDurations, tp.getDuration(), 1000); } } } } while ((modified) && ((difference = lapTrackpointDurationVsLapEndDuration(lapTrackpointStore, lapEndDuration)) > 0)); } } /** * Get the difference (in millis) between the duration of the final trackpoint in the trackpoint-store and the expected lap-end-duration. * @param lapTrackpointStore An ArrayList of trackpoints for the lap - the last element in this collection should have duration less than lapEndDuration. * @param lapEndDuration The expected duration at the end of the lap. * @return The difference (positive if the trackpoint store exceeds the expected lap-end-duration). */ private long lapTrackpointDurationVsLapEndDuration(ArrayList<Trackpoint> lapTrackpointStore, long lapEndDuration) { return (lapTrackpointStore.size() == 0) ? 0 : roundToNearestThousand(getLastTrackpointFromArrayList(lapTrackpointStore).getDuration()) - roundToNearestThousand(lapEndDuration) ; } /** * Use this to round lap durations. The duration specified in the <code>&lt;Lap&gt;</code> element is to the nearest * millisecond whereas the data in the <code>&lt;Trackpoint&gt;</code> elements is to the nearest second. * @param n The number to round to the nearest thousand. * @return The rounded number. */ private long roundToNearestThousand(long n) { return (Math.round((double)n / 1000) * 1000); } /** * Decrement pause-resumes which are greater than the durationMinimum. * @param al The ArrayList of pause-resumes to modify. * @param durationMinimum We only modifiy entries with a value greater than this. * @param decrementLength How much to decrement the entries. */ private void decrementPauseResumes(ArrayList<Long> al, long durationMinimum, long decrementLength) { Iterator prdIt = al.iterator(); int index = 0; while (prdIt.hasNext()) { Long prDuration = (Long)prdIt.next(); if (prDuration > durationMinimum) al.set(index, prDuration - decrementLength); index++; } } /** * Call this when we find a 'resume' trackpoint the next trackpoint immeadiately following a 'pause' trackpoint. * We add the pause/resume details to the pauseResumeTImes ArrayList and return the length of time (in millis) that the * device was paused for. * <p> * Nike+ currently just use the same duration/distance to represent both the pause and the resume so I only store the pauseTime. * @param pauseResumeTimes The store of pause/resume times. If not provided then we don't store the times. * @param resumeTp The 'resume' trackpoint. * @param durationPaused The duration of the previous 'pause' trackpoint. * @return The length of time the device was paused for (so we can update decrement future trackpoint durations). */ private long addPauseResume(ArrayList<Long> pauseResumeTimes, Trackpoint resumeTp, long durationPaused) { long durationResume = resumeTp.getDuration(); long pauseLength = (durationResume- durationPaused); if (pauseResumeTimes != null) { pauseResumeTimes.add(durationPaused); log.out(Level.FINER, "Adding pause/resume.\tDuration %d\tDistance %.4f.\tlength %d", durationPaused, resumeTp.getDistance(), pauseLength); } return pauseLength; } /** * Generates the following CubicSplines: distanceToDuration, durationToDistance, durationToPace, durationToHeartRate. * @param trackpoints The Trackpoint data from which to build the CubicSplines. * @return A CubicSpline array in represnting the data listed in the description above. */ private CubicSpline[] generateCubicSplines(ArrayList<Trackpoint> trackpoints) { int tpsSize = trackpoints.size(); double[] durationsArray = new double[tpsSize]; double[] distancesArray = new double[tpsSize]; double[] pacesArray = new double[tpsSize]; double[] heartRatesArray = new double[tpsSize]; populateDurationsAndDistancesArrays(trackpoints, durationsArray, distancesArray, pacesArray, heartRatesArray); // Generate cubic splines for distance -> duration, duration -> distance & distance -> pace. // I'd have thought the flanagan classes would have offered some method of inverting the data, but I've not looked into it and this hack will do for now. CubicSpline distanceToDuration = new CubicSpline(distancesArray, durationsArray); CubicSpline durationToDistance = new CubicSpline(durationsArray, distancesArray); CubicSpline durationToPace = new CubicSpline(durationsArray, pacesArray); // Heartrate cubic spline CubicSpline durationToHeartRate = new CubicSpline(durationsArray, heartRatesArray); return new CubicSpline[] { distanceToDuration, durationToDistance, durationToPace, durationToHeartRate }; } private void appendSnapShotListAndExtendedData(Element sportsDataElement, ArrayList<Double> onDemandVPDistances, ArrayList<Long> pauseResumeTimes, CubicSpline distanceToDuration, CubicSpline durationToDistance, CubicSpline durationToPace, CubicSpline durationToHeartRate) { Element snapShotKmListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "kmSplit"); Element snapShotMileListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "mileSplit"); Element snapShotClickListElement = Util.appendElement(sportsDataElement, "snapShotList", null, "snapShotType", "userClick"); // Create a double array representing the on-demand-vp clicks - ignoring the final one as this is covered by the "stop" event. int odvpsCount = onDemandVPDistances.size() - 1; double[] odvps = new double[(odvpsCount >= 0) ? odvpsCount : 0]; Iterator<Double> odvpsIt = onDemandVPDistances.iterator(); int index = 0; while (odvpsIt.hasNext() && (index < odvpsCount)) odvps[index++] = odvpsIt.next(); // Pause/Resume splits. int odvpsIndex = 0; Iterator<Long> prIt = pauseResumeTimes.iterator(); while (prIt.hasNext()) { long pauseDuration = prIt.next(); double distance = interpolate(durationToDistance, pauseDuration); // Add all onDemandVP clicks leading up to this pause/resume. odvpsIndex = addOnDemandVPClicks(snapShotClickListElement, odvps, odvpsIndex, distance, distanceToDuration, durationToPace, durationToHeartRate); // Sometimes a pause/resume happens at the very end of a workout - if this is the case then we will not have decremented the // durations properly so just leave them out - there's no point in documeting a pause directly before the end of the workout anyway. if (pauseDuration < _totalDuration) { long pace = (long)(interpolate(durationToPace, pauseDuration)); int heartRateBpm = (int)(interpolate(durationToHeartRate, pauseDuration)); // 2009-12-01: Looking at various runs on nike+ it seems the each pause/resume pair now has the same duration/distance // (using the pause event). I can't find my nike+ stuff to check this is 100% accurate but will go with it for now. appendSnapShot(snapShotClickListElement, pauseDuration, distance, pace, heartRateBpm, "event", "pause"); appendSnapShot(snapShotClickListElement, pauseDuration, distance, pace, heartRateBpm, "event", "resume"); } } // Add all remaining onDemandVP clicks leading up to the stop click. addOnDemandVPClicks(snapShotClickListElement, odvps, odvpsIndex, _totalDistance, distanceToDuration, durationToPace, durationToHeartRate); // Km splits for (int i = 1000; i <= _totalDistance; i += 1000) { double duration = (long)(interpolate(distanceToDuration, i)); appendSnapShot(snapShotKmListElement, (long)duration, i, (long)(interpolate(durationToPace, duration)), (int)(interpolate(durationToHeartRate, duration))); } // Mile splits for (double i = D_METRES_PER_MILE; i <= _totalDistance; i += D_METRES_PER_MILE) { double duration = (long)(interpolate(distanceToDuration, i)); appendSnapShot(snapShotMileListElement, (long)duration, i, (long)(interpolate(durationToPace, duration)), (int)(interpolate(durationToHeartRate, duration))); } // Stop split appendSnapShot(snapShotClickListElement, _totalDuration, _totalDistance, (long)(interpolate(durationToPace, _totalDuration)), (int)(interpolate(durationToHeartRate, _totalDuration)), "event", "stop"); // ExtendedDataLists appendExtendedDataList(sportsDataElement, durationToDistance, durationToPace, durationToHeartRate); } /** * Adds onDemandVP elements from the odvps array to the snapShotClickList only when their index in the array >= odvpsIndex and their value < distanceLimit. * <br /> It incrememnts the odvpsIndex amount for each onDemandVP element it adds. * <br />Once it has completed (0...n iterations) it returns the updated odvpsIndex value. * @param snapShotClickListElement The element to add the onDemandVP elements to. * @param odvps An array of distances representing all the onDemandVP elements we need to create for this workout. * @param odvpsIndex We ignore all cells in the odvps array before this index (it's likely onDeamndVP elements for them have already been created). * @param distanceLimit We stop iterating when we find an odvps cell >= this amount. * @param distanceToDuration Cubicspline for converting distances to duration. * @param durationToPace Cubicspline for converting duraiton to pace. * @param durationToHeartRate Cubicspline for converting duration to heart rate. * @return Updated odvpsIndex value. */ private int addOnDemandVPClicks(Element snapShotClickListElement, double[] odvps, int odvpsIndex, double distanceLimit, CubicSpline distanceToDuration, CubicSpline durationToPace, CubicSpline durationToHeartRate) { while ((odvpsIndex < odvps.length) && (odvps[odvpsIndex] <= distanceLimit)) { log.out(Level.FINE, "onDemandVP %d\tdistance-since-previous: %f", odvpsIndex + 1, (odvpsIndex == 0) ? odvps[odvpsIndex] : odvps[odvpsIndex] - odvps[odvpsIndex-1]); double odvpDistance = odvps[odvpsIndex++]; long odvpDuration = (long)(interpolate(distanceToDuration, odvpDistance)); long odvpPace = (long)(interpolate(durationToPace, odvpDuration)); int odvpHeartRateBpm = (int)(interpolate(durationToHeartRate, odvpDuration)); appendSnapShot(snapShotClickListElement, odvpDuration, odvpDistance, odvpPace, odvpHeartRateBpm, "event", "onDemandVP"); } return odvpsIndex; } // Copy data from the trackpoint ArrayList into the durations & distances arrays in preparation for creating CubicSplines. private void populateDurationsAndDistancesArrays(ArrayList<Trackpoint> trackpoints, double[] durations, double[] distances, double[] paces, double[] heartRates) { Iterator<Trackpoint> tpsIt = trackpoints.iterator(); int i = 0; while (tpsIt.hasNext()) { Trackpoint tp = tpsIt.next(); if (_includeHeartRateData) heartRates[i] = tp.getHeartRate(); durations[i] = tp.getDuration(); distances[i] = tp.getDistance(); paces[i++] = tp.getPace(); } } /* <extendedDataList> <extendedData dataType="distance" intervalType="time" intervalUnit="s" intervalValue="10">0.0. 1.1, 2.3, 4.7, etc</extendedData> </extendedDataList> */ private void appendExtendedDataList(Element sportsDataElement, CubicSpline durationToDistance, CubicSpline durationToPace, CubicSpline durationToHeartRate) { int finalReading = (int)(durationToDistance.getXmax()); double previousDistance = 0; StringBuilder sbDistance = new StringBuilder("0.0"); StringBuilder sbSpeed = new StringBuilder("0.0"); StringBuilder sbHeartRate = new StringBuilder(); if (_includeHeartRateData) sbHeartRate.append((int)(interpolate(durationToHeartRate, 0d))); for (int i = 10000; i < finalReading; i = i + 10000) { // Distance double distance = (interpolate(durationToDistance, i))/1000; // 2010-06-18: Phillip Purcell emailed me two workouts on 2010-06-14 which did not draw graphs on nikeplus.com // A bit of debugging showed that some of the interpolated distances in these workouts were less than the // previous distance (impossible). Hacked this fix so that this will never happen. if (distance < previousDistance) distance = previousDistance; sbDistance.append(String.format(", %.6f", distance)); previousDistance = distance; // Speed sbSpeed.append(String.format(", %.6f", MILLIS_PER_HOUR/(interpolate(durationToPace, i)))); // Heart Rate if (_includeHeartRateData) sbHeartRate.append(String.format(", %d", (int)(interpolate(durationToHeartRate, i)))); } Element extendedDataListElement = Util.appendElement(sportsDataElement, "extendedDataList"); Util.appendElement(extendedDataListElement, "extendedData", sbDistance, "dataType", "distance", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); Util.appendElement(extendedDataListElement, "extendedData", sbSpeed, "dataType", "speed", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); if (_includeHeartRateData) Util.appendElement(extendedDataListElement, "extendedData", sbHeartRate, "dataType", "heartRate", "intervalType", "time", "intervalUnit", "s", "intervalValue", "10"); } private void appendSnapShot(Element snapShotListElement, long durationMillis, double distanceMetres, long paceMillisKm, int heartRateBpm, String ... attributes) { Element snapShotElement = Util.appendElement(snapShotListElement, "snapShot", null, attributes); Util.appendElement(snapShotElement, "duration", durationMillis); Util.appendElement(snapShotElement, "distance", String.format("%.3f", distanceMetres/1000)); Util.appendElement(snapShotElement, "pace", paceMillisKm); if (_includeHeartRateData) Util.appendElement(snapShotElement, "bpm", heartRateBpm); } private double interpolate(CubicSpline spline, double x) { if (x < spline.getXmin()) x = spline.getXmin(); else if (x > spline.getXmax()) x = spline.getXmax(); return spline.interpolate(x); } public String generateFileName() { SimpleDateFormat outfileFormat = new SimpleDateFormat("yyyy-MM-dd HH;mm;ss'.xml'"); outfileFormat.setTimeZone(_workoutTimeZone); return outfileFormat.format(_calEnd.getTime()); } public String getStartTimeHumanReadable() { return _startTimeStringHuman; } private Trackpoint getLastTrackpointFromArrayList(ArrayList<Trackpoint> al) { return getTrackpointFromEndofArrayList(al, 0); } private Trackpoint getTrackpointFromEndofArrayList(ArrayList<Trackpoint> al, int placesFromEnd) { return ((al != null) && (al.size() > placesFromEnd)) ? al.get(al.size() - (placesFromEnd + 1)) : null; } public static void main(String[] args) { File inFile = new File(args[0]); String empedID = (args.length >= 2) ? args[1] : null; ConvertTcx c = new ConvertTcx(); try { Document doc = c.generateNikePlusXml(inFile, empedID); Util.writeDocument(doc, c.generateFileName()); } catch (Throwable t) { log.out(t); } } private class Trackpoint { private static final int PACE_MILLIS = 20 * 10000; // How many milli seconds of data to use when calculating pace. private Long _duration; private Double _distance; private Double _heartRate; private Trackpoint _previousTrackpoint; public Trackpoint(Trackpoint previousTrackpoint) { _previousTrackpoint = previousTrackpoint; } /** * A representatino of a garmin <trackpoint> element. * @param duration Current (relative to start of workout) duration in millis. * @param distance Current distance in metres. * @param heartRate Current heartrate in bpm. * @param previousTrackpoint The previously recorded trackpoint, or null if this is the first trackpoint. */ public Trackpoint(long duration, double distance, Double heartRate, Trackpoint previousTrackpoint) { _duration = duration; _distance = distance; _heartRate = heartRate; _previousTrackpoint = previousTrackpoint; } protected Long getDuration() { return _duration; } protected Double getDistance() { return _distance; } protected Double getHeartRate() { return _heartRate; } protected void setDuration(Long duration) { _duration = duration; } protected void setDistance(Double distance) { _distance = distance; } protected void setHeartRate(Double heartRate) { _heartRate = heartRate; } protected void setPreviousTrackpoint(Trackpoint previousTrackpoint) { _previousTrackpoint = previousTrackpoint; } /** * Nike+ uses the number of millis it takes to complete 1km as their pace figure. * @return Nike+ pace. */ protected long getPace() { // This can give skewed pace figures as we might have a trackpoint 2 seconds ago with slightly inaccurate distance resulting in wildly chaotic pace data. //Trackpoint previous = getPreviousDifferentTrackpoint(); // I use PACE_MILLIS previous seconds of data to calculate pace (avoiding the problem caused by getPreviousDifferntTrackpoint). long startDuration = (_duration > PACE_MILLIS) ? _duration - PACE_MILLIS : 0; Trackpoint startTp = getPreviousTrackpoint(); while ((startTp != null) && (startTp.getDuration() > startDuration)) startTp = startTp.getPreviousTrackpoint(); long splitDuration = (startTp == null) ? _duration : (_duration - startTp.getDuration()); double splitDistance = (startTp == null) ? _distance : (_distance - startTp.getDistance()); return (long)((1000d/splitDistance) * splitDuration); } protected Trackpoint getPreviousTrackpoint() { return _previousTrackpoint; } protected Double getMostRecentDistance() { Trackpoint tp = this; while ((tp != null)) { if (tp.getDistance() != null) return tp.getDistance(); tp = tp.getPreviousTrackpoint(); } return 0d; } protected long getDurationSinceLastTrackpoint() { return (_previousTrackpoint == null) ? 0 : (_duration - _previousTrackpoint.getDuration()); } protected boolean isRepeatDuration() { //return (_previousTrackpoint != null) && (_duration.equals(_previousTrackpoint.getDuration())); return (_previousTrackpoint != null) && ((_duration.compareTo(_previousTrackpoint.getDuration())) <= 0); } protected boolean isRepeatDistance() { //return (_previousTrackpoint != null) && (_distance.equals(_previousTrackpoint.getDistance())); return (_previousTrackpoint != null) && ((_distance.compareTo(_previousTrackpoint.getDistance())) <= 0); } protected Long getPreviousDuration() { return (_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDuration(); } protected Double getPreviousDistance() { return (_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDistance(); } protected void incrementDuration(long millis) { _duration += millis; } protected void decrementDuration(long millis) { _duration -= millis; } @Override public String toString() { return String.format("Duration (difference): %d\t(%d)\t\tDistance: %.4f", _duration, (_duration - ((_previousTrackpoint == null) ? 0 : _previousTrackpoint.getDuration())), _distance); } } }
package be.kuleuven.cs.distrinet.rejuse.tree; import be.kuleuven.cs.distrinet.rejuse.action.Nothing; import be.kuleuven.cs.distrinet.rejuse.predicate.Predicate; import be.kuleuven.cs.distrinet.rejuse.predicate.UniversalPredicate; public abstract class TreePredicate<D, E extends Exception> extends UniversalPredicate<D,E>{ public TreePredicate(Class<D> type) { super(type); } /** * Check whether or not this predicate can match a descendant of the * given node. If false, traversal of the subtree can be avoided. * * @param node * @return */ public abstract boolean canSucceedBeyond(D node) throws E; public TreePredicate<D, E> or(final TreePredicate<D, ? extends E> other) { return new TreePredicate<D, E>(type()) { @Override public boolean canSucceedBeyond(D node) throws E { return TreePredicate.this.canSucceedBeyond(node) || other.canSucceedBeyond(node); } @Override public boolean uncheckedEval(D t) throws E { return TreePredicate.this.eval(t) || other.eval(t); } @Override public String toString() { return "("+TreePredicate.this.toString() + "|" + other.toString()+")"; } }; } public TreePredicate<D, E> and(final TreePredicate<D, ? extends E> other) { return new TreePredicate<D, E>(type()) { @Override public boolean canSucceedBeyond(D node) throws E { return TreePredicate.this.canSucceedBeyond(node) && other.canSucceedBeyond(node); } @Override public boolean uncheckedEval(D t) throws E { return TreePredicate.this.eval(t) && other.eval(t); } @Override public String toString() { return "("+TreePredicate.this.toString() + "&" + other.toString()+")"; } }; } public static TreePredicate<Object,Nothing> False() { return new TreePredicate<Object, Nothing>(Object.class) { @Override public boolean canSucceedBeyond(Object node) { return false; } @Override public boolean uncheckedEval(Object t) { return false; } @Override public TreePredicate<Object, Nothing> or( TreePredicate<Object, ? extends Nothing> other) { return (TreePredicate<Object, Nothing>) other; } @Override public Predicate<Object, Nothing> and( Predicate<? super Object, ? extends Nothing> other) { return this; } }; } }
package polyglot.ast; import java.util.StringTokenizer; import polyglot.util.CodeWriter; import polyglot.util.Position; import polyglot.util.SerialVersionUID; import polyglot.visit.PrettyPrinter; /** * An Immutable representation of a Javadoc */ public class Javadoc_c extends Node_c implements Javadoc { private static final long serialVersionUID = SerialVersionUID.generate(); private String text; public Javadoc_c(Position pos, String text) { super(pos, null); this.text = text; } @Override public void prettyPrint(CodeWriter w, PrettyPrinter pp) { // Avoid messing up the pretty printer. String whitespace = " \t"; String linebreak = "\n\r\f"; StringTokenizer tokenizer = new StringTokenizer(text, whitespace + linebreak, true); boolean ignoreSpace = false; w.begin(0); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (linebreak.contains(token)) { w.newline(); ignoreSpace = true; } else if (whitespace.contains(token)) { if (!ignoreSpace) w.allowBreak(1, token); } else { if (ignoreSpace) { w.write(" "); ignoreSpace = false; } w.write(token); } } w.end(); w.newline(); } @Override public String getText() { return text; } }
package burlap.behavior.singleagent.learning; import java.util.LinkedList; import java.util.List; import burlap.behavior.singleagent.EpisodeAnalysis; import burlap.oomdp.core.State; /** * This is the standard interface for defining an agent that learns how to behave in the world through experience. The primary method * is the {@link #runLearningEpisodeFrom(State)} method which causes the agent to interact with the world until it reaches a terminal state. * The interface also provides some common mechanisms for getting the last learning episode the agent performed, storing a history * of learning episodes, and returning the history of stored episodes. * @author James MacGlashan * */ public interface LearningAgent { /** * Causes the agent to perform a learning episode starting in the given initial state. The episode terminates when a terminal * state is reached or if the agent decides to determinate the episode (e.g., by having an internal parameter set for a * maximum number of steps in an episode). * @param initialState The initial state in which the agent will start the episode. * @return The learning episode events that was performed, stored in an {@link burlap.behavior.singleagent.EpisodeAnalysis} object. */ public EpisodeAnalysis runLearningEpisodeFrom(State initialState); /** * Causes the agent to perform a learning episode starting in the given initial state. The episode terminates when a terminal * state is reached, if the agent decides to determinate the episode, or if the number of steps reaches the provided threshold. * @param initialState The initial state in which the agent will start the episode. * @param maxSteps the maximum number of steps in the episode * @return The learning episode events that was performed, stored in an {@link burlap.behavior.singleagent.EpisodeAnalysis} object. */ public EpisodeAnalysis runLearningEpisodeFrom(State initialState, int maxSteps); /** * Returns the last learning episode of the agent. * @return the last learning episode of the agent. */ public EpisodeAnalysis getLastLearningEpisode(); /** * Tells the agent how many {@link burlap.behavior.singleagent.EpisodeAnalysis} objects representing learning episodes to internally store. * For instance, if the number of set to 5, then the agent should remember the save the last 5 learning episodes. Note that this number * has nothing to do with how learning is performed; it is purely for performance gathering. * @param numEps the number of learning episodes to remember. */ public void setNumEpisodesToStore(int numEps); /** * Returns all saved {@link burlap.behavior.singleagent.EpisodeAnalysis} objects of which the agent has kept track. * @return all saved {@link burlap.behavior.singleagent.EpisodeAnalysis} objects of which the agent has kept track. */ public List<EpisodeAnalysis> getAllStoredLearningEpisodes(); /** * Because {@link burlap.behavior.singleagent.learning.LearningAgent} is an interface, default methods for managing * the history of experienced episodes is not provided. Therefore, this class provides the requisite data members * and default methods for making that bookkeeping easy. This allows a class that implements the * {@link burlap.behavior.singleagent.learning.LearningAgent} interface to simply have a data member for this * class and allow it to manage the methods. * * All data members of this class are public. By default the history of learning episodes stored will be just * 1. This method also includes a data member {@link #maxEpisodeSize} which can be optionally used for setting the longest * time a learning agent will run when the {@link burlap.behavior.singleagent.learning.LearningAgent#runLearningEpisodeFrom(burlap.oomdp.core.State)} * method is called. By default, it is INT MAX. * * The class also has a method for automatically adding an episode to its history, will removing the oldest stored * episode if the the size of the history is larger than the max history size. */ public static class LearningAgentBookKeeping{ /** * The history of learning episodes */ public LinkedList<EpisodeAnalysis> episodeHistory = new LinkedList<EpisodeAnalysis>(); public int numEpisodesToStore = 1; public int maxEpisodeSize = Integer.MAX_VALUE; /** * Returns the last learning episode of the agent. * @return the last learning episode of the agent. */ public EpisodeAnalysis getLastLearningEpisode(){ return this.episodeHistory.getLast(); } /** * Tells the agent how many {@link burlap.behavior.singleagent.EpisodeAnalysis} objects representing learning episodes to internally store. * For instance, if the number of set to 5, then the agent should remember the save the last 5 learning episodes. Note that this number * has nothing to do with how learning is performed; it is purely for performance gathering. * @param numEps the number of learning episodes to remember. */ public void setNumEpisodesToStore(int numEps){ this.numEpisodesToStore = numEps; } /** * Returns all saved {@link burlap.behavior.singleagent.EpisodeAnalysis} objects of which the agent has kept track. * @return all saved {@link burlap.behavior.singleagent.EpisodeAnalysis} objects of which the agent has kept track. */ public List<EpisodeAnalysis> getAllStoredLearningEpisodes(){ return this.episodeHistory; } /** * Adds episode ea to this objects history of experienced episodes. If the current size of all episodes * stored is equal to the number of episodes this object is supposed to store, it first removes the oldest * episodes added before adding ea. * @param ea the episode to add to the history of experienced episodes. */ public void offerEpisodeToHistory(EpisodeAnalysis ea){ if(episodeHistory.size() >= numEpisodesToStore){ episodeHistory.poll(); } episodeHistory.offer(ea); } } }
package org.postgresql.util; import java.sql.*; import java.text.*; import java.util.*; /** * This class extends SQLException, and provides our internationalisation handling */ public class PSQLException extends SQLException { private String message; // Cache for future errors static ResourceBundle bundle; /** * This provides the same functionality to SQLException * @param error Error string */ public PSQLException(String error) { super(); translate(error,null); } /** * A more generic entry point. * @param error Error string or standard message id * @param args Array of arguments */ public PSQLException(String error,Object[] args) { //super(); translate(error,args); } /** * Helper version for 1 arg */ public PSQLException(String error,Object arg) { super(); Object[] argv = new Object[1]; argv[0] = arg; translate(error,argv); } /** * Helper version for 2 args */ public PSQLException(String error,Object arg1,Object arg2) { super(); Object[] argv = new Object[2]; argv[0] = arg1; argv[1] = arg2; translate(error,argv); } /** * This does the actual translation */ private void translate(String id,Object[] args) { if(bundle == null) { try { bundle = ResourceBundle.getBundle("org.postgresql.errors"); } catch(MissingResourceException e) { // translation files have not been installed. message = id; } } if (bundle != null) { // Now look up a localized message. If one is not found, then use // the supplied message instead. message = null; try { message = bundle.getString(id); } catch(MissingResourceException e) { message = id; } } // Expand any arguments if(args!=null) message = MessageFormat.format(message,args); } /** * Overides Throwable */ public String getLocalizedMessage() { return message; } /** * Overides Throwable */ public String getMessage() { return message; } /** * Overides Object */ public String toString() { return message; } }
package org.xins.common.text; import org.xins.common.Log; /** * Fast, unsynchronized string buffer implementation. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public class FastStringBuffer extends Object { // Class fields // Class functions // Constructors public FastStringBuffer(int capacity) throws IllegalArgumentException { // Check preconditions if (capacity < 0) { throw new IllegalArgumentException( "capacity (" + capacity + ") < 0"); } // Initialize fields _buffer = new char[capacity]; _length = 0; } public FastStringBuffer(String s) throws IllegalArgumentException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } // Initialize fields _buffer = s.toCharArray(); _length = _buffer.length; } public FastStringBuffer(int capacity, String s) throws IllegalArgumentException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } if (capacity < s.length()) { throw new IllegalArgumentException( "capacity (" + capacity + ") < s.length() (" + s.length() + ')'); } // Initialize fields _buffer = new char[capacity]; _length = s.length(); s.getChars(0, _length, _buffer, 0); } // Fields /** * The underlying character buffer. The size of this buffer is the capacity * of this string buffer object. */ private char[] _buffer; /** * The actual length of the contained content. Is always less than or equal * to the capacity. */ private int _length; // Methods /** * Ensures that the specified needed capacity is actually available. If it * is not, then the internal buffer will be expanded. The new capacity will * be larger than or equal to the needed capacity. * * @param needed * the needed capacity. */ private void ensureCapacity(int needed) { // Determine current capacity int current = _buffer.length; // Increase capacity if needed if (current < needed) { int newCapacity = needed << 2; Log.log_1250(current, newCapacity); char[] newBuffer = new char[newCapacity]; System.arraycopy(_buffer, 0, newBuffer, 0, current); _buffer = newBuffer; } } /** * Appends the specified boolean. If necessary, the capacity of this * string buffer will be increased. * * @param b * the boolean to append, if it is <code>true</code> then the string * <code>"true"</code> will be appended, otherwise the string * <code>"false"</code> will be appended.. */ public void append(boolean b) { append(b ? "true" : "false"); } /** * Appends the specified character. If necessary, the capacity of this * string buffer will be increased. * * @param c * the character to append. */ public void append(char c) { // Ensure there is enough capacity ensureCapacity(_length + 1); // Append the character _buffer[_length++] = c; } public void append(char[] cbuf) throws IllegalArgumentException { // Check preconditions if (cbuf == null) { throw new IllegalArgumentException("cbuf == null"); } int newLength = _length + cbuf.length; // Ensure there is enough capacity ensureCapacity(newLength); // Copy the data into the internal buffer System.arraycopy(cbuf, 0, _buffer, _length, cbuf.length); _length = newLength; } public void append(char[] cbuf, int off, int len) throws IllegalArgumentException { // Check preconditions if (cbuf == null) { throw new IllegalArgumentException("cbuf == null"); } if (off < 0) { throw new IllegalArgumentException("off (" + off + ") < 0"); } else if (off >= cbuf.length && off > 0) { throw new IllegalArgumentException( "off (" + off + ") >= cbuf.length (" + cbuf.length + ')'); } else if (len < 0) { throw new IllegalArgumentException("len (" + len + ") < 0"); } else if (off + len > cbuf.length) { throw new IllegalArgumentException( "off (" + off + ") + len (" + len + ") > cbuf.length (" + cbuf.length + ')'); } if (len == 0) { return; } int newLength = _length + len; // Ensure there is enough capacity ensureCapacity(newLength); // Copy the data into the internal buffer System.arraycopy(cbuf, off, _buffer, _length, len); _length = newLength; } public void append(String str) throws IllegalArgumentException { // Check preconditions if (str == null) { throw new IllegalArgumentException("str == null"); } int strLength = str.length(); int newLength = _length + strLength; // Ensure there is enough capacity ensureCapacity(newLength); // Copy the string chars into the buffer str.getChars(0, strLength, _buffer, _length); _length = newLength; } /** * Appends the string representation of the specified <code>byte</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(byte n) { append(String.valueOf(n)); } /** * Appends the string representation of the specified <code>short</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(short n) { append(String.valueOf(n)); } /** * Appends the string representation of the specified <code>int</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(int n) { append(String.valueOf(n)); } /** * Appends the string representation of the specified <code>long</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(long n) { append(String.valueOf(n)); } /** * Appends the string representation of the specified <code>float</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(float n) { append(String.valueOf(n)); } /** * Appends the string representation of the specified <code>double</code>. * If necessary, the capacity of this string buffer will be increased. * * @param n * the number of which the string representation should be added to this * buffer. */ public void append(double n) { append(String.valueOf(n)); } /** * Gets the length of this string buffer. This is always &lt;= the * capacity. * * @return * the number of characters in this buffer, always * &lt;= {@link #getCapacity()}. */ public int getLength() { return _length; } /** * Gets the capacity of this string buffer. This is always &gt;= the * length. * * @return * the number of characters that fits in this buffer without having to * extend the internal data structure, always &gt;= * {@link #getLength()}. */ public int getCapacity() { return _buffer.length; } /** * Sets the character at the specified index. * * @param index * the index at which to set the character, must be &lt; * {@link #getLength()}. * * @param newChar * the new character value. * * @return * the old character value. * * @throws IndexOutOfBoundsException * if <code>index &lt; 0 || index &gt;= </code>{@link #getLength()}. */ public char setChar(int index, char newChar) throws IndexOutOfBoundsException { if (index >= _length) { throw new IndexOutOfBoundsException( "index (" + index + ") >= getLength() (" + _length + ')'); } char oldChar = _buffer[index]; _buffer[index] = newChar; return oldChar; } public void crop(int newLength) throws IllegalArgumentException { // Check preconditions if (newLength < 0) { throw new IllegalArgumentException( "newLength (" + newLength + ") < 0"); } else if (newLength > _length) { throw new IllegalArgumentException( "newLength (" + newLength + ") > getLength() (" + _length + ')'); } _length = newLength; } /** * Clears this string buffer. The capacity will remain untouched, though. */ public void clear() { crop(0); } /** * Converts the contents of this buffer to a <code>String</code> object. A * new {@link String} object is created each time this method is called. * * @return * a newly constructed {@link String} that contains the same characters * as this string buffer object, never <code>null</code>. */ public String toString() { return new String(_buffer, 0, _length); } }
package com.jaeksoft.searchlib.request; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Iterator; import javax.xml.xpath.XPathExpressionException; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.queryParser.QueryParser.Operator; import org.apache.lucene.search.Query; import org.apache.lucene.search.similar.MoreLikeThis; import org.apache.lucene.util.Version; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.jaeksoft.searchlib.SearchLibException; import com.jaeksoft.searchlib.analysis.LanguageEnum; import com.jaeksoft.searchlib.collapse.CollapseMode; import com.jaeksoft.searchlib.config.Config; import com.jaeksoft.searchlib.facet.FacetField; import com.jaeksoft.searchlib.filter.Filter; import com.jaeksoft.searchlib.filter.Filter.Source; import com.jaeksoft.searchlib.filter.FilterList; import com.jaeksoft.searchlib.function.expression.RootExpression; import com.jaeksoft.searchlib.function.expression.SyntaxError; import com.jaeksoft.searchlib.index.IndexAbstract; import com.jaeksoft.searchlib.result.Result; import com.jaeksoft.searchlib.schema.Field; import com.jaeksoft.searchlib.schema.FieldList; import com.jaeksoft.searchlib.schema.Schema; import com.jaeksoft.searchlib.schema.SchemaField; import com.jaeksoft.searchlib.snippet.SnippetField; import com.jaeksoft.searchlib.sort.SortField; import com.jaeksoft.searchlib.sort.SortList; import com.jaeksoft.searchlib.spellcheck.SpellCheckField; import com.jaeksoft.searchlib.util.External; import com.jaeksoft.searchlib.util.ReadWriteLock; import com.jaeksoft.searchlib.util.Timer; import com.jaeksoft.searchlib.util.XPathParser; import com.jaeksoft.searchlib.util.XmlWriter; public class SearchRequest implements Externalizable { private static final long serialVersionUID = 148522254171520640L; private transient QueryParser queryParser; private transient Query complexQuery; private transient Query primitiveQuery; private transient Config config; private transient Timer timer; private transient long finalTime; private String requestName; private FilterList filterList; private boolean allowLeadingWildcard; private int phraseSlop; private QueryParser.Operator defaultOperator; private FieldList<SnippetField> snippetFieldList; private FieldList<Field> returnFieldList; private FieldList<Field> documentFieldList; private FieldList<FacetField> facetFieldList; private FieldList<SpellCheckField> spellCheckFieldList; private SortList sortList; private String collapseField; private int collapseMax; private CollapseMode collapseMode; private boolean isMoreLikeThis; private String moreLikeThisDocQuery; private FieldList<Field> moreLikeThisFieldList; private int moreLikeThisMinWordLen; private int moreLikeThisMaxWordLen; private int moreLikeThisMinDocFreq; private int moreLikeThisMinTermFreq; private String moreLikeThisStopWords; private int start; private int rows; private LanguageEnum lang; private String queryString; private String patternQuery; private String scoreFunction; private String queryParsed; private boolean withDocuments; private boolean withSortValues; private boolean debug; private final ReadWriteLock rwl = new ReadWriteLock(); public SearchRequest() { queryParser = null; config = null; timer = null; finalTime = 0; } public SearchRequest(Config config) { this.config = config; this.requestName = null; this.filterList = new FilterList(this.config); this.queryParser = null; this.allowLeadingWildcard = false; this.phraseSlop = 10; this.defaultOperator = Operator.OR; this.snippetFieldList = new FieldList<SnippetField>(); this.returnFieldList = new FieldList<Field>(); this.sortList = new SortList(); this.documentFieldList = null; this.facetFieldList = new FieldList<FacetField>(); this.spellCheckFieldList = new FieldList<SpellCheckField>(); this.collapseField = null; this.collapseMax = 2; this.collapseMode = CollapseMode.COLLAPSE_OFF; this.isMoreLikeThis = false; this.moreLikeThisFieldList = new FieldList<Field>(); this.moreLikeThisMinWordLen = 0; this.moreLikeThisMaxWordLen = 0; this.moreLikeThisMinDocFreq = 0; this.moreLikeThisMinTermFreq = 0; this.moreLikeThisStopWords = null; this.start = 0; this.rows = 10; this.lang = null; this.complexQuery = null; this.primitiveQuery = null; this.queryString = null; this.patternQuery = null; this.scoreFunction = null; this.withDocuments = true; this.withSortValues = false; this.queryParsed = null; this.timer = new Timer("Search request"); this.finalTime = 0; this.debug = false; } public SearchRequest(SearchRequest searchRequest) { this(searchRequest.config); searchRequest.rwl.r.lock(); try { this.requestName = searchRequest.requestName; this.filterList = new FilterList(searchRequest.filterList); this.queryParser = null; this.allowLeadingWildcard = searchRequest.allowLeadingWildcard; this.phraseSlop = searchRequest.phraseSlop; this.defaultOperator = searchRequest.defaultOperator; this.snippetFieldList = new FieldList<SnippetField>( searchRequest.snippetFieldList); this.returnFieldList = new FieldList<Field>( searchRequest.returnFieldList); this.sortList = new SortList(searchRequest.sortList); this.documentFieldList = null; if (searchRequest.documentFieldList != null) this.documentFieldList = new FieldList<Field>( searchRequest.documentFieldList); this.facetFieldList = new FieldList<FacetField>( searchRequest.facetFieldList); this.spellCheckFieldList = new FieldList<SpellCheckField>( searchRequest.spellCheckFieldList); this.collapseField = searchRequest.collapseField; this.collapseMax = searchRequest.collapseMax; this.collapseMode = searchRequest.collapseMode; this.isMoreLikeThis = searchRequest.isMoreLikeThis; this.moreLikeThisFieldList = new FieldList<Field>( searchRequest.moreLikeThisFieldList); this.moreLikeThisMinWordLen = searchRequest.moreLikeThisMinWordLen; this.moreLikeThisMaxWordLen = searchRequest.moreLikeThisMaxWordLen; this.moreLikeThisMinDocFreq = searchRequest.moreLikeThisMinDocFreq; this.moreLikeThisMinTermFreq = searchRequest.moreLikeThisMinTermFreq; this.moreLikeThisStopWords = searchRequest.moreLikeThisStopWords; this.moreLikeThisDocQuery = searchRequest.moreLikeThisDocQuery; this.withDocuments = searchRequest.withDocuments; this.withSortValues = searchRequest.withSortValues; this.start = searchRequest.start; this.rows = searchRequest.rows; this.lang = searchRequest.lang; this.complexQuery = null; this.primitiveQuery = null; this.queryString = searchRequest.queryString; this.patternQuery = searchRequest.patternQuery; this.scoreFunction = searchRequest.scoreFunction; this.queryParsed = null; this.debug = searchRequest.debug; } finally { searchRequest.rwl.r.unlock(); } } public void reset() { rwl.w.lock(); try { this.queryParsed = null; this.complexQuery = null; this.primitiveQuery = null; this.queryParser = null; } finally { rwl.w.unlock(); } } private SearchRequest(Config config, String requestName, boolean allowLeadingWildcard, int phraseSlop, QueryParser.Operator defaultOperator, int start, int rows, String codeLang, String patternQuery, String queryString, String scoreFunction, boolean delete, boolean withDocuments, boolean withSortValues, boolean debug) { this(config); this.requestName = requestName; this.allowLeadingWildcard = allowLeadingWildcard; this.phraseSlop = phraseSlop; this.defaultOperator = defaultOperator; this.start = start; this.rows = rows; this.lang = LanguageEnum.findByCode(codeLang); this.queryString = queryString; this.patternQuery = patternQuery; if (scoreFunction != null) if (scoreFunction.trim().length() == 0) scoreFunction = null; this.scoreFunction = scoreFunction; this.withDocuments = withDocuments; this.withSortValues = withSortValues; this.debug = debug; } public void init(Config config) { rwl.w.lock(); try { this.config = config; finalTime = 0; if (timer != null) timer.reset(); timer = new Timer("Search request"); } finally { rwl.w.unlock(); } } public Config getConfig() { rwl.r.lock(); try { return this.config; } finally { rwl.r.unlock(); } } public String getRequestName() { rwl.r.lock(); try { return this.requestName; } finally { rwl.r.unlock(); } } public void setRequestName(String name) { rwl.w.lock(); try { this.requestName = name; } finally { rwl.w.unlock(); } } public int getPhraseSlop() { rwl.r.lock(); try { return phraseSlop; } finally { rwl.r.unlock(); } } public void setPhraseSlop(int value) { rwl.w.lock(); try { phraseSlop = value; } finally { rwl.w.unlock(); } } private String getFinalQuery() { String finalQuery; if (patternQuery != null && patternQuery.length() > 0 && queryString != null) finalQuery = patternQuery.replace("$$", queryString).replace( "\"\"", "\""); else finalQuery = queryString; return finalQuery; } public Query getSnippetQuery() throws IOException, ParseException, SyntaxError, SearchLibException { rwl.r.lock(); try { if (primitiveQuery != null) return primitiveQuery; } finally { rwl.r.unlock(); } rwl.w.lock(); try { if (primitiveQuery != null) return primitiveQuery; primitiveQuery = config.getIndex().rewrite(getQuery()); return primitiveQuery; } finally { rwl.w.unlock(); } } private Query getMoreLikeThisQuery() throws SearchLibException, IOException { Config config = getConfig(); IndexAbstract index = config.getIndex(); SearchRequest searchRequest = config.getNewSearchRequest(); searchRequest.setRows(1); searchRequest.setQueryString(moreLikeThisDocQuery); Result result = index.search(searchRequest); if (result.getNumFound() == 0) return null; int docId = result.getDocs()[0].doc; MoreLikeThis mlt = index.getMoreLikeThis(); mlt.setMinWordLen(moreLikeThisMinWordLen); mlt.setMaxWordLen(moreLikeThisMaxWordLen); mlt.setMinDocFreq(moreLikeThisMinDocFreq); mlt.setMinTermFreq(moreLikeThisMinTermFreq); mlt.setFieldNames(moreLikeThisFieldList.toArrayName()); mlt.setAnalyzer(config.getSchema().getQueryPerFieldAnalyzer(lang)); if (moreLikeThisStopWords != null) mlt.setStopWords(getConfig().getStopWordsManager().getWords( moreLikeThisStopWords)); return mlt.like(docId); } public Query getQuery() throws ParseException, SyntaxError, SearchLibException, IOException { rwl.r.lock(); try { if (complexQuery != null) return complexQuery; } finally { rwl.r.unlock(); } rwl.w.lock(); try { if (complexQuery != null) return complexQuery; if (isMoreLikeThis) { complexQuery = getMoreLikeThisQuery(); } else { queryParser = getQueryParser(); String fq = getFinalQuery(); if (fq == null) return null; complexQuery = queryParser.parse(fq); } queryParsed = complexQuery.toString(); if (scoreFunction != null) complexQuery = RootExpression.getQuery(complexQuery, scoreFunction); return complexQuery; } finally { rwl.w.unlock(); } } private QueryParser getQueryParser() throws ParseException, SearchLibException { if (queryParser != null) return queryParser; Schema schema = getConfig().getSchema(); queryParser = new QueryParser(Version.LUCENE_29, schema.getFieldList() .getDefaultField().getName(), schema.getQueryPerFieldAnalyzer(getLang())); queryParser.setAllowLeadingWildcard(allowLeadingWildcard); queryParser.setPhraseSlop(phraseSlop); queryParser.setDefaultOperator(defaultOperator); queryParser.setLowercaseExpandedTerms(false); return queryParser; } public String getQueryString() { rwl.r.lock(); try { return queryString; } finally { rwl.r.unlock(); } } public String getPatternQuery() { rwl.r.lock(); try { return patternQuery; } finally { rwl.r.unlock(); } } public void setPatternQuery(String value) { rwl.w.lock(); try { patternQuery = value; complexQuery = null; primitiveQuery = null; } finally { rwl.w.unlock(); } } public String getQueryParsed() throws ParseException, SyntaxError, SearchLibException, IOException { rwl.r.lock(); try { getQuery(); return queryParsed; } finally { rwl.r.unlock(); } } public void setQueryString(String q) { rwl.w.lock(); try { queryString = q; complexQuery = null; primitiveQuery = null; } finally { rwl.w.unlock(); } } public String getScoreFunction() { rwl.r.lock(); try { return scoreFunction; } finally { rwl.r.unlock(); } } public void setScoreFunction(String v) { rwl.w.lock(); try { scoreFunction = v; } finally { rwl.w.unlock(); } } public FilterList getFilterList() { rwl.r.lock(); try { return this.filterList; } finally { rwl.r.unlock(); } } public void addFilter(String req) throws ParseException { rwl.w.lock(); try { this.filterList.add(req, Filter.Source.REQUEST); } finally { rwl.w.unlock(); } } public FieldList<SnippetField> getSnippetFieldList() { rwl.r.lock(); try { return this.snippetFieldList; } finally { rwl.r.unlock(); } } public FieldList<Field> getReturnFieldList() { rwl.r.lock(); try { return this.returnFieldList; } finally { rwl.r.unlock(); } } public void addReturnField(String fieldName) throws SearchLibException { rwl.w.lock(); try { returnFieldList.add(new Field(config.getSchema().getFieldList() .get(fieldName))); } finally { rwl.w.unlock(); } } public SortList getSortList() { rwl.r.lock(); try { return this.sortList; } finally { rwl.r.unlock(); } } public void addSort(String fieldName, boolean desc) { rwl.w.lock(); try { sortList.add(fieldName, desc); } finally { rwl.w.unlock(); } } public FieldList<FacetField> getFacetFieldList() { rwl.r.lock(); try { return this.facetFieldList; } finally { rwl.r.unlock(); } } public FieldList<SpellCheckField> getSpellCheckFieldList() { rwl.r.lock(); try { return this.spellCheckFieldList; } finally { rwl.r.unlock(); } } public void setCollapseField(String collapseField) { rwl.w.lock(); try { this.collapseField = collapseField; } finally { rwl.w.unlock(); } } public void setCollapseMax(int collapseMax) { rwl.w.lock(); try { this.collapseMax = collapseMax; } finally { rwl.w.unlock(); } } public String getCollapseField() { rwl.r.lock(); try { return this.collapseField; } finally { rwl.r.unlock(); } } public int getCollapseMax() { rwl.r.lock(); try { return this.collapseMax; } finally { rwl.r.unlock(); } } public int getStart() { rwl.r.lock(); try { return this.start; } finally { rwl.r.unlock(); } } public void setStart(int start) { rwl.w.lock(); try { this.start = start; } finally { rwl.w.unlock(); } } public boolean isWithDocument() { rwl.r.lock(); try { return this.withDocuments; } finally { rwl.r.unlock(); } } public void setWithDocument(boolean withDocuments) { rwl.w.lock(); try { this.withDocuments = withDocuments; } finally { rwl.w.unlock(); } } public boolean isWithSortValues() { rwl.r.lock(); try { return withSortValues; } finally { rwl.r.unlock(); } } public void setWithSortValues(boolean withSortValues) { rwl.w.lock(); try { this.withSortValues = withSortValues; } finally { rwl.w.unlock(); } } public void setDebug(boolean debug) { rwl.w.lock(); try { this.debug = debug; } finally { rwl.w.unlock(); } } public boolean isDebug() { rwl.r.lock(); try { return debug; } finally { rwl.r.unlock(); } } public int getRows() { rwl.r.lock(); try { return this.rows; } finally { rwl.r.unlock(); } } public LanguageEnum getLang() { rwl.r.lock(); try { return this.lang; } finally { rwl.r.unlock(); } } public void setRows(int rows) { rwl.w.lock(); try { this.rows = rows; } finally { rwl.w.unlock(); } } public int getEnd() { rwl.r.lock(); try { return this.start + this.rows; } finally { rwl.r.unlock(); } } @Override public String toString() { rwl.r.lock(); try { StringBuffer sb = new StringBuffer(); sb.append("RequestName: "); sb.append(requestName); sb.append(" DefaultOperator: "); sb.append(defaultOperator); sb.append(" Start: "); sb.append(start); sb.append(" Rows: "); sb.append(rows); sb.append(" Query: "); sb.append(complexQuery); sb.append(" Facet: " + getFacetFieldList().toString()); if (getCollapseMode() != CollapseMode.COLLAPSE_OFF) sb.append(" Collapsing: " + getCollapseMode() + " " + getCollapseField() + "(" + getCollapseMax() + ")"); return sb.toString(); } finally { rwl.r.unlock(); } } public void setLang(LanguageEnum lang) { rwl.w.lock(); try { this.lang = lang; } finally { rwl.w.unlock(); } } public FieldList<Field> getDocumentFieldList() { rwl.r.lock(); try { if (documentFieldList != null) return documentFieldList; } finally { rwl.r.unlock(); } rwl.w.lock(); try { if (documentFieldList != null) return documentFieldList; documentFieldList = new FieldList<Field>(returnFieldList); Iterator<SnippetField> it = snippetFieldList.iterator(); while (it.hasNext()) documentFieldList.add(new Field(it.next())); return documentFieldList; } finally { rwl.w.unlock(); } } public String getDefaultOperator() { rwl.r.lock(); try { return defaultOperator.toString(); } finally { rwl.r.unlock(); } } public void setDefaultOperator(String value) { rwl.w.lock(); try { if ("and".equalsIgnoreCase(value)) defaultOperator = Operator.AND; else if ("or".equalsIgnoreCase(value)) defaultOperator = Operator.OR; } finally { rwl.w.unlock(); } } public void setCollapseMode(CollapseMode mode) { rwl.w.lock(); try { this.collapseMode = mode; } finally { rwl.w.unlock(); } } public CollapseMode getCollapseMode() { rwl.r.lock(); try { return this.collapseMode; } finally { rwl.r.unlock(); } } /** * @return the moreLikeThisDocQuery */ public String getMoreLikeThisDocQuery() { rwl.r.lock(); try { return moreLikeThisDocQuery; } finally { rwl.r.unlock(); } } /** * @return the isMoreLikeThis */ public boolean isMoreLikeThis() { rwl.r.lock(); try { return isMoreLikeThis; } finally { rwl.r.unlock(); } } /** * @param isMoreLikeThis * the isMoreLikeThis to set */ public void setMoreLikeThis(boolean isMoreLikeThis) { rwl.w.lock(); try { this.isMoreLikeThis = isMoreLikeThis; } finally { rwl.w.unlock(); } } /** * @param moreLikeThisDocQuery * the moreLikeThisDocQuery to set */ public void setMoreLikeThisDocQuery(String moreLikeThisDocQuery) { rwl.w.lock(); try { this.moreLikeThisDocQuery = moreLikeThisDocQuery; } finally { rwl.w.unlock(); } } /** * @return the moreLikeThisFieldList */ public FieldList<Field> getMoreLikeThisFieldList() { rwl.r.lock(); try { return moreLikeThisFieldList; } finally { rwl.r.unlock(); } } /** * @return the moreLikeThisMinWordLen */ public int getMoreLikeThisMinWordLen() { rwl.r.lock(); try { return moreLikeThisMinWordLen; } finally { rwl.r.unlock(); } } /** * @param moreLikeThisMinWordLen * the moreLikeThisMinWordLen to set */ public void setMoreLikeThisMinWordLen(int moreLikeThisMinWordLen) { rwl.w.lock(); try { this.moreLikeThisMinWordLen = moreLikeThisMinWordLen; } finally { rwl.w.unlock(); } } /** * @return the moreLikeThisMaxWordLen */ public int getMoreLikeThisMaxWordLen() { rwl.r.lock(); try { return moreLikeThisMaxWordLen; } finally { rwl.r.unlock(); } } /** * @param moreLikeThisMaxWordLen * the moreLikeThisMaxWordLen to set */ public void setMoreLikeThisMaxWordLen(int moreLikeThisMaxWordLen) { rwl.w.lock(); try { this.moreLikeThisMaxWordLen = moreLikeThisMaxWordLen; } finally { rwl.w.unlock(); } } /** * @return the moreLikeThisMinDocFreq */ public int getMoreLikeThisMinDocFreq() { rwl.r.lock(); try { return moreLikeThisMinDocFreq; } finally { rwl.r.unlock(); } } /** * @param moreLikeThisMinDocFreq * the moreLikeThisMinDocFreq to set */ public void setMoreLikeThisMinDocFreq(int moreLikeThisMinDocFreq) { rwl.w.lock(); try { this.moreLikeThisMinDocFreq = moreLikeThisMinDocFreq; } finally { rwl.w.unlock(); } } /** * @return the moreLikeThisMinTermFreq */ public int getMoreLikeThisMinTermFreq() { rwl.r.lock(); try { return moreLikeThisMinTermFreq; } finally { rwl.r.unlock(); } } /** * @param moreLikeThisMinTermFreq * the moreLikeThisMinTermFreq to set */ public void setMoreLikeThisMinTermFreq(int moreLikeThisMinTermFreq) { rwl.w.lock(); try { this.moreLikeThisMinTermFreq = moreLikeThisMinTermFreq; } finally { rwl.w.unlock(); } } /** * @return the moreLikeThisStopWords */ public String getMoreLikeThisStopWords() { rwl.r.lock(); try { return moreLikeThisStopWords; } finally { rwl.r.unlock(); } } /** * @param moreLikeThisStopWords * the moreLikeThisStopWords to set */ public void setMoreLikeThisStopWords(String moreLikeThisStopWords) { rwl.w.lock(); try { this.moreLikeThisStopWords = moreLikeThisStopWords; } finally { rwl.w.unlock(); } } public final static String[] CONTROL_CHARS = { "\\", "^", "\"", "~", ":" }; public final static String[] RANGE_CHARS = { "(", ")", "{", "}", "[", "]" }; public final static String[] AND_OR_NOT_CHARS = { "+", "-", "&&", "||", "!" }; public final static String[] WILDCARD_CHARS = { "*", "?" }; public static String escapeQuery(String query, String[] escapeChars) { for (String s : escapeChars) { String r = ""; for (int i = 0; i < s.length(); i++) r += "\\" + s.charAt(i); query = query.replace(s, r); } return query; } public static String escapeQuery(String query) { query = escapeQuery(query, CONTROL_CHARS); query = escapeQuery(query, RANGE_CHARS); query = escapeQuery(query, AND_OR_NOT_CHARS); query = escapeQuery(query, WILDCARD_CHARS); return query; } public boolean isFacet() { rwl.r.lock(); try { if (facetFieldList == null) return false; return facetFieldList.size() > 0; } finally { rwl.r.unlock(); } } public boolean isSpellCheck() { rwl.r.lock(); try { if (spellCheckFieldList == null) return false; return spellCheckFieldList.size() > 0; } finally { rwl.r.unlock(); } } public long getFinalTime() { rwl.r.lock(); try { if (finalTime != 0) return finalTime; } finally { rwl.r.unlock(); } rwl.w.lock(); try { finalTime = timer.duration(); return finalTime; } finally { rwl.w.unlock(); } } public Timer getTimer() { rwl.r.lock(); try { return timer; } finally { rwl.r.unlock(); } } public static SearchRequest fromXmlConfig(Config config, XPathParser xpp, Node node) throws XPathExpressionException, DOMException, ParseException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (node == null) return null; String name = XPathParser.getAttributeString(node, "name"); SearchRequest searchRequest = new SearchRequest(config, name, ("yes".equalsIgnoreCase(XPathParser.getAttributeString(node, "allowLeadingWildcard"))), XPathParser.getAttributeValue(node, "phraseSlop"), ("and".equalsIgnoreCase(XPathParser.getAttributeString(node, "defaultOperator"))) ? QueryParser.AND_OPERATOR : QueryParser.OR_OPERATOR, XPathParser.getAttributeValue(node, "start"), XPathParser.getAttributeValue(node, "rows"), XPathParser.getAttributeString(node, "lang"), xpp.getNodeString(node, "query"), null, xpp.getNodeString(node, "scoreFunction"), false, true, false, false); searchRequest.setCollapseMode(CollapseMode.valueOfLabel(XPathParser .getAttributeString(node, "collapseMode"))); searchRequest.setCollapseField(XPathParser.getAttributeString(node, "collapseField")); searchRequest.setCollapseMax(XPathParser.getAttributeValue(node, "collapseMax")); Node mltNode = xpp.getNode(node, "moreLikeThis"); if (mltNode != null) { searchRequest.setMoreLikeThis("yes".equalsIgnoreCase(XPathParser .getAttributeString(mltNode, "active"))); searchRequest.setMoreLikeThisMinWordLen(XPathParser .getAttributeValue(mltNode, "minWordLen")); searchRequest.setMoreLikeThisMaxWordLen(XPathParser .getAttributeValue(mltNode, "maxWordLen")); searchRequest.setMoreLikeThisMinTermFreq(XPathParser .getAttributeValue(mltNode, "minTermFreq")); searchRequest.setMoreLikeThisMinDocFreq(XPathParser .getAttributeValue(mltNode, "minDocFreq")); searchRequest.setMoreLikeThisStopWords(XPathParser .getAttributeString(mltNode, "stopWords")); NodeList mltFieldsNodes = xpp.getNodeList(mltNode, "fields/field"); if (mltFieldsNodes != null) { FieldList<Field> moreLikeThisFields = searchRequest .getMoreLikeThisFieldList(); for (int i = 0; i < mltFieldsNodes.getLength(); i++) { Field field = Field.fromXmlConfig(mltFieldsNodes.item(i)); if (field != null) moreLikeThisFields.add(field); } } Node mltDocQueryNode = xpp.getNode(mltNode, "docQuery"); if (mltDocQueryNode != null) searchRequest.setMoreLikeThisDocQuery(xpp .getNodeString(mltDocQueryNode)); } FieldList<Field> returnFields = searchRequest.getReturnFieldList(); FieldList<SchemaField> fieldList = config.getSchema().getFieldList(); Field.filterCopy(fieldList, xpp.getNodeString(node, "returnFields"), returnFields); NodeList nodes = xpp.getNodeList(node, "returnFields/field"); for (int i = 0; i < nodes.getLength(); i++) { Field field = Field.fromXmlConfig(nodes.item(i)); if (field != null) returnFields.add(field); } FieldList<SnippetField> snippetFields = searchRequest .getSnippetFieldList(); nodes = xpp.getNodeList(node, "snippet/field"); for (int i = 0; i < nodes.getLength(); i++) SnippetField.copySnippetFields(nodes.item(i), fieldList, snippetFields); FieldList<FacetField> facetFields = searchRequest.getFacetFieldList(); nodes = xpp.getNodeList(node, "facetFields/facetField"); for (int i = 0; i < nodes.getLength(); i++) FacetField.copyFacetFields(nodes.item(i), fieldList, facetFields); FieldList<SpellCheckField> spellCheckFields = searchRequest .getSpellCheckFieldList(); nodes = xpp.getNodeList(node, "spellCheckFields/spellCheckField"); for (int i = 0; i < nodes.getLength(); i++) SpellCheckField.copySpellCheckFields(nodes.item(i), fieldList, spellCheckFields); FilterList filterList = searchRequest.getFilterList(); nodes = xpp.getNodeList(node, "filters/filter"); for (int i = 0; i < nodes.getLength(); i++) filterList.add(xpp.getNodeString(nodes.item(i)), Source.CONFIGXML); SortList sortList = searchRequest.getSortList(); nodes = xpp.getNodeList(node, "sort/field"); for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); String textNode = xpp.getNodeString(node); if (textNode != null && textNode.length() > 0) sortList.add(textNode); else sortList.add(new SortField(node)); } return searchRequest; } public void writeXmlConfig(XmlWriter xmlWriter) throws SAXException { xmlWriter.startElement("request", "name", requestName, "phraseSlop", Integer.toString(phraseSlop), "defaultOperator", getDefaultOperator(), "start", Integer.toString(start), "rows", Integer.toString(rows), "lang", lang != null ? lang.getCode() : null, "collapseMode", collapseMode.getLabel(), "collapseField", collapseField, "collapseMax", Integer .toString(collapseMax)); xmlWriter.startElement("moreLikeThis", "minWordLen", Integer.toString(moreLikeThisMinWordLen), "maxWordLen", Integer.toString(moreLikeThisMaxWordLen), "minDocFreq", Integer.toString(moreLikeThisMinDocFreq), "minTermFreq", Integer.toString(moreLikeThisMinTermFreq), "stopWords", moreLikeThisStopWords, "active", isMoreLikeThis ? "yes" : "no"); if (moreLikeThisFieldList.size() > 0) { xmlWriter.startElement("fields"); moreLikeThisFieldList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (moreLikeThisDocQuery != null && moreLikeThisDocQuery.length() > 0) { xmlWriter.startElement("docQuery"); xmlWriter.textNode(moreLikeThisDocQuery); xmlWriter.endElement(); } xmlWriter.endElement(); if (patternQuery != null && patternQuery.trim().length() > 0) { xmlWriter.startElement("query"); xmlWriter.textNode(patternQuery); xmlWriter.endElement(); } if (returnFieldList.size() > 0) { xmlWriter.startElement("returnFields"); returnFieldList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (snippetFieldList.size() > 0) { xmlWriter.startElement("snippet"); snippetFieldList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (facetFieldList.size() > 0) { xmlWriter.startElement("facetFields"); facetFieldList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (spellCheckFieldList.size() > 0) { xmlWriter.startElement("spellCheckFields"); spellCheckFieldList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (sortList.getFieldList().size() > 0) { xmlWriter.startElement("sort"); sortList.getFieldList().writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (filterList.size() > 0) { xmlWriter.startElement("filters"); filterList.writeXmlConfig(xmlWriter); xmlWriter.endElement(); } if (scoreFunction != null && scoreFunction.trim().length() > 0) { xmlWriter.startElement("scoreFunction"); xmlWriter.textNode(scoreFunction); xmlWriter.endElement(); } xmlWriter.endElement(); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { requestName = External.readUTF(in); filterList = External.readObject(in); allowLeadingWildcard = in.readBoolean(); phraseSlop = in.readInt(); if (in.readBoolean()) defaultOperator = Operator.OR; else defaultOperator = Operator.AND; snippetFieldList = External.readObject(in); returnFieldList = External.readObject(in); documentFieldList = External.readObject(in); facetFieldList = External.readObject(in); spellCheckFieldList = External.readObject(in); sortList = External.readObject(in); collapseField = External.readUTF(in); collapseMax = in.readInt(); collapseMode = CollapseMode.valueOf(in.readInt()); start = in.readInt(); rows = in.readInt(); lang = LanguageEnum.findByCode(External.readUTF(in)); queryString = External.readUTF(in); patternQuery = External.readUTF(in); scoreFunction = External.readUTF(in); queryParsed = External.readUTF(in); withDocuments = in.readBoolean(); withSortValues = in.readBoolean(); debug = in.readBoolean(); } @Override public void writeExternal(ObjectOutput out) throws IOException { External.writeUTF(requestName, out); External.writeObject(filterList, out); out.writeBoolean(allowLeadingWildcard); out.writeInt(phraseSlop); out.writeBoolean(defaultOperator == Operator.OR); External.writeObject(snippetFieldList, out); External.writeObject(returnFieldList, out); External.writeObject(documentFieldList, out); External.writeObject(facetFieldList, out); External.writeObject(spellCheckFieldList, out); External.writeObject(sortList, out); External.writeUTF(collapseField, out); out.writeInt(collapseMax); out.writeInt(collapseMode.code); out.writeInt(start); out.writeInt(rows); if (lang == null) External.writeUTF(LanguageEnum.UNDEFINED.getCode(), out); else External.writeUTF(lang.getCode(), out); External.writeUTF(queryString, out); External.writeUTF(patternQuery, out); External.writeUTF(scoreFunction, out); External.writeUTF(queryParsed, out); out.writeBoolean(withDocuments); out.writeBoolean(withSortValues); out.writeBoolean(debug); } }
package com.idunnolol.ragefaces; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.idunnolol.ragefaces.adapters.RageFaceDbAdapter; import com.idunnolol.ragefaces.adapters.RageFaceScannerAdapter; import com.idunnolol.ragefaces.adapters.RawRetriever; import com.idunnolol.ragefaces.data.DatabaseHelper; public class RageFacePickerActivity extends Activity { // Where files go for sharing with other apps private static final String RAGE_DIR = "com.idunnolol.rageface/"; private static final String PUBLIC_RAGE_DIR = "Rage Faces/"; // For keeping state between configuration changes private static final String STATE_RAGEFACE_ID = "STATE_RAGEFACE_ID"; private static final String STATE_RAGEFACE_NAME = "STATE_RAGEFACE_NAME"; private static final String STATE_RAGEFACE_URI = "STATE_RAGEFACE_URI"; // Dialog codes private static final int DIALOG_ACTIONS = 1; private static final int DIALOG_ABOUT = 2; private static final int DIALOG_FILTER = 3; // Cached Activity info private Context mContext; private Resources mResources; private BaseAdapter mAdapter; // Cached views private LinearLayout mLoadingContainer; private TextView mMessageView; private GridView mGridView; // When dialog is opened, rage face data stored here private int mRageFaceId; private String mRageFaceName; private Uri mRageFaceUri; // Filter data private int[] mCategoryIds; private String[] mCategoryNames; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean dbExists = DatabaseHelper.createOrUpdateDatabase(this); mContext = this; mResources = getResources(); setContentView(R.layout.main); mLoadingContainer = (LinearLayout) findViewById(R.id.LoadingContainer); mMessageView = (TextView) findViewById(R.id.Message); mGridView = (GridView) findViewById(R.id.GridView); // Create an adapter if (dbExists) { mAdapter = new RageFaceDbAdapter(this); } else { mAdapter = new RageFaceScannerAdapter(this); findViewById(R.id.button_bar_layout).setVisibility(View.GONE); } // Apply adapter to gridview mGridView.setAdapter(mAdapter); mGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Gather some data on what the user selected RawRetriever retriever = (RawRetriever) mAdapter; mRageFaceId = retriever.getRawResourceId((String) mAdapter.getItem(position)); mRageFaceName = (String) mAdapter.getItem(position); mRageFaceUri = loadRageFace(mRageFaceName, false); Intent intent = getIntent(); if (intent.getAction().equals(Intent.ACTION_GET_CONTENT)) { Intent data = new Intent(); data.setData(mRageFaceUri); // #18: This is needed for the picture frame widget, which depends on // the face being passed as a Parcelable Bitmap as "data" data.putExtra("data", BitmapFactory.decodeResource(getResources(), mRageFaceId)); setResult(RESULT_OK, data); finish(); } else { // Default - show dialog with action options to user showDialog(DIALOG_ACTIONS); } } }); // Configure the filter button Button filterButton = (Button) findViewById(R.id.filter_button); filterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_FILTER); } }); // Configure the filter dialog backing data if (dbExists) { SQLiteDatabase db = DatabaseHelper.getFacesDb(this); Cursor c = DatabaseHelper.getCategories(db); c.moveToFirst(); int len = c.getCount(); mCategoryIds = new int[len]; mCategoryNames = new String[len]; int a = 0; while (!c.isAfterLast()) { mCategoryIds[a] = c.getInt(0); mCategoryNames[a] = c.getString(1); c.moveToNext(); a++; } c.close(); db.close(); } // Load rage faces to SD card boolean success = loadRageFacesDir(); // Supposing everything went fine, load the gridview if (success) { mLoadingContainer.setVisibility(View.GONE); mGridView.setVisibility(View.VISIBLE); } if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_RAGEFACE_URI)) { mRageFaceId = savedInstanceState.getInt(STATE_RAGEFACE_ID); mRageFaceName = savedInstanceState.getString(STATE_RAGEFACE_NAME); mRageFaceUri = savedInstanceState.getParcelable(STATE_RAGEFACE_URI); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRageFaceUri != null) { outState.putInt(STATE_RAGEFACE_ID, mRageFaceId); outState.putString(STATE_RAGEFACE_NAME, mRageFaceName); outState.putParcelable(STATE_RAGEFACE_URI, mRageFaceUri); } } @Override protected void onDestroy() { super.onDestroy(); // Properly close cursor if we're using db-based faces if (mAdapter instanceof RageFaceDbAdapter) { ((RageFaceDbAdapter) mAdapter).shutdown(); } } public boolean loadRageFacesDir() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { mMessageView.setText(R.string.err_sd_not_mounted); return false; } File rageDir = getRageDir(); if (!rageDir.exists()) { Log.d(RageFacesApp.TAG, "Rage face directory does not exist, creating it."); rageDir.mkdir(); } File nomediaFile = new File(rageDir, ".nomedia"); if (!nomediaFile.exists()) { Log.d(RageFacesApp.TAG, ".nomedia file does not exist, creating it."); try { nomediaFile.createNewFile(); } catch (IOException e) { Log.e(RageFacesApp.TAG, "Could not create .nomedia file", e); mMessageView.setText(R.string.err_loading); return false; } } File picturesDir = new File(Environment.getExternalStorageDirectory(), "Pictures/"); if (!picturesDir.exists()) { Log.d(RageFacesApp.TAG, "Pictures media directory does not exist, creating it."); picturesDir.mkdir(); } File publicRageDir = getPublicRageDir(); if (!publicRageDir.exists()) { Log.d(RageFacesApp.TAG, "Public rage face directory does not exist, creating it."); publicRageDir.mkdir(); } return true; } // Loads a rage face to the SD card, if it is not already there // Returns the URI for it private Uri loadRageFace(String name, boolean isPublic) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(mContext, getString(R.string.err_sd_not_mounted), Toast.LENGTH_LONG).show(); return null; } // Just in case, can't hurt. loadRageFacesDir(); File rageDir = (isPublic) ? getPublicRageDir() : getRageDir(); File rageFaceFile = new File(rageDir, name + ".png"); if (!rageFaceFile.exists()) { // File doesn't exist, copy it in try { RawRetriever retriever = (RawRetriever) mAdapter; InputStream in = mResources.openRawResource(retriever.getRawResourceId(name)); OutputStream out = new FileOutputStream(rageFaceFile); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } out.close(); in.close(); } catch (IOException e) { Log.e(RageFacesApp.TAG, "Could not copy ragefaces file " + name + ".png", e); Toast.makeText(mContext, getString(R.string.err_load_face), Toast.LENGTH_LONG).show(); return null; } } // If this was loaded to be public, do a media scan now to load it into the gallery if (isPublic) { RageFaceMediaScanner mediaScanner = new RageFaceMediaScanner(this, rageFaceFile.getAbsolutePath()); mediaScanner.doScan(); } return Uri.fromFile(rageFaceFile); } private File getRageDir() { return new File(Environment.getExternalStorageDirectory(), RAGE_DIR); } private File getPublicRageDir() { return new File(Environment.getExternalStorageDirectory(), "Pictures/" + PUBLIC_RAGE_DIR); } /** * This tests to see if there is a SEND_MSG intent. If there is, * it means we're on an asshole HTC Sense machine, and have to give * the user an explicit option to send via Messaging or some other app. * @return */ private boolean hasSenseMessagingApp(Uri rageFaceUri) { Intent dummy = new Intent("android.intent.action.SEND_MSG"); dummy.putExtra(Intent.EXTRA_STREAM, rageFaceUri); dummy.setType("image/png"); PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(dummy, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } private void shareRageFaceSenseMessaging(Uri rageFaceUri) { Intent intent = new Intent("android.intent.action.SEND_MSG"); intent.putExtra(Intent.EXTRA_STREAM, rageFaceUri); intent.setType("image/png"); startActivity(intent); } private void shareRageFace(Uri rageFaceUri) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, rageFaceUri); intent.setType("image/png"); Intent chooser = Intent.createChooser(intent, null); startActivity(chooser); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.picker_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.About: { showDialog(DIALOG_ABOUT); return true; } } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ACTIONS: { // First, determine which items we will show to the user ArrayList<String> items = new ArrayList<String>(); final ArrayList<DialogAction> actions = new ArrayList<DialogAction>(); // Standard share option items.add(getString(R.string.dialog_actions_opt_share)); actions.add(new DialogAction() { public void doAction() { shareRageFace(mRageFaceUri); } }); // If the user has Sense messaging, that option if (hasSenseMessagingApp(mRageFaceUri)) { items.add(getString(R.string.dialog_actions_opt_share_sense)); actions.add(new DialogAction() { public void doAction() { shareRageFaceSenseMessaging(mRageFaceUri); } }); } // View the face full screen items.add(getString(R.string.dialog_actions_opt_view)); actions.add(new DialogAction() { public void doAction() { Intent intent = new Intent(mContext, RageFaceViewerActivity.class); intent.putExtra(RageFaceViewerActivity.EXTRA_FACE_ID, mRageFaceId); startActivity(intent); } }); // Add the face to the gallery items.add(getString(R.string.dialog_actions_opt_add_to_gallery)); actions.add(new DialogAction() { public void doAction() { loadRageFace(mRageFaceName, true); } }); Builder builder = new Builder(this); builder.setTitle(R.string.dialog_actions_title); builder.setItems(items.toArray(new String[0]), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { actions.get(which).doAction(); removeDialog(DIALOG_ACTIONS); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_ACTIONS); } }); return builder.create(); } case DIALOG_FILTER: { Builder builder = new Builder(this); builder.setTitle(R.string.dialog_filter_title); builder.setItems(mCategoryNames, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { filter(mCategoryIds[which]); dismissDialog(DIALOG_FILTER); } }); builder.setNeutralButton(R.string.dialog_filter_clear, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { clearFilter(); } }); builder.setNegativeButton(android.R.string.cancel, null); return builder.create(); } case DIALOG_ABOUT: // Try to get the version name String versionName; try { PackageManager pm = getPackageManager(); PackageInfo pi = pm.getPackageInfo("com.idunnolol.ragefaces", 0); versionName = pi.versionName; } catch (Exception e) { // PackageManager is traditionally wonky, need to accept all exceptions here. Log.w(RageFacesApp.TAG, "Couldn't get package info in order to show version #!", e); versionName = ""; } Builder builder = new Builder(this); builder.setMessage(getString(R.string.about_msg, versionName)); builder.setNeutralButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(DIALOG_ABOUT); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_ABOUT); } }); return builder.create(); } return super.onCreateDialog(id); } public void clearFilter() { RageFaceDbAdapter adapter = (RageFaceDbAdapter) mAdapter; adapter.filter(null); } public void filter(int category) { List<Integer> filteredCategories = new ArrayList<Integer>(); filteredCategories.add(category); RageFaceDbAdapter adapter = (RageFaceDbAdapter) mAdapter; adapter.filter(filteredCategories); } // This is for making it easier to associate each dialog option with an action private interface DialogAction { public void doAction(); } }
package com.jaeksoft.searchlib.result; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import com.jaeksoft.searchlib.SearchLibException; import com.jaeksoft.searchlib.function.expression.SyntaxError; import com.jaeksoft.searchlib.index.ReaderLocal; import com.jaeksoft.searchlib.query.ParseException; import com.jaeksoft.searchlib.request.RequestInterfaces; import com.jaeksoft.searchlib.request.ReturnField; import com.jaeksoft.searchlib.request.SearchRequest; import com.jaeksoft.searchlib.result.collector.CollapseDocInterface; import com.jaeksoft.searchlib.result.collector.DocIdInterface; import com.jaeksoft.searchlib.result.collector.ScoreDocInterface; import com.jaeksoft.searchlib.schema.AbstractField; import com.jaeksoft.searchlib.schema.FieldValue; import com.jaeksoft.searchlib.schema.FieldValueItem; import com.jaeksoft.searchlib.schema.FieldValueOriginEnum; import com.jaeksoft.searchlib.snippet.SnippetField; import com.jaeksoft.searchlib.snippet.SnippetFieldValue; import com.jaeksoft.searchlib.util.Timer; public class ResultDocument { final private Map<String, FieldValue> returnFields; final private Map<String, SnippetFieldValue> snippetFields; final private int docId; public ResultDocument(SearchRequest searchRequest, TreeSet<String> fieldSet, int docId, ReaderLocal reader, Timer timer) throws IOException, ParseException, SyntaxError, SearchLibException { this.docId = docId; returnFields = new TreeMap<String, FieldValue>(); snippetFields = new TreeMap<String, SnippetFieldValue>(); Map<String, FieldValue> documentFields = reader.getDocumentFields( docId, fieldSet, timer); for (ReturnField field : searchRequest.getReturnFieldList()) { String fieldName = field.getName(); FieldValue fieldValue = documentFields.get(fieldName); if (fieldValue != null) returnFields.put(fieldName, fieldValue); } for (SnippetField field : searchRequest.getSnippetFieldList()) { String fieldName = field.getName(); field.initSearchTerms(searchRequest); List<FieldValueItem> snippets = new ArrayList<FieldValueItem>(); boolean isSnippet = false; FieldValue fieldValue = documentFields.get(fieldName); if (fieldValue != null) field.getSnippets(docId, reader, fieldValue.getValueArray(), snippets); if (snippets.size() == 0) snippets.add(new FieldValueItem(FieldValueOriginEnum.SNIPPET, "")); SnippetFieldValue snippetFieldValue = new SnippetFieldValue( fieldName, snippets, isSnippet); snippetFields.put(fieldName, snippetFieldValue); } } public ResultDocument(RequestInterfaces.ReturnedFieldInterface rfiRequest, TreeSet<String> fieldSet, int docId, ReaderLocal reader, Timer timer) throws IOException, ParseException, SyntaxError { this.docId = docId; returnFields = reader.getDocumentFields(docId, fieldSet, timer); snippetFields = new TreeMap<String, SnippetFieldValue>(); } public static <T> List<T> toList(Map<String, T> map) { List<T> list = new ArrayList<T>(0); for (T fv : map.values()) list.add(fv); return list; } public Map<String, FieldValue> getReturnFields() { return returnFields; } public Map<String, SnippetFieldValue> getSnippetFields() { return snippetFields; } public FieldValueItem[] getValueArray(AbstractField<?> field) { if (field == null) return null; return getValueArray(field.getName()); } public FieldValueItem[] getValueArray(String fieldName) { if (fieldName == null) return null; FieldValue fieldValue = returnFields.get(fieldName); if (fieldValue == null) return null; return fieldValue.getValueArray(); } public String getValueContent(AbstractField<?> field, int pos) { FieldValueItem[] values = getValueArray(field); if (values == null) return null; if (pos >= values.length) return null; return values[pos].getValue(); } public String getValueContent(String fieldName, int pos) { FieldValue field = returnFields.get(fieldName); if (field == null) return null; return getValueContent(field, pos); } final public FieldValueItem[] getSnippetArray(SnippetField field) { if (field == null) return null; return getSnippetArray(field.getName()); } final public FieldValueItem[] getSnippetValue(SnippetField field) { if (field == null) return null; return getSnippetArray(field.getName()); } final public FieldValueItem[] getSnippetArray(String fieldName) { SnippetFieldValue fieldValue = snippetFields.get(fieldName); if (fieldValue == null) return null; return fieldValue.getValueArray(); } public FieldValueItem[] getSnippetList(String fieldName) { SnippetFieldValue snippetFieldValue = snippetFields.get(fieldName); if (snippetFieldValue == null) return null; return snippetFieldValue.getValueArray(); } public FieldValueItem[] getSnippetList(AbstractField<?> field) { if (field == null) return null; return getSnippetList(field.getName()); } public FieldValueItem getSnippet(String fieldName, int pos) { FieldValueItem[] values = getSnippetArray(fieldName); if (values == null) return null; if (pos >= values.length) return null; return values[pos]; } public boolean isHighlighted(String fieldName) { return snippetFields.get(fieldName).isHighlighted(); } public void appendIfStringDoesNotExist(ResultDocument rd) { for (FieldValue newFieldValue : rd.returnFields.values()) { String fieldName = newFieldValue.getName(); FieldValue fieldValue = returnFields.get(fieldName); if (fieldValue == null) returnFields.put(fieldName, fieldValue); else fieldValue.addIfStringDoesNotExist(newFieldValue .getValueArray()); } for (SnippetFieldValue newFieldValue : rd.snippetFields.values()) { String fieldName = newFieldValue.getName(); SnippetFieldValue fieldValue = snippetFields.get(fieldName); if (fieldValue == null) snippetFields.put(fieldName, fieldValue); else fieldValue.addIfStringDoesNotExist(newFieldValue .getValueArray()); } } final public static float getScore(DocIdInterface docs, int pos) { if (docs == null) return 0; if (!(docs instanceof ScoreDocInterface)) return 0; return ((ScoreDocInterface) docs).getScores()[pos]; } final public static int getCollapseCount(DocIdInterface docs, int pos) { if (docs == null) return 0; if (!(docs instanceof CollapseDocInterface)) return 0; return ((CollapseDocInterface) docs).getCollapseCounts()[pos]; } public int getDocId() { return docId; } }
package com.chasehaddleton.smartalarmclock; import com.chasehaddleton.smartalarmclock.UI.TimeUpdate; import com.chasehaddleton.smartalarmclock.UI.WeatherUpdate; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class SmartAlarmClock { public static void main(String[] args) { Runnable timeUpdate = new TimeUpdate(); Runnable weatherUpdate = new WeatherUpdate("Toronto"); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(timeUpdate, 0, 1, TimeUnit.MINUTES); executor.scheduleAtFixedRate(weatherUpdate, 0, 30, TimeUnit.MINUTES); } }
package com.jcwhatever.bukkit.rental.region; import com.jcwhatever.bukkit.generic.file.GenericsByteReader; import com.jcwhatever.bukkit.generic.file.GenericsByteWriter; import com.jcwhatever.bukkit.generic.pathing.InteriorFinder; import com.jcwhatever.bukkit.generic.pathing.InteriorFinder.InteriorResults; import com.jcwhatever.bukkit.generic.regions.BuildMethod; import com.jcwhatever.bukkit.generic.regions.RestorableRegion; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.DateUtils; import com.jcwhatever.bukkit.generic.utils.LocationUtils; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.rental.BillCollector; import com.jcwhatever.bukkit.rental.Msg; import com.jcwhatever.bukkit.rental.RentalRooms; import com.jcwhatever.bukkit.rental.Tenant; import com.jcwhatever.bukkit.rental.events.RentMoveInEvent; import com.jcwhatever.bukkit.rental.events.RentMoveOutEvent; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; public class RentRegion extends RestorableRegion { private Tenant _tenant; private Set<Location> _tenantArea; private boolean _isEditModeOn = false; private Date _rentExpiration = null; private FriendManager _friendManager; private static final int INTERIOR_FILE_VERSION = 1; IDataNode _tenantInfo; public RentRegion(String name, IDataNode dataNode) { super(RentalRooms.getInstance(), name, dataNode); PreCon.notNull(dataNode); _tenantArea = new HashSet<Location>(100); _tenantInfo = dataNode.getNode("tenant"); loadSettings(); loadInterior(); _friendManager = new FriendManager(this, dataNode.getNode("friends")); } public FriendManager getFriendManager() { return _friendManager; } public void setPayed() { BillCollector billCollector = RentalRooms.getInstance().getBillCollector(); _rentExpiration = _rentExpiration == null ? org.apache.commons.lang.time.DateUtils.addDays(new Date(), billCollector.getRentCycle()) : org.apache.commons.lang.time.DateUtils.addDays(_rentExpiration, billCollector.getRentCycle()); SimpleDateFormat dateFormat = new SimpleDateFormat(); getDataNode().set("rent-expiration", dateFormat.format(_rentExpiration)); getDataNode().saveAsync(null); } public Date getExpirationDate() { return _rentExpiration; } public String getFormattedExpiration() { return DateUtils.format(getExpirationDate(), RentalRooms.DATE_FORMAT); } public boolean isEditModeOn() { return _isEditModeOn; } public void setIsEditModeOn(boolean isEditModeOn) { _isEditModeOn = isEditModeOn; } @Override protected String getFilePrefix() { return "rent." + getName(); } @Override public boolean setOwner(UUID ownerId) { if (_tenant != null) { evict(); } if (!super.setOwner(ownerId)) return false; _tenant = Tenant.add(ownerId, this); RentMoveInEvent.callEvent(this, _tenant); return true; } public void setTenant(Player p) { setOwner(p.getUniqueId()); } public void setTenant(UUID playerId) { setOwner(playerId); } public boolean hasTenant() { return _tenant != null; } public Tenant getTenant() { return _tenant; } public void evict() { super.setOwner(null); Tenant oldTenant = _tenant; _tenant = null; if (this.canRestore()) { try { this.restoreData(BuildMethod.PERFORMANCE); } catch (IOException e) { e.printStackTrace(); } } _rentExpiration = null; //noinspection ConstantConditions getDataNode().set("rent-expiration", null); getDataNode().saveAsync(null); RentMoveOutEvent.callEvent(this, oldTenant); } public int getRentSpaceVolume() { return _tenantArea.size(); } public boolean isTenantArea(Location location) { return _tenantArea.contains(location); } public boolean canInteract(Player p, Location location) { return canInteract(p.getUniqueId(), location); } public boolean canInteract(UUID playerId, Location location) { if (_isEditModeOn) return true; location = LocationUtils.getBlockLocation(location); if (_tenant == null || playerId == null || location == null || !isDefined()) return false; // tenant equals method works with UUID's return (_tenant.equals(playerId) || _friendManager.hasFriend(playerId)) && _tenantArea.contains(location); } public boolean isTenantOrFriend(Player p) { return isTenantOrFriend(p.getUniqueId()); } public boolean isTenantOrFriend(UUID playerId) { return _tenant != null && (_tenant.equals(playerId) || _friendManager.hasFriend(playerId)); } public int addInterior(Location start) { InteriorFinder finder = new InteriorFinder(); InteriorResults results = finder.searchInterior(start, this); Set<Location> interior = results.getNodes(); _tenantArea.addAll(interior); saveInterior(); return interior.size(); } public void clearInterior() { _tenantArea.clear(); try { getInteriorFile(true); // delete interior file } catch (IOException e) { e.printStackTrace(); } } private void loadSettings() { UUID tenantId = super.getOwnerId(); if (tenantId == null) return; _tenant = Tenant.add(tenantId, this); _rentExpiration = null; //noinspection ConstantConditions String expiresStr = getDataNode().getString("rent-expiration"); if (expiresStr != null) { SimpleDateFormat format = new SimpleDateFormat(); try { _rentExpiration = format.parse(expiresStr); } catch (ParseException e) { e.printStackTrace(); } } } private File getInteriorFile(boolean deleteIfExists) throws IOException { File interiorDir = new File(getDataFolder(), "interiors"); if (!interiorDir.exists() && !interiorDir.mkdir()) throw new IOException("Failed to create interior file folder."); File file = new File(interiorDir, getFilePrefix() + ".bin"); if (deleteIfExists && file.exists() && !file.delete()) throw new IOException("Failed to delete interior file."); return file; } private void loadInterior() { File file; try { file = getInteriorFile(false); } catch (IOException e) { e.printStackTrace(); return; } if (!file.exists()) return; Bukkit.getScheduler().runTaskAsynchronously(RentalRooms.getInstance(), new LoadInterior(this, file)); } private void saveInterior() { File file; try { file = getInteriorFile(true); } catch (IOException e) { e.printStackTrace(); return; } Bukkit.getScheduler().runTaskAsynchronously(RentalRooms.getInstance(), new SaveInterior(this, _tenantArea, file)); } private static final class LoadInterior implements Runnable { private RentRegion _region; private List<Location> _interior; private File _file; public LoadInterior(RentRegion region, File file) { _region = region; _file = file; } @Override public void run() { GenericsByteReader reader = null; try { reader = new GenericsByteReader(new FileInputStream(_file)); int fileVersion = reader.getInteger(); if (fileVersion != INTERIOR_FILE_VERSION) { Msg.warning("Failed to load interior file because it's not the correct version: {0}", _file.getName()); return; } reader.getString(); // get region name String worldName = reader.getString(); World world = Bukkit.getWorld(worldName); if (world == null) { Msg.warning("Failed to load interior file because the world it's in ({0}) is not loaded: {1}", worldName, _file.getName()); return; } reader.getLocation(); reader.getLocation(); int size = reader.getInteger(); _interior = new ArrayList<Location>(size + 2); for (int i=0; i < size; i++) { Location loc = reader.getLocation(); if (loc != null) _interior.add(loc); } } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } } Bukkit.getScheduler().scheduleSyncDelayedTask(RentalRooms.getInstance(), new Runnable () { @Override public void run() { _region._tenantArea.clear(); _region._tenantArea.addAll(_interior); } }); } } private static final class SaveInterior implements Runnable { private RentRegion _region; private List<Location> _interior; private File _file; public SaveInterior(RentRegion region, Set<Location> interior, File file) { _region = region; _interior = new ArrayList<Location>(interior); _file = file; } @Override public void run() { GenericsByteWriter writer = null; try { _file.createNewFile(); writer = new GenericsByteWriter(new FileOutputStream(_file)); writer.write(INTERIOR_FILE_VERSION); writer.write(_region.getName()); writer.write(_region.getWorld().getName()); writer.write(_region.getP1()); writer.write(_region.getP2()); writer.write(_interior.size()); for (Location loc : _interior) { writer.write(loc); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
// $Id: ClientManager.java,v 1.32 2003/07/22 02:50:49 mdb Exp $ package com.threerings.presents.server; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import com.samskivert.util.IntervalManager; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.data.ClientObject; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.AuthResponse; import com.threerings.presents.net.Credentials; import com.threerings.presents.server.net.*; import com.threerings.presents.server.util.SafeInterval; /** * The client manager is responsible for managing the clients (surprise, * surprise) which are slightly more than just connections. Clients * persist in the absence of connections in case a user goes bye bye * unintentionally and wants to reconnect and continue their session. * * <p> The client manager operates with thread safety because it is called * both from the conmgr thread (to notify of connections showing up or * going away) and from the dobjmgr thread (when clients are given the * boot for application-defined reasons). */ public class ClientManager implements ConnectionObserver, PresentsServer.Reporter, PresentsServer.Shutdowner { /** * Used by {@link #applyToClient}. */ public static interface ClientOp { /** * Called with the resolved client object. */ public void apply (ClientObject clobj); /** * Called if the client resolution fails. */ public void resolutionFailed (Exception e); } /** * Constructs a client manager that will interact with the supplied * connection manager. */ public ClientManager (ConnectionManager conmgr) { // register ourselves as a connection observer conmgr.addConnectionObserver(this); // start up an interval that will check for expired clients and // flush them from the bowels of the server IntervalManager.register(new SafeInterval(PresentsServer.omgr) { public void run () { flushClients(); } }, CLIENT_FLUSH_INTERVAL, null, true); // register as a "state of server" reporter and a shutdowner PresentsServer.registerReporter(this); PresentsServer.registerShutdowner(this); } // documentation inherited from interface public void shutdown () { Log.info("Client manager shutting down " + "[ccount=" + _usermap.size() + "]."); // inform all of our clients that they are being shut down for (Iterator iter = _usermap.values().iterator(); iter.hasNext(); ) { PresentsClient pc = (PresentsClient)iter.next(); try { pc.shutdown(); } catch (Exception e) { Log.warning("Client choked in shutdonw() [client=" + StringUtil.safeToString(pc) + "]."); Log.logStackTrace(e); } } } /** * Instructs the client manager to construct instances of this derived * class of {@link PresentsClient} to managed newly accepted client * connections. */ public void setClientClass (Class clientClass) { // sanity check if (!PresentsClient.class.isAssignableFrom(clientClass)) { Log.warning("Requested to use client class that does not " + "derive from PresentsClient " + "[class=" + clientClass.getName() + "]."); return; } // make a note of it _clientClass = clientClass; } /** * Instructs the client to use instances of this {@link * ClientResolver} derived class when resolving clients in preparation * for starting a client session. */ public void setClientResolverClass (Class clrClass) { // sanity check if (!ClientResolver.class.isAssignableFrom(clrClass)) { Log.warning("Requested to use client resolver class that does " + "not derive from ClientResolver " + "[class=" + clrClass.getName() + "]."); } else { // make a note of it _clrClass = clrClass; } } /** * Enumerates all active client objects. */ public Iterator enumerateClientObjects () { return _objmap.values().iterator(); } /** * Returns the client instance that manages the client session for the * specified authentication username or null if that client is not * currently connected to the server. */ public PresentsClient getClient (String authUsername) { return (PresentsClient)_usermap.get(authUsername.toLowerCase()); } /** * Returns the client object associated with the specified username. * This will return null unless the client object is resolved for some * reason (like they are logged on). */ public ClientObject getClientObject (String username) { return (ClientObject)_objmap.get(toKey(username)); } /** * We convert usernames to lower case in the username to client object * mapping so that we can pass arbitrarily cased usernames (like those * that might be typed in by a "user") straight on through. */ protected final String toKey (String username) { return username.toLowerCase(); } /** * Resolves the specified client, applies the supplied client * operation to them and releases the client. */ public void applyToClient (String username, ClientOp clop) { resolveClientObject(username, new ClientOpResolver(clop)); } /** * Requests that the client object for the specified user be resolved. * If the client object is already resolved, the request will be * processed immediately, otherwise the appropriate client object will * be instantiated and populated by the registered client resolver * (which may involve talking to databases). <em>Note:</em> this * <b>must</b> be paired with a call to {@link #releaseClientObject} * when the caller is finished with the client object. */ public synchronized void resolveClientObject ( String username, ClientResolutionListener listener) { // look to see if the client object is already resolved String key = toKey(username); ClientObject clobj = (ClientObject)_objmap.get(key); if (clobj != null) { clobj.reference(); listener.clientResolved(username, clobj); return; } // look to see if it's currently being resolved ClientResolver clr = (ClientResolver)_penders.get(key); if (clr != null) { // throw this guy onto the bandwagon clr.addResolutionListener(listener); return; } try { // create a client resolver instance which will create our // client object, populate it and notify the listeners clr = (ClientResolver)_clrClass.newInstance(); clr.init(username); clr.addResolutionListener(listener); // the dobject manager which starts the whole business off PresentsServer.omgr.createObject(clr.getClientObjectClass(), clr); } catch (Exception e) { // let the listener know that we're hosed listener.resolutionFailed(username, e); } } /** * Called by the {@link ClientResolver} once a client object has been * resolved. */ protected synchronized void mapClientObject ( String username, ClientObject clobj) { // stuff the object into the mapping table String key = toKey(username); _objmap.put(key, clobj); // and remove the resolution listener _penders.remove(key); } /** * Releases a client object that was obtained via a call to {@link * #resolveClientObject}. If this caller is the last reference, the * object will be flushed and destroyed. */ public void releaseClientObject (String username) { String key = toKey(username); ClientObject clobj = (ClientObject)_objmap.get(key); if (clobj == null) { Log.warning("Requested to release unmapped client object " + "[username=" + username + "]."); Thread.dumpStack(); return; } // decrement the reference count and stop here if there are // remaining references if (clobj.release()) { return; } Log.debug("Destroying client " + clobj.who() + "."); // we're all clear to go; remove the mapping _objmap.remove(key); // and destroy the object itself PresentsServer.omgr.destroyObject(clobj.getOid()); } // documentation inherited public synchronized void connectionEstablished ( Connection conn, AuthRequest req, AuthResponse rsp) { Credentials creds = req.getCredentials(); String username = creds.getUsername().toLowerCase(); // see if a client is already registered with these credentials PresentsClient client = getClient(username); if (client != null) { Log.info("Resuming session [username=" + username + ", conn=" + conn + "]."); client.resumeSession(conn); } else { Log.info("Session initiated [username=" + username + ", conn=" + conn + "]."); // create a new client and stick'em in the table try { // create a client and start up its session client = (PresentsClient)_clientClass.newInstance(); client.startSession(this, creds, conn); // map their client instance _usermap.put(username, client); } catch (Exception e) { Log.warning("Failed to instantiate client instance to " + "manage new client connection '" + conn + "'."); Log.logStackTrace(e); } } // map this connection to this client _conmap.put(conn, client); } // documentation inherited public synchronized void connectionFailed ( Connection conn, IOException fault) { // remove the client from the connection map PresentsClient client = (PresentsClient)_conmap.remove(conn); if (client != null) { Log.info("Unmapped failed client [client=" + client + ", conn=" + conn + ", fault=" + fault + "]."); // let the client know the connection went away client.wasUnmapped(); // and let the client know things went haywire client.connectionFailed(fault); } else { Log.info("Unmapped connection failed? [conn=" + conn + ", fault=" + fault + "]."); Thread.dumpStack(); } } // documentation inherited public synchronized void connectionClosed (Connection conn) { // remove the client from the connection map PresentsClient client = (PresentsClient)_conmap.remove(conn); if (client != null) { Log.debug("Unmapped client [client=" + client + ", conn=" + conn + "]."); // let the client know the connection went away client.wasUnmapped(); } else { Log.info("Closed unmapped connection '" + conn + "'. " + "Client probably not yet authenticated."); } } /** * Returns the number of client sessions (some may be disconnected). */ public int getClientCount () { return _usermap.size(); } /** * Returns the number of connected clients. */ public int getConnectionCount () { return _conmap.size(); } // documentation inherited from interface PresentsServer.Reporter public void appendReport (StringBuffer report, long now, long sinceLast) { report.append("* presents.ClientManager:\n"); report.append("- Sessions: "); report.append(_usermap.size()).append(" total, "); report.append(_conmap.size()).append(" connected, "); report.append(_penders.size()).append(" pending\n"); report.append("- Mapped users: ").append(_objmap.size()).append("\n"); } /** * Called by the client instance when the client requests a logoff. * This is called from the conmgr thread. */ synchronized void clientDidEndSession (PresentsClient client) { Credentials creds = client.getCredentials(); String username = client.getUsername(); // remove the client from the username map PresentsClient rc = (PresentsClient) _usermap.remove(creds.getUsername().toLowerCase()); // sanity check just because we can if (rc == null) { Log.warning("Unregistered client ended session " + client + "."); Thread.dumpStack(); } else if (rc != client) { Log.warning("Different clients with same username!? " + "[c1=" + rc + ", c2=" + client + "]."); } else { Log.info("Ending session " + client + "."); } } /** * Called once per minute to check for clients that have been * disconnected too long and forcibly end their sessions. */ protected void flushClients () { ArrayList victims = null; long now = System.currentTimeMillis(); // first build a list of our victims (we can't flush clients // directly while iterating due to risk of a // ConcurrentModificationException) Iterator iter = _usermap.values().iterator(); while (iter.hasNext()) { PresentsClient client = (PresentsClient)iter.next(); if (client.checkExpired(now)) { if (victims == null) { victims = new ArrayList(); } victims.add(client); } } if (victims != null) { for (int ii = 0; ii < victims.size(); ii++) { PresentsClient client = (PresentsClient)victims.get(ii); Log.info("Client expired, ending session [client=" + client + ", dtime=" + (now-client.getNetworkStamp()) + "ms]."); client.endSession(); } } } /** Used by {@link #applyToClient}. */ protected class ClientOpResolver implements ClientResolutionListener { public ClientOpResolver (ClientOp clop) { _clop = clop; } // documentation inherited from interface public void clientResolved (String username, ClientObject clobj) { try { _clop.apply(clobj); } catch (Exception e) { Log.warning("Client op failed [username=" + username + ", clop=" + _clop + "]."); Log.logStackTrace(e); } finally { releaseClientObject(username); } } // documentation inherited from interface public void resolutionFailed (String username, Exception reason) { _clop.resolutionFailed(reason); } protected ClientOp _clop; } /** A mapping from auth username to client instances. */ protected HashMap _usermap = new HashMap(); /** A mapping from connections to client instances. */ protected HashMap _conmap = new HashMap(); /** A mapping from usernames to client object instances. */ protected HashMap _objmap = new HashMap(); /** A mapping of pending client resolvers. */ protected HashMap _penders = new HashMap(); /** A set containing the usernames of all locked clients. */ protected HashSet _locks = new HashSet(); /** The client class in use. */ protected Class _clientClass = PresentsClient.class; /** The client resolver class in use. */ protected Class _clrClass = ClientResolver.class; /** The frequency with which we check for expired clients. */ protected static final long CLIENT_FLUSH_INTERVAL = 60 * 1000L; }
package com.jetbrains.ther.parsing; import com.intellij.lang.PsiBuilder; import com.intellij.openapi.diagnostic.Logger; import com.jetbrains.ther.lexer.TheRTokenTypes; import org.jetbrains.annotations.NotNull; public class TheRFunctionParsing extends Parsing { private static final Logger LOG = Logger.getInstance(TheRFunctionParsing.class.getName()); public TheRFunctionParsing(@NotNull final TheRParsingContext context) { super(context); } public void parseFunctionDeclaration() { LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.FUNCTION_KEYWORD); final PsiBuilder.Marker functionMarker = myBuilder.mark(); myBuilder.advanceLexer(); parseParameterList(); getStatementParser().parseBlock(); functionMarker.done(TheRElementTypes.FUNCTION_DECLARATION); } private void parseParameterList() { final PsiBuilder.Marker parameterList = myBuilder.mark(); if (myBuilder.getTokenType() != TheRTokenTypes.LPAR) { parameterList.rollbackTo(); myBuilder.error("( expected"); return; } else { myBuilder.advanceLexer(); } boolean first = true; while (myBuilder.getTokenType() != TheRTokenTypes.RPAR) { if (first) { first = false; } else { if (myBuilder.getTokenType() == TheRTokenTypes.COMMA) { myBuilder.advanceLexer(); } else { myBuilder.error(", or ) expected"); break; } } final PsiBuilder.Marker parameter = myBuilder.mark(); if (myBuilder.getTokenType() == TheRTokenTypes.IDENTIFIER) { myBuilder.advanceLexer(); if (matchToken(TheRTokenTypes.EQ)) { if (!getExpressionParser().parseExpression()) { PsiBuilder.Marker invalidElements = myBuilder.mark(); while(!atToken(TheRTokenTypes.COMMA)) { myBuilder.advanceLexer(); } invalidElements.error(EXPRESSION_EXPECTED); } } parameter.done(TheRElementTypes.PARAMETER); } else { myBuilder.error("parameter name expected"); parameter.rollbackTo(); } } if (myBuilder.getTokenType() == TheRTokenTypes.RPAR) { myBuilder.advanceLexer(); } parameterList.done(TheRElementTypes.PARAMETER_LIST); } }
package org.apache.commons.dbcp; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.List; import java.util.Map; /** * A base delegating implementation of {@link Connection}. * <p> * All of the methods from the {@link Connection} interface * simply check to see that the {@link Connection} is active, * and call the corresponding method on the "delegate" * provided in my constructor. * <p> * Extends AbandonedTrace to implement Connection tracking and * logging of code which created the Connection. Tracking the * Connection ensures that the AbandonedObjectPool can close * this connection and recycle it if its pool of connections * is nearing exhaustion and this connection's last usage is * older than the removeAbandonedTimeout. * * @author Rodney Waldhoff * @author Glenn L. Nielsen * @author James House (<a href="mailto:james@interobjective.com">james@interobjective.com</a>) * @version $Id: DelegatingConnection.java,v 1.14 2003/08/13 14:46:28 dirkv Exp $ */ public class DelegatingConnection extends AbandonedTrace implements Connection { /** My delegate {@link Connection}. */ protected Connection _conn = null; protected boolean _closed = false; /** * Create a wrapper for the Connectin which traces this * Connection in the AbandonedObjectPool. * * @param c the {@link Connection} to delegate all calls to. */ public DelegatingConnection(Connection c) { super(); _conn = c; } /** * Create a wrapper for the Connection which traces * the Statements created so that any unclosed Statements * can be closed when this Connection is closed. * * @param Connection the {@link Connection} to delegate all calls to. * @param AbandonedConfig the configuration for tracing abandoned objects * @deprecated AbandonedConfig is now deprecated. */ public DelegatingConnection(Connection c, AbandonedConfig config) { super(config); _conn = c; } /** * Returns my underlying {@link Connection}. * @return my underlying {@link Connection}. */ public Connection getDelegate() { return _conn; } public boolean equals(Object obj) { Connection delegate = getInnermostDelegate(); if (delegate == null) { return false; } if (obj instanceof DelegatingConnection) { DelegatingConnection c = (DelegatingConnection) obj; return delegate.equals(c.getInnermostDelegate()); } else { return delegate.equals(obj); } } public int hashCode() { Object obj = getInnermostDelegate(); if (obj == null) { return 0; } return obj.hashCode(); } /** * If my underlying {@link Connection} is not a * <tt>DelegatingConnection</tt>, returns it, * otherwise recursively invokes this method on * my delegate. * <p> * Hence this method will return the first * delegate that is not a <tt>DelegatingConnection</tt>, * or <tt>null</tt> when no non-<tt>DelegatingConnection</tt> * delegate can be found by transversing this chain. * <p> * This method is useful when you may have nested * <tt>DelegatingConnection</tt>s, and you want to make * sure to obtain a "genuine" {@link Connection}. */ public Connection getInnermostDelegate() { Connection c = _conn; while(c != null && c instanceof DelegatingConnection) { c = ((DelegatingConnection)c).getDelegate(); if(this == c) { return null; } } return c; } /** Sets my delegate. */ public void setDelegate(Connection c) { _conn = c; } /** * Closes the underlying connection, and close * any Statements that were not explicitly closed. */ public void close() throws SQLException { passivate(); _conn.close(); } public Statement createStatement() throws SQLException { checkOpen(); return new DelegatingStatement(this, _conn.createStatement()); } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingStatement (this, _conn.createStatement(resultSetType,resultSetConcurrency)); } public PreparedStatement prepareStatement(String sql) throws SQLException { checkOpen(); return new DelegatingPreparedStatement (this, _conn.prepareStatement(sql)); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingPreparedStatement (this, _conn.prepareStatement (sql,resultSetType,resultSetConcurrency)); } public CallableStatement prepareCall(String sql) throws SQLException { checkOpen(); return new DelegatingCallableStatement(this, _conn.prepareCall(sql)); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingCallableStatement (this, _conn.prepareCall(sql, resultSetType,resultSetConcurrency)); } public void clearWarnings() throws SQLException { checkOpen(); _conn.clearWarnings();} public void commit() throws SQLException { checkOpen(); _conn.commit();} public boolean getAutoCommit() throws SQLException { checkOpen(); return _conn.getAutoCommit();} public String getCatalog() throws SQLException { checkOpen(); return _conn.getCatalog();} public DatabaseMetaData getMetaData() throws SQLException { checkOpen(); return _conn.getMetaData();} public int getTransactionIsolation() throws SQLException { checkOpen(); return _conn.getTransactionIsolation();} public Map getTypeMap() throws SQLException { checkOpen(); return _conn.getTypeMap();} public SQLWarning getWarnings() throws SQLException { checkOpen(); return _conn.getWarnings();} public boolean isClosed() throws SQLException { if(_closed || _conn.isClosed()) { return true; } return false; } public boolean isReadOnly() throws SQLException { checkOpen(); return _conn.isReadOnly();} public String nativeSQL(String sql) throws SQLException { checkOpen(); return _conn.nativeSQL(sql);} public void rollback() throws SQLException { checkOpen(); _conn.rollback();} public void setAutoCommit(boolean autoCommit) throws SQLException { checkOpen(); _conn.setAutoCommit(autoCommit);} public void setCatalog(String catalog) throws SQLException { checkOpen(); _conn.setCatalog(catalog);} public void setReadOnly(boolean readOnly) throws SQLException { checkOpen(); _conn.setReadOnly(readOnly);} public void setTransactionIsolation(int level) throws SQLException { checkOpen(); _conn.setTransactionIsolation(level);} public void setTypeMap(Map map) throws SQLException { checkOpen(); _conn.setTypeMap(map);} protected void checkOpen() throws SQLException { if(_closed) { throw new SQLException("Connection is closed."); } } protected void activate() { _closed = false; setLastUsed(); if(_conn instanceof DelegatingConnection) { ((DelegatingConnection)_conn).activate(); } } protected void passivate() throws SQLException { _closed = true; // The JDBC spec requires that a Connection close any open // Statement's when it is closed. List statements = getTrace(); if( statements != null) { Statement[] set = new Statement[statements.size()]; statements.toArray(set); for (int i = 0; i < set.length; i++) { set[i].close(); } clearTrace(); } setLastUsed(0); if(_conn instanceof DelegatingConnection) { ((DelegatingConnection)_conn).passivate(); } } // Will be commented by the build process on a JDBC 2.0 system /* JDBC_3_ANT_KEY_BEGIN */ public int getHoldability() throws SQLException { checkOpen(); return _conn.getHoldability(); } public void setHoldability(int holdability) throws SQLException { checkOpen(); _conn.setHoldability(holdability); } public java.sql.Savepoint setSavepoint() throws SQLException { checkOpen(); return _conn.setSavepoint(); } public java.sql.Savepoint setSavepoint(String name) throws SQLException { checkOpen(); return _conn.setSavepoint(name); } public void rollback(java.sql.Savepoint savepoint) throws SQLException { checkOpen(); _conn.rollback(savepoint); } public void releaseSavepoint(java.sql.Savepoint savepoint) throws SQLException { checkOpen(); _conn.releaseSavepoint(savepoint); } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingStatement(this, _conn.createStatement( resultSetType, resultSetConcurrency, resultSetHoldability)); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, _conn.prepareStatement( sql, resultSetType, resultSetConcurrency, resultSetHoldability)); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingCallableStatement(this, _conn.prepareCall( sql, resultSetType, resultSetConcurrency, resultSetHoldability)); } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, _conn.prepareStatement( sql, autoGeneratedKeys)); } public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, _conn.prepareStatement( sql, columnIndexes)); } public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, _conn.prepareStatement( sql, columnNames)); } /* JDBC_3_ANT_KEY_END */ }
package com.jme.widget.renderer; import com.jme.image.Texture; import com.jme.renderer.Renderer; import com.jme.scene.state.AlphaState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jme.util.TextureManager; import com.jme.widget.Widget; import com.jme.widget.WidgetRenderer; /** * <code>WidgetAbstractRenderer</code> * @author Gregg Patton * @version $Id: WidgetAbstractRenderer.java,v 1.2 2004-03-05 11:38:14 greggpatton Exp $ */ public abstract class WidgetAbstractRenderer implements WidgetRenderer { public static float LOOK_AND_FEEL_TEXTURE_SIZE = 64; public static float LOOK_AND_FEEL_PIXEL_SIZE = 1f / LOOK_AND_FEEL_TEXTURE_SIZE; private static String IMAGE_DIRECTORY = "jmetest/data/lookandfeel/"; protected Widget widget; protected Renderer renderer; static protected TextureState textureState; static protected AlphaState alphaState; public WidgetAbstractRenderer(Widget w) { super(); widget = w; renderer = DisplaySystem.getDisplaySystem().getRenderer(); if (textureState == null) { textureState = DisplaySystem.getDisplaySystem().getRenderer().getTextureState(); alphaState = DisplaySystem.getDisplaySystem().getRenderer().getAlphaState(); alphaState.setBlendEnabled(true); Texture t = TextureManager.loadTexture( WidgetAbstractRenderer.class.getClassLoader().getResource(IMAGE_DIRECTORY + "DefaultLookAndFeel.png"), Texture.MM_NONE, Texture.MM_NONE, false); t.setApply(Texture.AM_REPLACE); textureState.setTexture(t); } } /** <code>setWidget</code> * @param w * @see com.jme.widget.WidgetRenderer#setWidget(com.jme.widget.Widget) */ public void setWidget(Widget w) { widget = w; } /** <code>getWidget</code> * @return * @see com.jme.widget.WidgetRenderer#getWidget() */ public Widget getWidget() { return widget; } /** * <code>updateCamera</code> * */ protected void updateCamera() { if (renderer != null && renderer.getCamera() != null) { renderer.getCamera().update(); } } }
package org.apache.velocity.anakia; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.input.DefaultJDOMFactory; /** * A customized JDOMFactory for Anakia that produces {@link AnakiaElement} * instances instead of ordinary JDOM {@link Element} instances. * * @author <a href="mailto:szegedia@freemail.hu">Attila Szegedi</a> * @version $Id: AnakiaJDOMFactory.java,v 1.2 2001/10/10 13:43:30 geirm Exp $ */ public class AnakiaJDOMFactory extends DefaultJDOMFactory { public AnakiaJDOMFactory() { } public Element element(String name, Namespace namespace) { return new AnakiaElement(name, namespace); } public Element element(String name) { return new AnakiaElement(name); } public Element element(String name, String uri) { return new AnakiaElement(name, uri); } public Element element(String name, String prefix, String uri) { return new AnakiaElement(name, prefix, uri); } }
package org.apache.velocity.tools.generic; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; /** * Tool for working with {@link Number} in Velocity templates. * It is useful for accessing and * formatting arbitrary {@link Number} objects. Also * the tool can be used to retrieve {@link NumberFormat} instances * or make conversions to and from various number types. * <p><pre> * Example uses: * $myNumber -> 13.55 * $number.format('currency',$myNumber) -> $13.55 * $number.format('integer',$myNumber) -> 13 * * Example toolbox.xml config (if you want to use this with VelocityView): * &lt;tool&gt; * &lt;key&gt;number&lt;/key&gt; * &lt;scope&gt;application&lt;/scope&gt; * &lt;class&gt;org.apache.velocity.tools.generic.NumberTool&lt;/class&gt; * &lt;/tool&gt; * </pre></p> * * <p>This tool is entirely threadsafe, and has no instance members. * It may be used in any scope (request, session, or application). * As such, the methods are highly interconnected, and overriding * key methods provides an easy way to create subclasses that use * a non-default format or locale.</p> * * @author <a href="mailto:nathan@esha.com">Nathan Bubna</a> * @author <a href="mailto:mkienenb@alaska.net">Mike Kienenberger</a> * @since VelocityTools 1.2 */ public class NumberTool { /** * The default format to be used when none is specified. */ public static final String DEFAULT_FORMAT = "default"; private static final int STYLE_NUMBER = 0; private static final int STYLE_CURRENCY = 1; private static final int STYLE_PERCENT = 2; //NOTE: '3' belongs to a non-public "scientific" style private static final int STYLE_INTEGER = 4; /** * Default constructor. */ public NumberTool() { // do nothing } /** * This implementation returns the default locale. Subclasses * may override this to return alternate locales. Please note that * doing so will affect all formatting methods where no locale is * specified in the parameters. * * @return the default {@link Locale} */ public Locale getLocale() { return Locale.getDefault(); } /** * Return the pattern or style to be used for formatting numbers when none * is specified. This implementation gives a 'default' number format. * Subclasses may override this to provide a different default format. * * <p>NOTE: At some point in the future it may be feasible to configure * this value via the toolbox definition, but at present, it is not possible * to specify custom tool configurations there. For now you should just * override this in a subclass to have a different default.</p> */ public String getFormat() { return DEFAULT_FORMAT; } /** * Converts the specified object to a number and formats it according to * the pattern or style returned by {@link #getFormat()}. * * @param obj the number object to be formatted * @return the specified number formatted as a string * @see #format(String format, Object obj, Locale locale) */ public String format(Object obj) { return format(getFormat(), obj); } /** * Converts the specified object to a number and returns * a formatted string representing that number in the locale * returned by {@link #getLocale()}. * * @param format the formatting instructions * @param obj the number object to be formatted * @return a formatted string for this locale representing the specified * number or <code>null</code> if the parameters are invalid * @see #format(String format, Object obj, Locale locale) */ public String format(String format, Object obj) { return format(format, obj, getLocale()); } /** * Converts the specified object to a number and returns * a formatted string representing that number in the specified * {@link Locale}. * * @param format the custom or standard pattern to be used * @param obj the number object to be formatted * @param locale the {@link Locale} to be used when formatting * @return a formatted string representing the specified number or * <code>null</code> if the parameters are invalid */ public String format(String format, Object obj, Locale locale) { Number number = toNumber(obj); NumberFormat nf = getNumberFormat(format, locale); if (number == null || nf == null) { return null; } return nf.format(number); } /** * Returns a {@link NumberFormat} instance for the specified * format and {@link Locale}. If the format specified is a standard * style pattern, then a number instance * will be returned with the number style set to the * specified style. If it is a custom format, then a customized * {@link NumberFormat} will be returned. * * @param format the custom or standard formatting pattern to be used * @param locale the {@link Locale} to be used * @return an instance of {@link NumberFormat} * @see NumberFormat */ public NumberFormat getNumberFormat(String format, Locale locale) { if (format == null) { return null; } NumberFormat nf = null; int style = getStyleAsInt(format); if (style < 0) { // we have a custom format nf = new DecimalFormat(format, new DecimalFormatSymbols(locale)); } else { // we have a standard format nf = getNumberFormat(style, locale); } return nf; } /** * Returns a {@link NumberFormat} instance for the specified * number style and {@link Locale}. * * @param numberStyle the number style (number will be ignored if this is * less than zero or the number style is not recognized) * @param locale the {@link Locale} to be used * @return an instance of {@link NumberFormat} or <code>null</code> * if an instance cannot be constructed with the given * parameters */ protected NumberFormat getNumberFormat(int numberStyle, Locale locale) { try { NumberFormat nf; switch (numberStyle) { case STYLE_NUMBER: nf = NumberFormat.getNumberInstance(locale); break; case STYLE_CURRENCY: nf = NumberFormat.getCurrencyInstance(locale); break; case STYLE_PERCENT: nf = NumberFormat.getPercentInstance(locale); break; case STYLE_INTEGER: nf = getIntegerInstance(locale); break; default: // invalid style was specified, return null nf = null; } return nf; } catch (Exception suppressed) { // let it go... return null; } } /** * Since we wish to continue supporting Java 1.3, * for the present we cannot use Java 1.4's * NumberFormat.getIntegerInstance(Locale) method. * This method mimics that method (at least as of JDK1.4.2_01). * It is private so that it can be removed later * without a deprecation period. */ private NumberFormat getIntegerInstance(Locale locale) { DecimalFormat format = (DecimalFormat)NumberFormat.getNumberInstance(locale); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); return format; } /** * Checks a string to see if it matches one of the standard * NumberFormat style patterns: * NUMBER, CURRENCY, PERCENT, INTEGER, or DEFAULT. * if it does it will return the integer constant for that pattern. * if not, it will return -1. * * @see NumberFormat * @param style the string to be checked * @return the int identifying the style pattern */ protected int getStyleAsInt(String style) { // avoid needlessly running through all the string comparisons if (style == null || style.length() < 6 || style.length() > 8) { return -1; } if (style.equalsIgnoreCase("default")) { //NOTE: java.text.NumberFormat returns "number" instances // as the default (at least in Java 1.3 and 1.4). return STYLE_NUMBER; } if (style.equalsIgnoreCase("number")) { return STYLE_NUMBER; } if (style.equalsIgnoreCase("currency")) { return STYLE_CURRENCY; } if (style.equalsIgnoreCase("percent")) { return STYLE_PERCENT; } if (style.equalsIgnoreCase("integer")) { return STYLE_INTEGER; } // ok, it's not any of the standard patterns return -1; } /** * Converts an object to an instance of {@link Number} using the * format returned by {@link #getFormat()} and the {@link Locale} * returned by {@link #getLocale()} if the object is not already * an instance of Number. * * @param obj the number to convert * @return the object as a {@link Number} or <code>null</code> if no * conversion is possible */ public Number toNumber(Object obj) { return toNumber(getFormat(), obj, getLocale()); } /** * Converts an object to an instance of {@link Number} using the * specified format and the {@link Locale} returned by * {@link #getLocale()} if the object is not already an instance * of Number. * * @param format - the format the number is in * @param obj - the number to convert * @return the object as a {@link Number} or <code>null</code> if no * conversion is possible * @see #toNumber(String format, Object obj, Locale locale) */ public Number toNumber(String format, Object obj) { return toNumber(format, obj, getLocale()); } /** * Converts an object to an instance of {@link Number} using the * specified format and {@link Locale}if the object is not already * an instance of Number. * * @param format - the format the number is in * @param obj - the number to convert * @param locale - the {@link Locale} * @return the object as a {@link Number} or <code>null</code> if no * conversion is possible * @see NumberFormat#parse */ public Number toNumber(String format, Object obj, Locale locale) { if (obj == null) { return null; } if (obj instanceof Number) { return (Number)obj; } try { NumberFormat parser = getNumberFormat(format, locale); return parser.parse(String.valueOf(obj)); } catch (Exception e) { return null; } } }
package org.jivesoftware.sparkimpl.settings; public class JiveInfo { private JiveInfo() { } public static String getVersion() { return "2.0.5"; } public static String getOS() { return System.getProperty("os.name"); } }
import java.util.Scanner; public class ExpectedSalary { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); final int baseBSc = 28000; final int expBSc = 6000; final int baseMSc = 35000; final int expMSc = 5000; final int basePhD = 45000; final int expPhD = 15000; String degrees[] = {"BSc", "MSc", "PhD"}; /* Collect all the user input. */ String userInputs = ""; for(; userInput.hasNext();) { String input = userInput.next(); if(input.equalsIgnoreCase("done")) break; userInputs += input; } Scanner scanner = new Scanner(userInputs); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } }
package com.mebigfatguy.fbcontrib.detect; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.AnnotationEntry; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.GETFIELD; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKEVIRTUAL; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.BasicBlock.InstructionIterator; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; /** * finds fields that are used in a locals only fashion, specifically private fields * that are accessed first in each method with a store vs. a load. */ public class FieldCouldBeLocal extends BytecodeScanningDetector { private final BugReporter bugReporter; private ClassContext clsContext; private Map<String, FieldInfo> localizableFields; private CFG cfg; private ConstantPoolGen cpg; private BitSet visitedBlocks; private Map<String, Set<String>> methodFieldModifiers; private String clsName; /** * constructs a FCBL detector given the reporter to report bugs on. * @param bugReporter the sync of bug reports */ public FieldCouldBeLocal(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * overrides the visitor to collect localizable fields, and then report those that * survive all method checks. * * @param classContext the context object that holds the JavaClass parsed */ @Override public void visitClassContext(ClassContext classContext) { try { localizableFields = new HashMap<String, FieldInfo>(); visitedBlocks = new BitSet(); clsContext = classContext; clsName = clsContext.getJavaClass().getClassName(); JavaClass cls = classContext.getJavaClass(); Field[] fields = cls.getFields(); ConstantPool cp = classContext.getConstantPoolGen().getConstantPool(); for (Field f : fields) { if (!f.isStatic() && !f.isVolatile() && (f.getName().indexOf('$') < 0) && f.isPrivate()) { FieldAnnotation fa = new FieldAnnotation(cls.getClassName(), f.getName(), f.getSignature(), false); boolean hasExternalAnnotation = false; for (AnnotationEntry entry : f.getAnnotationEntries()) { ConstantUtf8 cutf = (ConstantUtf8) cp.getConstant(entry.getTypeIndex()); if (!cutf.getBytes().startsWith("java")) { hasExternalAnnotation = true; break; } } localizableFields.put(f.getName(), new FieldInfo(fa, hasExternalAnnotation)); } } if (localizableFields.size() > 0) { buildMethodFieldModifiers(classContext); super.visitClassContext(classContext); for (FieldInfo fi : localizableFields.values()) { FieldAnnotation fa = fi.getFieldAnnotation(); SourceLineAnnotation sla = fi.getSrcLineAnnotation(); BugInstance bug = new BugInstance(this, "FCBL_FIELD_COULD_BE_LOCAL", NORMAL_PRIORITY) .addClass(this) .addField(fa); if (sla != null) bug.addSourceLine(sla); bugReporter.reportBug(bug); } } } finally { localizableFields = null; visitedBlocks = null; clsContext = null; methodFieldModifiers = null; } } /** * overrides the visitor to navigate basic blocks looking for all first usages of fields, removing * those that are read from first. * * @param obj the context object of the currently parsed method */ @Override public void visitMethod(Method obj) { if (localizableFields.isEmpty()) return; try { cfg = clsContext.getCFG(obj); cpg = cfg.getMethodGen().getConstantPool(); BasicBlock bb = cfg.getEntry(); Set<String> uncheckedFields = new HashSet<String>(localizableFields.keySet()); visitedBlocks.clear(); checkBlock(bb, uncheckedFields); } catch (CFGBuilderException cbe) { localizableFields.clear(); } finally { cfg = null; cpg = null; } } /** * looks for methods that contain a GETFIELD or PUTFIELD opcodes * * @param method the context object of the current method * @return if the class uses synchronization */ public boolean prescreen(Method method) { BitSet bytecodeSet = getClassContext().getBytecodeSet(method); return (bytecodeSet != null) && (bytecodeSet.get(Constants.PUTFIELD) || bytecodeSet.get(Constants.GETFIELD)); } /** * implements the visitor to pass through constructors and static initializers to the * byte code scanning code. These methods are not reported, but are used to build * SourceLineAnnotations for fields, if accessed. * * @param obj the context object of the currently parsed code attribute */ @Override public void visitCode(Code obj) { Method m = getMethod(); if (prescreen(m)) { String methodName = m.getName(); if ("<clinit".equals(methodName) || "<init>".equals(methodName)) super.visitCode(obj); } } /** * implements the visitor to add SourceLineAnnotations for fields in constructors and static * initializers. * * @param seen the opcode of the currently visited instruction */ @Override public void sawOpcode(int seen) { if ((seen == GETFIELD) || (seen == PUTFIELD)) { String fieldName = getNameConstantOperand(); FieldInfo fi = localizableFields.get(fieldName); if (fi != null) { SourceLineAnnotation sla = SourceLineAnnotation.fromVisitedInstruction(this); fi.setSrcLineAnnotation(sla); } } } /** * looks in this basic block for the first access to the fields in uncheckedFields. Once found * the item is removed from uncheckedFields, and removed from localizableFields if the access is * a GETFIELD. If any unchecked fields remain, this method is recursively called on all outgoing edges * of this basic block. * * @param bb this basic block * @param uncheckedFields the list of fields to look for */ private void checkBlock(BasicBlock bb, Set<String> uncheckedFields) { LinkedList<BlockState> toBeProcessed = new LinkedList<BlockState>(); toBeProcessed.add(new BlockState(bb, uncheckedFields)); visitedBlocks.set(bb.getLabel()); while (!toBeProcessed.isEmpty()) { if (localizableFields.isEmpty()) return; BlockState bState = toBeProcessed.removeFirst(); bb = bState.getBasicBlock(); InstructionIterator ii = bb.instructionIterator(); while ((bState.getUncheckedFieldSize() > 0) && ii.hasNext()) { InstructionHandle ih = ii.next(); Instruction ins = ih.getInstruction(); if (ins instanceof FieldInstruction) { FieldInstruction fi = (FieldInstruction) ins; String fieldName = fi.getFieldName(cpg); FieldInfo finfo = localizableFields.get(fieldName); if ((finfo != null) && localizableFields.get(fieldName).hasAnnotation()) { localizableFields.remove(fieldName); } else { boolean justRemoved = bState.removeUncheckedField(fieldName); if (ins instanceof GETFIELD) { if (justRemoved) { localizableFields.remove(fieldName); if (localizableFields.isEmpty()) return; } } else { if (finfo != null) finfo.setSrcLineAnnotation(SourceLineAnnotation.fromVisitedInstruction(clsContext, this, ih.getPosition())); } } } else if (ins instanceof INVOKESPECIAL) { INVOKESPECIAL is = (INVOKESPECIAL) ins; if ("<init>".equals(is.getMethodName(cpg)) && (is.getClassName(cpg).startsWith(clsContext.getJavaClass().getClassName() + "$"))) { localizableFields.clear(); } } else if (ins instanceof INVOKEVIRTUAL) { INVOKEVIRTUAL is = (INVOKEVIRTUAL) ins; if (is.getClassName(cpg).equals(clsName)) { String methodDesc = is.getName(cpg) + is.getSignature(cpg); Set<String> fields = methodFieldModifiers.get(methodDesc); if (fields != null) { for (String field : fields) { localizableFields.remove(field); } } } } } if (bState.getUncheckedFieldSize() > 0) { Iterator<Edge> oei = cfg.outgoingEdgeIterator(bb); while (oei.hasNext()) { Edge e = oei.next(); BasicBlock cb = e.getTarget(); int label = cb.getLabel(); if (!visitedBlocks.get(label)) { toBeProcessed.addLast(new BlockState(cb, bState)); visitedBlocks.set(label); } } } } } /** * builds up the method to field map of what method write to which fields * this is one recursively so that if method A calls method B, and method B * writes to field C, then A modifies F. * * @param classContext the context object of the currently parsed class */ private void buildMethodFieldModifiers(ClassContext classContext) { FieldModifier fm = new FieldModifier(); fm.visitClassContext(classContext); methodFieldModifiers = fm.getMethodFieldModifiers(); } /** * holds information about a field and it's first usage */ private static class FieldInfo { private final FieldAnnotation fieldAnnotation; private SourceLineAnnotation srcLineAnnotation; private boolean hasAnnotation; /** * creates a FieldInfo from an annotation, and assumes no source line information * @param fa the field annotation for this field * @param hasExternalAnnotation the field has a non java based annotation */ public FieldInfo(final FieldAnnotation fa, boolean hasExternalAnnotation) { fieldAnnotation = fa; srcLineAnnotation = null; hasAnnotation = hasExternalAnnotation; } /** * set the source line annotation of first use for this field * @param sla the source line annotation */ public void setSrcLineAnnotation(final SourceLineAnnotation sla) { if (srcLineAnnotation == null) srcLineAnnotation = sla; } /** * get the field annotation for this field * @return the field annotation */ public FieldAnnotation getFieldAnnotation() { return fieldAnnotation; } /** * get the source line annotation for the first use of this field * @return the source line annotation */ public SourceLineAnnotation getSrcLineAnnotation() { return srcLineAnnotation; } /** * gets whether the field has a non java annotation * @return if the field has a non java annotation */ public boolean hasAnnotation() { return hasAnnotation; } } private static class BlockState { private final BasicBlock basicBlock; private Set<String> uncheckedFields; private boolean fieldsAreSharedWithParent; /** * creates a BlockState consisting of the next basic block to parse, * and what fields are to be checked * @param bb the basic block to parse * @param fields the fields to look for first use */ public BlockState(final BasicBlock bb, final Set<String> fields) { basicBlock = bb; uncheckedFields = fields; fieldsAreSharedWithParent = true; } /** * creates a BlockState consisting of the next basic block to parse, * and what fields are to be checked * @param bb the basic block to parse * @param the basic block to copy from */ public BlockState(final BasicBlock bb, BlockState parentBlockState) { basicBlock = bb; uncheckedFields = parentBlockState.uncheckedFields; fieldsAreSharedWithParent = true; } /** * get the basic block to parse * @return the basic block */ public BasicBlock getBasicBlock() { return basicBlock; } /** * returns the number of unchecked fields * @return the number of unchecked fields */ public int getUncheckedFieldSize() { return (uncheckedFields == null) ? 0 : uncheckedFields.size(); } /** * return the field from the set of unchecked fields * if this occurs make a copy of the set on write to reduce memory usage * @return whether the object was removed. */ public boolean removeUncheckedField(String field) { if ((uncheckedFields != null) && uncheckedFields.contains(field)) { if (uncheckedFields.size() == 1) { uncheckedFields = null; fieldsAreSharedWithParent = false; return true; } if (fieldsAreSharedWithParent) { uncheckedFields = new HashSet<String>(uncheckedFields); fieldsAreSharedWithParent = false; uncheckedFields.remove(field); return true; } else { uncheckedFields.remove(field); return true; } } return false; } @Override public String toString() { return basicBlock + "|" + uncheckedFields; } } private static class FieldModifier extends BytecodeScanningDetector { private Map<String, Set<String>> methodCallChain = new HashMap<String, Set<String>>(); private Map<String, Set<String>> mfModifiers = new HashMap<String, Set<String>>(); private String clsName; public Map<String, Set<String>> getMethodFieldModifiers() { Map<String, Set<String>> modifiers = new HashMap<String, Set<String>>(mfModifiers.size()); modifiers.putAll(mfModifiers); for (String method : modifiers.keySet()) { modifiers.put(method, (Set<String>) ((HashSet<String>) modifiers.get(method)).clone()); } boolean modified = true; while (modified) { modified = false; for (Map.Entry<String, Set<String>> entry : methodCallChain.entrySet()) { String methodDesc = entry.getKey(); Set<String> calledMethods = entry.getValue(); for (String calledMethodDesc : calledMethods) { Set<String> fields = mfModifiers.get(calledMethodDesc); if (fields != null) { Set<String> flds = modifiers.get(methodDesc); if (flds == null) { flds = new HashSet<String>(); modifiers.put(methodDesc, flds); } if (flds.addAll(fields)) modified = true; } } } } return modifiers; } @Override public void visitClassContext(ClassContext context) { clsName = context.getJavaClass().getClassName(); super.visitClassContext(context); } @Override public void sawOpcode(int seen) { if (seen == PUTFIELD) { if (clsName.equals(getClassConstantOperand())) { String methodDesc = getMethodName()+getMethodSig(); Set<String> fields = mfModifiers.get(methodDesc); if (fields == null) { fields = new HashSet<String>(); mfModifiers.put(methodDesc, fields); } fields.add(getNameConstantOperand()); } } else if (seen == INVOKEVIRTUAL) { if (clsName.equals(getClassConstantOperand())) { String methodDesc = getMethodName()+getMethodSig(); Set<String> methods = methodCallChain.get(methodDesc); if (methods == null) { methods = new HashSet<String>(); methodCallChain.put(methodDesc, methods); } methods.add(getNameConstantOperand()+getSigConstantOperand()); } } } } }
package com.valkryst.generator; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public final class ConsonantVowelNameGenerator implements NameGenerator { /** The consonants. */ private final String[] consonants; /** The vowels. */ private final String[] vowels; /** * Constructs a new ConsonantVowelNameGenerator. * * @param consonants * The consonants. * * @param vowels * The vowels. */ public ConsonantVowelNameGenerator(final List<String> consonants, final List<String> vowels) { // Ensure lists aren't null: if (consonants == null) { throw new IllegalArgumentException("The list of consonants is null."); } if (vowels == null) { throw new IllegalArgumentException("The list of vowels is null."); } // Ensure lists aren't empty: if (consonants.size() == 0) { throw new IllegalArgumentException("The list of consonants is empty."); } if (vowels.size() == 0) { throw new IllegalArgumentException("The list of vowels is empty."); } this.consonants = consonants.toArray(new String[consonants.size()]); this.vowels = vowels.toArray(new String[vowels.size()]); } @Override public String generateName(int length) { if (length < 2) { length = 2; } final StringBuilder sb = new StringBuilder(); while (sb.length() < length) { if (length % 2 == 0) { sb.append(vowels[ThreadLocalRandom.current().nextInt(vowels.length)]); } else { sb.append(consonants[ThreadLocalRandom.current().nextInt(consonants.length)]); } } return sb.substring(0, length); } }
package com.vinsol.sms_scheduler.activities; import java.io.InputStream; import java.util.ArrayList; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import com.vinsol.sms_scheduler.R; import com.vinsol.sms_scheduler.models.MyContact; import com.vinsol.sms_scheduler.utils.Log; public class SplashActivity extends Activity { static ArrayList<MyContact> contactsList = new ArrayList<MyContact>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_layout); ContactsAsync contactsAsync = new ContactsAsync(); contactsAsync.execute(); } class ContactsAsync extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... params) { loadContactsData(); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Intent intent = new Intent(SplashActivity.this, SmsSchedulerExplActivity.class); //intent.putExtra("ORIGIN", "new"); SplashActivity.this.finish(); startActivity(intent); } } public void loadContactsData(){ // SAZWQA: NR // contactsList.clear(); long t1 = System.currentTimeMillis(); ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if(cursor.moveToFirst()){ do{ if(!(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)).equals("0"))){ String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + id, null, null); if(phones.moveToFirst()){ MyContact contact = new MyContact(); contact.content_uri_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); contact.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); // SAZWQA: Why? // contact.number = " "; contact.number = phones.getString(phones.getColumnIndex(Phone.NUMBER)); Cursor cur = managedQuery(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID}, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID + "=" + contact.content_uri_id, null, null); if(cur.moveToFirst()){ do{ // SAZWQA: Should we add a rule that if GROUP_ROW_ID == 0 or it's equal to phone no. don't ADD it? contact.groupRowId.add(cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID))); }while(cur.moveToNext()); } Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contact.content_uri_id)); InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri); try{ contact.image = BitmapFactory.decodeStream(input); contact.image.getHeight(); } catch (NullPointerException e){ contact.image = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.no_image_thumbnail); } contactsList.add(contact); //Log.i("MSG", contact.groupRowId.size() + ""); } } }while(cursor.moveToNext()); } Log.d("111111111111111111111111111111111"); Log.d("time taken: " + (System.currentTimeMillis() - t1)); Log.d("111111111111111111111111111111111"); } // public void loadContactsData(){ // Uri myUri = ContactsContract.Contacts.CONTENT_URI; // Cursor cursor = managedQuery(myUri, null, null, null, ContactsContract.Contacts.DISPLAY_NAME); // Cursor phCursor; // ContentResolver cr = getContentResolver(); // if(cursor.moveToFirst()){ // Log.i("MSG", "total contacts : " + cursor.getCount()); // String numberString = ""; // while(cursor.moveToNext()){ // if(!(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)).equals("0"))){ // MyContact contact = new MyContact(); // contact.content_uri_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); // String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); // int idInt = Integer.parseInt(contact.content_uri_id); // phCursor = cr.query( // ContactsContract.CommonDataKinds.Phone.CONTENT_URI, // null, // ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", // new String[]{id}, null); // Log.i("MSG", "size of PhCursor : " + phCursor.getCount()); // if(phCursor.moveToFirst()){ // contact.number = phCursor.getString(phCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contact.content_uri_id)); // InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri); // contact.image = BitmapFactory.decodeStream(input); // contact.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); // contactsList.add(contact); // }else{ // //numberString = "Not Available"; }
package java.awt.peer; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import org.videolan.Logger; public class BDFramePeer extends BDComponentPeer implements FramePeer { public BDFramePeer(Frame frame, BDRootWindow rootWindow) { super(frame.getToolkit(), frame); this.rootWindow = rootWindow; } public Rectangle getBoundsPrivate() { return null; } public int getState() { return Frame.NORMAL; } public void setBoundsPrivate(int a, int b, int c, int d) { } public void setMaximizedBounds(Rectangle bounds) { } public void setMenuBar(MenuBar mb) { } public void setResizable(boolean resizeable) { } public void setState(int state) { } public void setTitle(String title) { } // ContainerPeer public void beginLayout() { } public void beginValidate() { } public void endLayout() { } public void endValidate() { } public Insets getInsets() { return insets; } /* java 1.6 only */ public Insets insets() { return getInsets(); } /* java 1.6 only */ public boolean isPaintPending() { return false; } /* java 1.6 only */ public boolean isRestackSupported() { return false; } /* java 1.6 only */ public void restack() { } // WindowPeer public void repositionSecurityWarning() { } public void setAlwaysOnTop(boolean b) { } public void setModalBlocked(Dialog d,boolean b) { } public void setOpacity(float f) { } public void setOpaque(boolean b) { } public void toBack() { } public void toFront() { } public void updateFocusableWindowState() { } public void updateIconImages() { } public void updateMinimumSize() { } public void updateWindow(BufferedImage b) { logger.unimplemented("updateWindow"); } /* java 1.7 ? */ public void updateWindow() { logger.unimplemented("updateWindow"); } /* java 1.6 only */ public boolean requestWindowFocus() { return true; } // ComponentPeer //public Rectangle getBounds() { // return rootWindow.getBounds(); public Graphics getGraphics() { return new BDWindowGraphics(rootWindow); } public Image createImage(int width, int height) { return ((BDToolkit)BDToolkit.getDefaultToolkit()).createImage((Component)null, width, height); } public boolean requestFocus(Component c, boolean a, boolean b, long l, sun.awt.CausedFocusEvent.Cause d) { if (c == null) { return true; } Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new FocusEvent(c, FocusEvent.FOCUS_GAINED)); return true; } public void setVisible(boolean b) { //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new WindowEvent((Frame)component, WindowEvent.WINDOW_ACTIVATED)); if (b == true) { component.paint(getGraphics()); } } public void dispose() { super.dispose(); rootWindow = null; } private BDRootWindow rootWindow; private Insets insets = new Insets(0, 0, 0, 0); private static final Logger logger = Logger.getLogger(BDFramePeer.class.getName()); }
package SW9.presentations; import SW9.HUPPAAL; import SW9.abstractions.Component; import SW9.controllers.ComponentController; import SW9.utility.colors.Color; import SW9.utility.helpers.MouseTrackable; import SW9.utility.helpers.SelectHelper; import SW9.utility.mouse.MouseTracker; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.ListChangeListener; import javafx.fxml.FXMLLoader; import javafx.fxml.JavaFXBuilderFactory; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.layout.*; import javafx.scene.shape.Path; import javafx.scene.shape.Polygon; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import static SW9.presentations.CanvasPresentation.GRID_SIZE; public class ComponentPresentation extends StackPane implements MouseTrackable, SelectHelper.Selectable { public final static double CORNER_SIZE = 4 * GRID_SIZE; public static final double TOOL_BAR_HEIGHT = CORNER_SIZE / 2; private final ComponentController controller; private final List<BiConsumer<Color, Color.Intensity>> updateColorDelegates = new ArrayList<>(); private LocationPresentation initialLocationPresentation = null; private LocationPresentation finalLocationPresentation = null; public ComponentPresentation() { this(new Component()); } public ComponentPresentation(final Component component) { final URL location = this.getClass().getResource("ComponentPresentation.fxml"); final FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(location); fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); try { fxmlLoader.setRoot(this); fxmlLoader.load(location.openStream()); // Set the width and the height of the view to the values in the abstraction setMinWidth(component.getWidth()); setMaxWidth(component.getWidth()); setMinHeight(component.getHeight()); setMaxHeight(component.getHeight()); controller = fxmlLoader.getController(); controller.setComponent(component); initializeDefaultLocationsContainer(); initializeToolbar(); initializeFrame(); initializeInitialLocation(); initializeFinalLocation(); initializeBackground(); initializeName(); BooleanProperty testAdderBoolean = new SimpleBooleanProperty(true); HUPPAAL.getProject().getComponents().addListener(new ListChangeListener<Component>() { @Override public void onChanged(Change<? extends Component> c) { while (c.next()) { if (HUPPAAL.getProject().getComponents().size() > 1 && testAdderBoolean.get()) { final SubComponentPresentation subComponentPresentation = new SubComponentPresentation(HUPPAAL.getProject().getComponents().get(2)); getChildren().add(subComponentPresentation); testAdderBoolean.set(false); } } } }); } catch (final IOException ioe) { throw new IllegalStateException(ioe); } } private void initializeDefaultLocationsContainer() { if (initialLocationPresentation != null) { controller.defaultLocationsContainer.getChildren().remove(initialLocationPresentation); } if (finalLocationPresentation != null) { controller.defaultLocationsContainer.getChildren().remove(finalLocationPresentation); } // Instantiate views for the initial and final location final Component component = controller.getComponent(); initialLocationPresentation = new LocationPresentation(component.getInitialLocation(), component); finalLocationPresentation = new LocationPresentation(component.getFinalLocation(), component); // Add the locations to the view controller.defaultLocationsContainer.getChildren().addAll(initialLocationPresentation, finalLocationPresentation); } private void initializeName() { final Component component = controller.getComponent(); final BooleanProperty initialized = new SimpleBooleanProperty(false); controller.name.focusedProperty().addListener((observable, oldValue, newValue) -> { if (newValue && !initialized.get()) { controller.root.requestFocus(); initialized.setValue(true); } }); // Set the text field to the name in the model, and bind the model to the text field controller.name.setText(component.getName()); component.nameProperty().bind(controller.name.textProperty()); final Runnable updateColor = () -> { final Color color = component.getColor(); final Color.Intensity colorIntensity = component.getColorIntensity(); // Set the text color for the label controller.name.setStyle("-fx-text-fill: " + color.getTextColorRgbaString(colorIntensity) + ";"); controller.name.setFocusColor(color.getTextColor(colorIntensity)); controller.name.setUnFocusColor(javafx.scene.paint.Color.TRANSPARENT); }; controller.getComponent().colorProperty().addListener(observable -> updateColor.run()); updateColor.run(); // Center the text vertically and aff a left padding of CORNER_SIZE controller.name.setPadding(new Insets(2, 0, 0, CORNER_SIZE)); } private void initializeInitialLocation() { initialLocationPresentation.setLocation(controller.getComponent().getInitialLocation()); initialLocationPresentation.layoutXProperty().unbind(); initialLocationPresentation.layoutYProperty().unbind(); initialLocationPresentation.setLayoutX(CORNER_SIZE / 2 + 1); initialLocationPresentation.setLayoutY(CORNER_SIZE / 2 + 1); StackPane.setAlignment(initialLocationPresentation, Pos.TOP_LEFT); } private void initializeFinalLocation() { final Component component = controller.getComponent(); finalLocationPresentation.setLocation(component.getFinalLocation()); finalLocationPresentation.layoutXProperty().unbind(); finalLocationPresentation.layoutYProperty().unbind(); finalLocationPresentation.setLayoutX(component.getWidth() - CORNER_SIZE / 2 - 1); finalLocationPresentation.setLayoutY(component.getHeight() - CORNER_SIZE / 2 - 1); StackPane.setAlignment(finalLocationPresentation, Pos.BOTTOM_RIGHT); } private void initializeToolbar() { final Component component = controller.getComponent(); final BiConsumer<Color, Color.Intensity> updateColor = (newColor, newIntensity) -> { // Set the background of the toolbar controller.toolbar.setBackground(new Background(new BackgroundFill( newColor.getColor(newIntensity), CornerRadii.EMPTY, Insets.EMPTY ))); // Set the icon color and rippler color of the toggleDeclarationButton controller.toggleDeclarationButton.setRipplerFill(newColor.getTextColor(newIntensity)); controller.toolbar.setPrefHeight(TOOL_BAR_HEIGHT); controller.toggleDeclarationButton.setBackground(Background.EMPTY); }; updateColorDelegates.add(updateColor); controller.getComponent().colorProperty().addListener(observable -> updateColor.accept(component.getColor(), component.getColorIntensity())); updateColor.accept(component.getColor(), component.getColorIntensity()); // Set a hover effect for the controller.toggleDeclarationButton controller.toggleDeclarationButton.setOnMouseEntered(event -> controller.toggleDeclarationButton.setCursor(Cursor.HAND)); controller.toggleDeclarationButton.setOnMouseExited(event -> controller.toggleDeclarationButton.setCursor(Cursor.DEFAULT)); } private void initializeFrame() { final Component component = controller.getComponent(); final Shape[] mask = new Shape[1]; final Rectangle rectangle = new Rectangle(component.getWidth(), component.getHeight()); // Generate first corner (to subtract) final Polygon corner1 = new Polygon( 0, 0, CORNER_SIZE + 2, 0, 0, CORNER_SIZE + 2 ); // Generate second corner (to subtract) final Polygon corner2 = new Polygon( component.getWidth(), component.getHeight(), component.getWidth() - CORNER_SIZE - 2, component.getHeight(), component.getWidth(), component.getHeight() - CORNER_SIZE - 2 ); final BiConsumer<Color, Color.Intensity> updateColor = (newColor, newIntensity) -> { // Mask the parent of the frame (will also mask the background) mask[0] = Path.subtract(rectangle, corner1); mask[0] = Path.subtract(mask[0], corner2); controller.frame.setClip(mask[0]); controller.background.setClip(Path.union(mask[0], mask[0])); controller.background.setOpacity(0.5); // Bind the missing lines that we cropped away controller.line1.setStartX(CORNER_SIZE); controller.line1.setStartY(0); controller.line1.setEndX(0); controller.line1.setEndY(CORNER_SIZE); controller.line1.setStroke(newColor.getColor(newIntensity.next(2))); controller.line1.setStrokeWidth(1.25); StackPane.setAlignment(controller.line1, Pos.TOP_LEFT); controller.line2.setStartX(CORNER_SIZE); controller.line2.setStartY(0); controller.line2.setEndX(0); controller.line2.setEndY(CORNER_SIZE); controller.line2.setStroke(newColor.getColor(newIntensity.next(2))); controller.line2.setStrokeWidth(1.25); StackPane.setAlignment(controller.line2, Pos.BOTTOM_RIGHT); // Set the stroke color to two shades darker controller.frame.setBorder(new Border(new BorderStroke( newColor.getColor(newIntensity.next(2)), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(1), Insets.EMPTY ))); }; updateColorDelegates.add(updateColor); component.colorProperty().addListener(observable -> { updateColor.accept(component.getColor(), component.getColorIntensity()); }); updateColor.accept(component.getColor(), component.getColorIntensity()); } private void initializeBackground() { final Component component = controller.getComponent(); // Bind the background width and height to the values in the model controller.background.widthProperty().bind(component.widthProperty()); controller.background.heightProperty().bind(component.heightProperty()); final BiConsumer<Color, Color.Intensity> updateColor = (newColor, newIntensity) -> { // Set the background color to the lightest possible version of the color controller.background.setFill(newColor.getColor(newIntensity)); }; updateColorDelegates.add(updateColor); component.colorProperty().addListener(observable -> { updateColor.accept(component.getColor(), component.getColorIntensity()); }); updateColor.accept(component.getColor(), component.getColorIntensity()); } @Override public DoubleProperty xProperty() { return layoutXProperty(); } @Override public DoubleProperty yProperty() { return layoutYProperty(); } @Override public MouseTracker getMouseTracker() { return controller.getMouseTracker(); } @Override public void select() { updateColorDelegates.forEach(colorConsumer -> colorConsumer.accept(Color.DEEP_ORANGE, Color.Intensity.I500)); } @Override public void deselect() { updateColorDelegates.forEach(colorConsumer -> { final Component component = controller.getComponent(); colorConsumer.accept(component.getColor(), component.getColorIntensity()); }); } }
package de.codemakers.bot.supreme.plugin; import de.codemakers.plugin.PluginLoader; import de.codemakers.plugin.impl.StandardPluginFilter; import java.io.File; import java.util.ArrayList; /** * PluginManager * * @author Panzer1119 */ public class PluginManager implements PluginProvider { private final PluginLoader pluginLoader; private final ArrayList<Plugin> plugins = new ArrayList<>(); public PluginManager() { this(new PluginLoader().setPluginFilter(StandardPluginFilter.createInstance(Plugin.class))); } public PluginManager(PluginLoader pluginLoader) { this.pluginLoader = pluginLoader; PluginLoader.DEBUG_MODE = true; } protected final PluginLoader getPluginLoader() { return pluginLoader; } public final PluginManager loadPlugins(File... files) { if (pluginLoader.loadPlugins(files)) { plugins.clear(); plugins.addAll(pluginLoader.getPluggables(Plugin.class)); plugins.stream().forEach((plugin) -> { plugin.setProvider(this); }); } return this; } @Override public boolean print(Plugin plugin, String print, Object... args) { if (args == null || args.length == 0) { System.out.print(String.format("[%s]: %s", plugin.getName(), print)); } else { System.out.printf(String.format("[%s]: %s", plugin.getName(), print), args); } return true; } }
package de.mrapp.android.preference; import static de.mrapp.android.preference.util.Condition.ensureAtLeast; import static de.mrapp.android.preference.util.Condition.ensureGreaterThan; import static de.mrapp.android.preference.util.Condition.ensureNotNull; import static de.mrapp.android.preference.util.DisplayUtil.convertDpToPixels; import static de.mrapp.android.preference.util.DisplayUtil.convertPixelsToDp; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentBreadCrumbs; import android.app.FragmentTransaction; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import de.mrapp.android.preference.adapter.AdapterListener; import de.mrapp.android.preference.adapter.PreferenceHeaderAdapter; import de.mrapp.android.preference.fragment.FragmentListener; import de.mrapp.android.preference.fragment.PreferenceHeaderFragment; import de.mrapp.android.preference.parser.PreferenceHeaderParser; /** * An activity, which provides a navigation for multiple groups of preferences, * in which each group is represented by an instance of the class * {@link PreferenceHeader}. On devices with small screens, e.g. on smartphones, * the navigation is designed to use the whole available space and selecting an * item causes the corresponding preferences to be shown full screen as well. On * devices with large screens, e.g. on tablets, the navigation and the * preferences of the currently selected item are shown split screen. * * @author Michael Rapp * * @since 1.0.0 */ public abstract class PreferenceActivity extends Activity implements FragmentListener, OnItemClickListener, AdapterListener { /** * When starting this activity, the invoking intent can contain this extra * string to specify which fragment should be initially displayed. */ public static final String EXTRA_SHOW_FRAGMENT = ":android:show_fragment"; /** * When starting this activity and using <code>EXTRA_SHOW_FRAGMENT</code>, * this extra can also be specified to supply a bundle of arguments to pass * to that fragment when it is instantiated during the initial creation of * the activity. */ public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":android:show_fragment_args"; /** * When starting this activity and using <code>EXTRA_SHOW_FRAGMENT</code>, * this extra can also be specified to supply the title to be shown for that * fragment. */ public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":android:show_fragment_title"; /** * When starting this activity and using <code>EXTRA_SHOW_FRAGMENT</code>, * this extra can also be specified to supply the short title to be shown * for that fragment. */ public static final String EXTRA_SHOW_FRAGMENT_SHORT_TITLE = ":android:show_fragment_short_title"; /** * When starting this activity, the invoking intent can contain this extra * boolean that the header list should not be displayed. This is most often * used in conjunction with <code>EXTRA_SHOW_FRAGMENT</code> to launch the * activity to display a specific fragment that the user has navigated to. */ public static final String EXTRA_NO_HEADERS = ":android:no_headers"; /** * When starting this activity, the invoking intent can contain this extra * boolean to display back and next buttons in order to use the activity as * a wizard. */ public static final String EXTRA_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar"; /** * When starting this activity and using <code>EXTRA_SHOW_BUTTON_BAR</code>, * this extra can also be specified to supply a custom text for the next * button. */ public static final String EXTRA_NEXT_BUTTON_TEXT = "extra_prefs_set_next_text"; /** * When starting this activity and using <code>EXTRA_SHOW_BUTTON_BAR</code>, * this extra can also be specified to supply a custom text for the back * button. */ public static final String EXTRA_BACK_BUTTON_TEXT = "extra_prefs_set_back_text"; /** * When starting this activity and using <code>EXTRA_SHOW_BUTTON_BAR</code>, * this extra can also be specified to supply a custom text for the back * button when the last preference header is shown. */ public static final String EXTRA_FINISH_BUTTON_TEXT = "extra_prefs_set_finish_text"; /** * The name of the extra, which is used to save the parameters, which have * been passed when the currently shown fragment has been created, within a * bundle. */ private static final String CURRENT_BUNDLE_EXTRA = PreferenceActivity.class .getSimpleName() + "::CurrentBundle"; /** * The name of the extra, which is used to save the title, which is * currently used by the bread crumbs, within a bundle. */ private static final String CURRENT_TITLE_EXTRA = PreferenceActivity.class .getSimpleName() + "::CurrentTitle"; /** * The name of the extra, which is used to save the short title, which is * currently used by the bread crumbs, within a bundle. */ private static final String CURRENT_SHORT_TITLE_EXTRA = PreferenceActivity.class .getSimpleName() + "::CurrentShortTitle"; /** * The name of the extra, which is used to save the currently selected * preference header, within a bundle. */ private static final String CURRENT_PREFERENCE_HEADER_EXTRA = PreferenceActivity.class .getSimpleName() + "::CurrentPreferenceHeader"; /** * The name of the extra, which is used to saved the preference headers * within a bundle. */ private static final String PREFERENCE_HEADERS_EXTRA = PreferenceActivity.class .getSimpleName() + "::PreferenceHeaders"; /** * The saved instance state, which has been passed to the activity, when it * has been created. */ private Bundle savedInstanceState; /** * The fragment, which contains the preference headers and provides the * navigation to each header's fragment. */ private PreferenceHeaderFragment preferenceHeaderFragment; /** * The fragment, which is currently shown as the preference screen or null, * if no preference header is currently selected. */ private Fragment preferenceScreenFragment; /** * The parent view of the fragment, which provides the navigation to each * preference header's fragment. */ private ViewGroup preferenceHeaderParentView; /** * The parent view of the fragment, which is used to show the preferences of * the currently selected preference header on devices with a large screen. */ private ViewGroup preferenceScreenParentView; /** * The view group, which contains all views, e.g. the preferences itself and * the bread crumbs, which are shown when a preference header is selected on * devices with a large screen. */ private ViewGroup preferenceScreenContainer; /** * The view group, which contains the buttons, which are shown when the * activity is used as a wizard. */ private ViewGroup buttonBar; /** * The back button, which is shown, if the activity is used as a wizard. */ private Button backButton; /** * The next button, which is shown, if the activity is used as a wizard and * the last preference header is currently not selected. */ private Button nextButton; /** * The finish button, which is shown, if the activity is used as a wizard * and the last preference header is currently selected. */ private Button finishButton; /** * The view, which is used to draw a separator between the bread crumbs and * the preferences on devices with a large screen. */ private View breadCrumbsSeperator; /** * The view, which is used to draw a separator between the button bar and * the preferences when the activity is used as a wizard. */ private View buttonBarSeparator; /** * The view, which is used to draw a shadow besides the navigation on * devices with a large screen. */ private View shadowView; /** * The preference header, which is currently selected, or null, if no * preference header is currently selected. */ private PreferenceHeader currentHeader; /** * The title, which is currently used by the bread crumbs or null, if no * bread crumbs are currently shown. */ private CharSequence currentTitle; /** * The short title, which is currently used by the bread crumbs or null, if * no bread crumbs are currently shown. */ private CharSequence currentShortTitle; /** * True, if the back button of the action bar should be shown, false * otherwise. */ private boolean displayHomeAsUp; /** * The default title of the activity. */ private CharSequence defaultTitle; /** * True, if the behavior of the action bar's back button is overridden to * return to the navigation when a preference header is currently selected * on devices with a small screen. */ private boolean overrideBackButton; /** * True, if the fragment, which provides navigation to each preference * header's fragment on devices with a large screen, is currently hidden or * not. */ private boolean navigationHidden; /** * The color of the separator, which is drawn between the bread crumbs and * the preferences on devices with a large screen. */ private int breadCrumbsSeparatorColor; /** * The color of the separator, which is drawn between the button bar and the * preference, when the activity is used as a wizard. */ private int buttonBarSeparatorColor; /** * The color of the shadow, which is drawn besides the navigation on devices * with a large screen. */ private int shadowColor; /** * The bread crumbs, which are used to show the title of the currently * selected fragment on devices with a large screen. */ private FragmentBreadCrumbs breadCrumbs; /** * A set, which contains the listeners, which have registered to be notified * when the user navigates within the activity, if it used as a wizard. */ private Set<WizardListener> wizardListeners = new LinkedHashSet<>(); /** * Handles the intent, which has been used to start the activity. */ private void handleIntent() { handleInitialFragmentIntent(); handleShowButtonBarIntent(); handleHideNavigationIntent(); } /** * Handles extras of the intent, which has been used to start the activity, * that allow to initially display a specific fragment. */ private void handleInitialFragmentIntent() { String initialFragment = getIntent() .getStringExtra(EXTRA_SHOW_FRAGMENT); Bundle initialArguments = getIntent().getBundleExtra( EXTRA_SHOW_FRAGMENT_ARGUMENTS); int initialTitle = getIntent() .getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE, 0); int initialShortTitle = getIntent().getIntExtra( EXTRA_SHOW_FRAGMENT_SHORT_TITLE, 0); if (initialFragment != null) { for (int i = 0; i < getListAdapter().getCount(); i++) { PreferenceHeader preferenceHeader = getListAdapter().getItem(i); if (preferenceHeader.getFragment() != null && preferenceHeader.getFragment().equals( initialFragment)) { showPreferenceScreen(preferenceHeader, initialArguments); getListView().setItemChecked(i, true); if (initialTitle != 0) { CharSequence title = getText(initialTitle); CharSequence shortTitle = (initialShortTitle != 0) ? getText(initialShortTitle) : null; showBreadCrumbs(title, shortTitle); } } } } } /** * Handles extras of the intent, which has been used to start the activity, * that allow to show the button bar in order to use the activity as a * wizard. */ private void handleShowButtonBarIntent() { boolean showButtonBar = getIntent().getBooleanExtra( EXTRA_SHOW_BUTTON_BAR, false); int nextButtonText = getIntent().getIntExtra(EXTRA_NEXT_BUTTON_TEXT, 0); int backButtonText = getIntent().getIntExtra(EXTRA_BACK_BUTTON_TEXT, 0); int finishButtonText = getIntent().getIntExtra( EXTRA_FINISH_BUTTON_TEXT, 0); if (showButtonBar) { showButtonBar(true); if (nextButtonText != 0) { setNextButtonText(nextButtonText); } if (backButtonText != 0) { setBackButtonText(backButtonText); } if (finishButtonText != 0) { setFinishButtonText(finishButtonText); } } } /** * Handles the extra of the intent, which has been used to start the * activity, that allows to hide the navigation. */ private void handleHideNavigationIntent() { boolean noHeaders = getIntent() .getBooleanExtra(EXTRA_NO_HEADERS, false); hideNavigation(noHeaders); } /** * Returns a listener, which allows to proceed to the next step, when the * activity is used as a wizard. * * @return The listener, which has been created, as an instance of the type * {@link OnClickListener} */ private OnClickListener createNextButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { int currentIndex = getListAdapter().indexOf(currentHeader); if (currentIndex < getNumberOfPreferenceHeaders() - 1 && notifyOnNextStep()) { showPreferenceScreen( getListAdapter().getItem(currentIndex + 1), null); if (isSplitScreen()) { getListView().setItemChecked(currentIndex + 1, true); } } } }; } /** * Returns a listener, which allows to resume to the previous step, when the * activity is used as a wizard. * * @return The listener, which has been created, as an instance of the type * {@link OnClickListener} */ private OnClickListener createBackButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { int currentIndex = getListAdapter().indexOf(currentHeader); if (currentIndex > 0 && notifyOnPreviousStep()) { showPreferenceScreen( getListAdapter().getItem(currentIndex - 1), null); if (isSplitScreen()) { getListView().setItemChecked(currentIndex - 1, true); } } } }; } /** * Returns a listener, which allows to finish the last step, when the * activity is used as a wizard. * * @return The listener, which has been created, as an instance of the type * {@link OnClickListener} */ private OnClickListener createFinishButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { notifyOnFinish(); } }; } /** * Notifies all registered listeners that the user wants to navigate to the * next step of the wizard. * * @return True, if navigating to the next step of the wizard should be * allowed, false otherwise */ private boolean notifyOnNextStep() { boolean accepted = true; for (WizardListener listener : wizardListeners) { accepted &= listener.onNextStep( getListAdapter().indexOf(currentHeader), currentHeader, preferenceScreenFragment); } return accepted; } /** * Notifies all registered listeners that the user wants to navigate to the * previous step of the wizard. * * @return True, if navigating to the previous step of the wizard should be * allowed, false otherwise */ private boolean notifyOnPreviousStep() { boolean accepted = true; for (WizardListener listener : wizardListeners) { accepted &= listener.onPreviousStep( getListAdapter().indexOf(currentHeader), currentHeader, preferenceScreenFragment); } return accepted; } /** * Notifies all registered listeners that the user wants to finish the last * step of the wizard. * * @return True, if finishing the last step of the wizard should be allowed, * false otherwise */ private boolean notifyOnFinish() { boolean accepted = true; for (WizardListener listener : wizardListeners) { accepted &= listener.onNextStep( getListAdapter().indexOf(currentHeader), currentHeader, preferenceScreenFragment); } return accepted; } /** * Notifies all registered listeners that the user wants to skip the wizard. * * @return True, if skipping the wizard should be allowed, false otherwise */ private boolean notifyOnSkip() { boolean accepted = true; for (WizardListener listener : wizardListeners) { accepted &= listener.onSkip( getListAdapter().indexOf(currentHeader), currentHeader, preferenceScreenFragment); } return accepted; } /** * Shows the fragment, which corresponds to a specific preference header. * * @param preferenceHeader * The preference header, the fragment, which should be shown, * corresponds to, as an instance of the class * {@link PreferenceHeader}. The preference header may not be * null * @param params * Optional parameters, which are passed to the fragment, as an * instance of the class Bundle or null, if the preference * header's extras should be used instead */ private void showPreferenceScreen(final PreferenceHeader preferenceHeader, final Bundle params) { currentHeader = preferenceHeader; adaptWizardButtons(); if (preferenceHeader.getFragment() != null) { showBreadCrumbs(preferenceHeader); Bundle parameters = (params != null) ? params : preferenceHeader .getExtras(); showPreferenceScreen(preferenceHeader.getFragment(), parameters); } else if (preferenceScreenFragment != null) { showBreadCrumbs(preferenceHeader); removeFragment(preferenceScreenFragment); preferenceScreenFragment = null; } if (preferenceHeader.getIntent() != null) { startActivity(preferenceHeader.getIntent()); } } /** * Shows the fragment, which corresponds to a specific class name. * * @param fragmentName * The full qualified class name of the fragment, which should be * shown, as a {@link String} * @param params * Optional parameters, which are passed to the fragment, as an * instance of the class {@link Bundle} or null, if no parameters * should be passed */ private void showPreferenceScreen(final String fragmentName, final Bundle params) { preferenceScreenFragment = Fragment.instantiate(this, fragmentName, params); if (isSplitScreen()) { replaceFragment(preferenceScreenFragment, R.id.preference_screen_parent, 0); } else { updateSavedInstanceState(); replaceFragment(preferenceScreenFragment, R.id.preference_header_parent, FragmentTransaction.TRANSIT_FRAGMENT_FADE); showActionBarBackButton(); } } /** * Adapts the buttons which are shown, when the activity is used as a * wizard, depending on the currently selected preference header. */ private void adaptWizardButtons() { if (currentHeader != null && isButtonBarShown()) { int index = getListAdapter().indexOf(currentHeader); getBackButton().setVisibility( (index != 0) ? View.VISIBLE : View.GONE); getNextButton().setVisibility( (index != getListAdapter().getCount() - 1) ? View.VISIBLE : View.GONE); getFinishButton().setVisibility( (index == getListAdapter().getCount() - 1) ? View.VISIBLE : View.GONE); } } /** * Adapts the GUI, depending on whether the navigation is currently hidden * or not. * * @param navigationHidden * True, if the navigation is currently hidden, false otherwise */ private void adaptNavigation(final boolean navigationHidden) { if (isSplitScreen()) { getPreferenceHeaderParentView().setVisibility( navigationHidden ? View.GONE : View.VISIBLE); getShadowView().setVisibility( navigationHidden ? View.GONE : View.VISIBLE); } else if (navigationHidden && isPreferenceHeaderSelected()) { hideActionBarBackButton(); } else if (navigationHidden && !isPreferenceHeaderSelected()) { if (!getListAdapter().isEmpty()) { showPreferenceScreen(getListAdapter().getItem(0), null); } else { finish(); } } } /** * Shows the fragment, which provides the navigation to each preference * header's fragment. */ private void showPreferenceHeaders() { int transition = 0; if (isPreferenceHeaderSelected()) { transition = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; currentHeader = null; preferenceScreenFragment = null; } replaceFragment(preferenceHeaderFragment, R.id.preference_header_parent, transition); } /** * Replaces the fragment, which is currently contained by a specific parent * view, by an other fragment. * * @param fragment * The fragment, which should replace the current fragment, as an * instance of the class {@link Fragment}. The fragment may not * be null * @param parentViewId * The id of the parent view, which contains the fragment, that * should be replaced, as an {@link Integer} value * @param transition * The transition, which should be shown when replacing the * fragment, as an {@link Integer} value or 0, if no transition * should be shown */ private void replaceFragment(final Fragment fragment, final int parentViewId, final int transition) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.setTransition(transition); transaction.replace(parentViewId, fragment); transaction.commit(); } /** * Removes a specific fragment from its parent view. * * @param fragment * The fragment, which should be removed, as an instance of the * class {@link Fragment}. The fragment may not be null */ private void removeFragment(final Fragment fragment) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.remove(fragment); transaction.commit(); } /** * Shows the back button in the activity's action bar. */ private void showActionBarBackButton() { if (getActionBar() != null && !isNavigationHidden() && !(!isSplitScreen() && isButtonBarShown())) { displayHomeAsUp = isDisplayHomeAsUpEnabled(); getActionBar().setDisplayHomeAsUpEnabled(true); } } /** * Hides the back button in the activity's action bar, if it was not * previously shown. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void hideActionBarBackButton() { if (getActionBar() != null && !displayHomeAsUp) { getActionBar().setDisplayHomeAsUpEnabled(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { getActionBar().setHomeButtonEnabled(false); } } } /** * Returns, whether the back button of the action bar is currently shown, or * not. * * @return True, if the back button of the action bar is currently shown, * false otherwise */ private boolean isDisplayHomeAsUpEnabled() { if (getActionBar() != null) { return (getActionBar().getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP; } return false; } /** * Shows the bread crumbs for a specific preference header, depending on * whether the device has a large screen or not. On devices with a large * screen the bread crumbs will be shown above the currently shown fragment, * on devices with a small screen the bread crumbs will be shown as the * action bar's title instead. * * @param preferenceHeader * The preference header, the bread crumbs should be shown for, * as an instance of the class {@link PreferenceHeader}. The * preference header may not be null */ private void showBreadCrumbs(final PreferenceHeader preferenceHeader) { CharSequence title = preferenceHeader.getBreadCrumbTitle(); if (title == null) { title = preferenceHeader.getTitle(); } if (title == null) { title = getTitle(); } showBreadCrumbs(title, preferenceHeader.getBreadCrumbShortTitle()); } /** * Shows the bread crumbs using a specific title and short title, depending * on whether the device has a large screen or not. On devices with a large * screen the bread crumbs will be shown above the currently shown fragment, * on devices with a small screen the bread crumbs will be shown as the * action bar's title instead. * * @param title * The title, which should be used by the bread crumbs, as an * instance of the class {@link CharSequence} or null, if no * title should be used * @param shortTitle * The short title, which should be used by the bread crumbs, as * an instance of the class {@link CharSequence} or null, if no * short title should be used */ private void showBreadCrumbs(final CharSequence title, final CharSequence shortTitle) { this.currentTitle = title; this.currentShortTitle = title; if (getBreadCrumbs() != null) { if (title != null || shortTitle != null) { getBreadCrumbs().setVisibility(View.VISIBLE); getBreadCrumbsSeparator().setVisibility(View.VISIBLE); } else { getBreadCrumbs().setVisibility(View.GONE); getBreadCrumbsSeparator().setVisibility(View.GONE); } getBreadCrumbs().setTitle(title, shortTitle); getBreadCrumbs().setParentTitle(null, null, null); } else if (title != null) { if (defaultTitle == null) { defaultTitle = getTitle(); } setTitle(title); } } /** * Resets the title of the activity to the default title, if it has been * previously changed. */ private void resetTitle() { if (defaultTitle != null) { setTitle(defaultTitle); defaultTitle = null; currentTitle = null; currentShortTitle = null; } } /** * Adds the preference headers, which are currently added to the activity, * to the bundle, which has been passed to the activity, when it has been * created. If no bundle has been passed to the activity, a new bundle will * be created. */ private void updateSavedInstanceState() { if (savedInstanceState == null) { savedInstanceState = new Bundle(); } savedInstanceState.putParcelableArrayList(PREFERENCE_HEADERS_EXTRA, getListAdapter().getAllItems()); } /** * Adds a new listener, which should be notified, when the user navigates * within the activity, if it is used as a wizard, to the activity. * * @param listener * The listener, which should be added, as an instance of the * type {@link WizardListener}. The listener may not be null */ public final void addWizardListener(final WizardListener listener) { ensureNotNull(listener, "The listener may not be null"); wizardListeners.add(listener); } /** * Removes a specific listener, which should not be notified, when the user * navigates within the activity, if it is used as a wizard, from the * activity. * * @param listener * The listener, which should be removed, as an instance of the * type {@link WizardListener}. The listener may not be null */ public final void removeWizardListener(final WizardListener listener) { ensureNotNull(listener, "The listener may not be null"); wizardListeners.remove(wizardListeners); } /** * Returns the parent view of the fragment, which provides the navigation to * each preference header's fragment. On devices with a small screen this * parent view is also used to show a preference header's fragment, when a * header is currently selected. * * @return The parent view of the fragment, which provides the navigation to * each preference header's fragment, as an instance of the class * {@link ViewGroup}. The parent view may not be null */ public final ViewGroup getPreferenceHeaderParentView() { return preferenceHeaderParentView; } /** * Returns the parent view of the fragment, which is used to show the * preferences of the currently selected preference header on devices with a * large screen. * * @return The parent view of the fragment, which is used to show the * preferences of the currently selected preference header, as an * instance of the class {@link ViewGroup} or null, if the device * has a small screen */ public final ViewGroup getPreferenceScreenParentView() { return preferenceScreenParentView; } /** * Returns the view group, which contains all views, e.g. the preferences * itself and the bread crumbs, which are shown when a preference header is * selected on devices with a large screen. * * @return The view group, which contains all views, which are shown when a * preference header is selected, as an instance of the class * {@link ViewGroup} or null, if the device has a small screen */ public final ViewGroup getPreferenceScreenContainer() { return preferenceScreenContainer; } /** * Returns the view group, which contains the buttons, which are shown when * the activity is used as a wizard. * * @return The view group, which contains the buttons, which are shown when * the activity is used as a wizard, as an instance of the class * {@link ViewGroup} or null, if the wizard is not used as a wizard */ public final ViewGroup getButtonBar() { return buttonBar; } /** * Returns the next button, which is shown, when the activity is used as a * wizard and the last preference header is currently not selected. * * @return The next button as an instance of the class {@link Button} or * null, if the activity is not used as a wizard */ public final Button getNextButton() { return nextButton; } /** * Returns the text of the next button, which is shown, when the activity is * used as a wizard. * * @return The text of the next button as an instance of the class * {@link CharSequence} or null, if the activity is not used as a * wizard */ public final CharSequence getNextButtonText() { if (nextButton != null) { return nextButton.getText(); } return null; } /** * Sets the text of the next button, which is shown, when the activity is * used as a wizard. The text is only set, if the activity is used as a * wizard. * * @param text * The text, which should be set, as an instance of the class * {@link CharSequence}. The text may not be null * @return True, if the text has been set, false otherwise */ public final boolean setNextButtonText(final CharSequence text) { ensureNotNull(text, "The text may not be null"); if (nextButton != null) { nextButton.setText(text); return true; } return false; } /** * Sets the text of the next button, which is shown, when the activity is * used as a wizard. The text is only set, if the activity is used as a * wizard. * * @param resourceId * The resource id of the text, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource * @return True, if the text has been set, false otherwise */ public final boolean setNextButtonText(final int resourceId) { return setNextButtonText(getText(resourceId)); } /** * Returns the finish button, which is shown, when the activity is used as a * wizard and the last preference header is currently selected. * * @return The finish button as an instance of the class {@link Button} or * null, if the activity is not used as a wizard */ public final Button getFinishButton() { return finishButton; } /** * Sets the text of the next button, which is shown, when the activity is * used as a wizard and the last preference header is currently selected. * The text is only set, if the activity is used as a wizard. * * @param text * The text, which should be set, as an instance of the class * {@link CharSequence}. The text may not be null * @return True, if the text has been set, false otherwise */ public final boolean setFinishButtonText(final CharSequence text) { ensureNotNull(text, "The text may not be null"); if (nextButton != null) { nextButton.setText(text); return true; } return false; } /** * Sets the text of the next button, which is shown, when the activity is * used as a wizard and the last preference header is currently selected. * The text is only set, if the activity is used as a wizard. * * @param resourceId * The resource id of the text, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource * @return True, if the text has been set, false otherwise */ public final boolean setFinishButtonText(final int resourceId) { return setFinishButtonText(getText(resourceId)); } /** * Returns the back button, which is shown, when the activity is used as a * wizard. * * @return The back button as an instance of the class {@link Button} or * null, if the activity is not used as a wizard */ public final Button getBackButton() { return backButton; } /** * Returns the text of the back button, which is shown, when the activity is * used as a wizard. * * @return The text of the back button as an instance of the class * {@link CharSequence} or null, if the activity is not used as a * wizard */ public final CharSequence getBackButtonText() { if (backButton != null) { return backButton.getText(); } return null; } /** * Sets the text of the back button, which is shown, when the activity is * used as a wizard. The text is only set, if the activity is used as a * wizard. * * @param text * The text, which should be set, as an instance of the class * {@link CharSequence}. The text may not be null * @return True, if the text has been set, false otherwise */ public final boolean setBackButtonText(final CharSequence text) { ensureNotNull(text, "The text may not be null"); if (backButton != null) { backButton.setText(text); return true; } return false; } /** * Sets the text of the back button, which is shown, when the activity is * used as a wizard. The text is only set, if the activity is used as a * wizard. * * @param resourceId * The resource id of the text, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid string resource * @return True, if the text has been set, false otherwise */ public final boolean setBackButtonText(final int resourceId) { return setBackButtonText(getText(resourceId)); } /** * Returns the view, which is used to draw a separator between the bread * crumbs and the preferences on devices with a large screen. * * @return The view, which is used to draw a separator between the bread * crumbs and the preferences, as an instance of the class * {@link View} or null, if the device has a small display */ public final View getBreadCrumbsSeparator() { return breadCrumbsSeperator; } /** * Returns the view, which is used to draw a separator between the button * bar and the preferences when the activity is used as a wizard. * * @return The view, which is used to draw a separator between the button * bar and the preferences, as an instance of the class {@link View} * or null, if the activity is not used as a wizard */ public final View getButtonBarSeparator() { return buttonBarSeparator; } /** * Returns the view, which is used to draw a shadow besides the navigation * on devices with a large screen. * * @return The view, which is used to draw a shadow besides the navigation, * as an instance of the class {@link View} or null, if the device * has a small screen */ public final View getShadowView() { return shadowView; } /** * Returns the bread crumbs, which are used to show the title of the * currently selected fragment on devices with a large screen. * * @return The bread crumbs, which are used to show the title of the * currently selected fragment or null, if the device has a small * screen */ public final FragmentBreadCrumbs getBreadCrumbs() { return breadCrumbs; } /** * Returns the list view, which is used to show the preference headers. * * @return The list view, which is used to show the preference header, as an * instance of the class {@link ListView}. The list view may not be * null */ public final ListView getListView() { return preferenceHeaderFragment.getListView(); } /** * Returns the adapter, which provides the preference headers for * visualization using the list view. * * @return The adapter, which provides the preference headers for * visualization using the list view, as an instance of the class * {@link PreferenceHeaderAdapter}. The adapter may not be null */ public final PreferenceHeaderAdapter getListAdapter() { return preferenceHeaderFragment.getListAdapter(); } /** * Adds all preference headers, which are specified by a specific XML * resource, to the activity. * * @param resourceId * The resource id of the XML file, which specifies the * preference headers, as an {@link Integer} value. The resource * id must correspond to a valid XML resource */ public final void addPreferenceHeadersFromResource(final int resourceId) { getListAdapter().addAllItems( PreferenceHeaderParser.fromResource(this, resourceId)); } /** * Adds a new preference header to the activity. * * @param preferenceHeader * The preference header, which should be added, as an instance * of the class {@link PreferenceHeader}. The preference header * may not be null * @return */ public final void addPreferenceHeader( final PreferenceHeader preferenceHeader) { getListAdapter().addItem(preferenceHeader); } /** * Adds all preference headers, which are contained by a specific * collection, to the activity. * * @param preferenceHeaders * The collection, which contains the preference headers, which * should be added, as an instance of the type {@link Collection} * or an empty collection, if no preference headers should be * added */ public final void addAllPreferenceHeaders( final Collection<PreferenceHeader> preferenceHeaders) { getListAdapter().addAllItems(preferenceHeaders); } /** * Removes a specific preference header from the activity. * * @param preferenceHeader * The preference header, which should be removed, as an instance * of the class {@link PreferenceHeader}. The preference header * may not be null * @return True, if the preference header has been removed, false otherwise */ public final boolean removePreferenceHeader( final PreferenceHeader preferenceHeader) { return getListAdapter().removeItem(preferenceHeader); } /** * Returns a collection, which contains all preference headers, which are * currently added to the activity. * * @return A collection, which contains all preference headers, as an * instance of the type {@link Collection} or an empty collection, * if the activity does not contain any preference headers */ public final Collection<PreferenceHeader> getAllPreferenceHeaders() { return getListAdapter().getAllItems(); } /** * Returns the preference header, which belongs to a specific position. * * @param position * The position of the preference header, which should be * returned, as an {@link Integer} value * @return The preference header, which belongs to the given position, as an * instance of the class {@link PreferenceHeader}. The preference * header may not be null */ public final PreferenceHeader getPreferenceHeader(final int position) { return getListAdapter().getItem(position); } /** * Returns the number of preference headers, which are currently added to * the activity. * * @return The number of preference header, which are currently added to the * activity, as an {@link Integer} value */ public final int getNumberOfPreferenceHeaders() { return getListAdapter().getCount(); } /** * Removes all preference headers, which are currently added to the * activity. */ public final void clearPreferenceHeaders() { getListAdapter().clear(); } /** * Returns, whether the preference headers and the corresponding fragments * are shown split screen, or not. * * @return True, if the preference headers and the corresponding fragments * are shown split screen, false otherwise */ public final boolean isSplitScreen() { return getPreferenceScreenParentView() != null; } /** * Returns, whether the fragment, which provides navigation to each * preference header's fragment, is currently hidden or not. * * @return True, if the fragment, which provides navigation to each * preference header's fragment is currently hidden, false otherwise */ public final boolean isNavigationHidden() { return navigationHidden; } /** * Hides or shows the fragment, which provides navigation to each preference * header's fragment. When the activity is used as a wizard on devices with * a small screen, the navigation is always hidden. * * @param hideNavigation * True, if the fragment, which provides navigation to each * preference header's fragment, should be hidden, false * otherwise */ public final void hideNavigation(final boolean hideNavigation) { this.navigationHidden = hideNavigation; adaptNavigation(hideNavigation); } /** * Returns, whether the activity is used as a wizard, or not. * * @return True, if the activity is used as a wizard, false otherwise */ public final boolean isButtonBarShown() { return buttonBar != null; } /** * Shows or hides the view group, which contains the buttons, which are * shown when the activity is used as a wizard. * * @param showButtonBar * True, if the button bar should be shown, false otherwise */ public final void showButtonBar(final boolean showButtonBar) { if (showButtonBar) { buttonBar = (ViewGroup) findViewById(R.id.button_bar); buttonBar.setVisibility(View.VISIBLE); buttonBarSeparator = findViewById(R.id.button_bar_separator); if (getButtonBarSeparatorColor() == 0) { setButtonBarSeparatorColor(getResources().getColor( R.color.separator)); } nextButton = (Button) findViewById(R.id.next_button); nextButton.setOnClickListener(createNextButtonListener()); finishButton = (Button) findViewById(R.id.finish_button); finishButton.setOnClickListener(createFinishButtonListener()); backButton = (Button) findViewById(R.id.back_button); backButton.setOnClickListener(createBackButtonListener()); if (!isSplitScreen()) { adaptNavigation(true); } } else if (buttonBar != null) { buttonBar.setVisibility(View.GONE); buttonBar = null; buttonBarSeparator = null; finishButton = null; nextButton = null; backButton = null; } getListAdapter().setEnabled(!showButtonBar); adaptWizardButtons(); } /** * Returns, whether a preference header is currently selected, or not. * * @return True, if a preference header is currently selected, false * otherwise */ public final boolean isPreferenceHeaderSelected() { return currentHeader != null && currentHeader.getFragment() != null; } /** * Returns the color of the separator, which is drawn between the bread * crumbs and the preferences on devices with a large screen. * * @return The color of the separator as an {@link Integer} value or -1, if * the device has a small screen */ public final int getBreadCrumbsSeparatorColor() { if (getBreadCrumbsSeparator() != null) { return breadCrumbsSeparatorColor; } else { return -1; } } /** * Sets the color of the separator, which is drawn between the bread crumbs * and the preferences on devices with a large screen. The color is only set * on devices with a large screen. * * @param separatorColor * The color, which should be set, as an {@link Integer} value * @return True, if the color has been set, false otherwise */ public final boolean setBreadCrumbsSeparatorColor(final int separatorColor) { if (getBreadCrumbsSeparator() != null) { this.breadCrumbsSeparatorColor = separatorColor; getBreadCrumbsSeparator().setBackgroundColor(separatorColor); return true; } return false; } /** * Returns the color of the separator, which is drawn between the button bar * and the preferences when the activity is used as a wizard. * * @return The color of the separator as an {@link Integer} value or -1, if * the activity is not used as a wizard */ public final int getButtonBarSeparatorColor() { if (getButtonBarSeparator() != null) { return buttonBarSeparatorColor; } else { return -1; } } /** * Sets the color of the separator, which is drawn between the button bar * and the preferences when the activity is used as a wizard. The color is * only set when the activity is used as a wizard. * * @param separatorColor * The color, which should be set, as an {@link Integer} value * @return True, if the color has been set, false otherwise */ public final boolean setButtonBarSeparatorColor(final int separatorColor) { if (getButtonBarSeparator() != null) { this.buttonBarSeparatorColor = separatorColor; getButtonBarSeparator().setBackgroundColor(separatorColor); return true; } return false; } /** * Returns the color of the shadow, which is drawn besides the navigation on * devices with a large screen. * * @return The color of the shadow, which is drawn besides the navigation, * as an {@link Integer} value or -1, if the device has a small * screen */ public final int getShadowColor() { if (isSplitScreen()) { return shadowColor; } else { return -1; } } /** * Sets the color of the shadow, which is drawn besides the navigation on * devices with a large screen. The color is only set on devices with a * large screen. * * @param shadowColor * The color, which should be set, as an {@link Integer} value * @return True, if the color has been set, false otherwise */ @SuppressWarnings("deprecation") public final boolean setShadowColor(final int shadowColor) { if (getShadowView() != null) { this.shadowColor = shadowColor; GradientDrawable gradient = new GradientDrawable( Orientation.LEFT_RIGHT, new int[] { shadowColor, Color.TRANSPARENT }); getShadowView().setBackgroundDrawable(gradient); return true; } return false; } /** * Returns the width of the shadow, which is drawn besides the navigation on * devices with a large screen. * * @return The width of the shadow, which is drawn besides the navigation, * in dp as an {@link Integer} value or -1, if the device has a * small screen */ public final int getShadowWidth() { if (getShadowView() != null) { return convertPixelsToDp(this, getShadowView().getLayoutParams().width); } else { return -1; } } /** * Sets the width of the shadow, which is drawn besides the navigation on * devices with a large screen. The width is only set on devices with a * large screen. * * @param width * The width, which should be set, in dp as an {@link Integer} * value. The width must be at least 0 * @return True, if the width has been set, false otherwise */ public final boolean setShadowWidth(final int width) { ensureAtLeast(width, 0, "The width must be at least 0"); if (getShadowView() != null) { getShadowView().getLayoutParams().width = convertDpToPixels(this, width); getShadowView().requestLayout(); return true; } return false; } /** * Returns the background of the view group, which contains all views, which * are shown when a preference header is selected on devices with a large * screen. * * @return The background of the view group, which contains all views, which * are shown when a preference header is selected or null, if no * background has been set or device has a small screen */ public final Drawable getPreferenceScreenBackground() { if (getPreferenceScreenContainer() != null) { return getPreferenceScreenContainer().getBackground(); } else { return null; } } /** * Sets the background of the view group, which contains all views, which * are shown when a preference header is selected. The background is only * set on devices with a large screen. * * @param resourceId * The resource id of the background, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid drawable resource * @return True, if the background has been set, false otherwise */ public final boolean setPreferenceScreenBackground(final int resourceId) { return setPreferenceScreenBackground(getResources().getDrawable( resourceId)); } /** * Sets the background color of the view group, which contains all views, * which are shown when a preference header is selected. The background is * only set on devices with a large screen. * * @param color * The background color, which should be set, as an * {@link Integer} value * @return True, if the background has been set, false otherwise */ public final boolean setPreferenceScreenBackgroundColor(final int color) { return setPreferenceScreenBackground(new ColorDrawable(color)); } /** * Sets the background of the view group, which contains all views, which * are shown when a preference header is selected. The background is only * set on devices with a large screen. * * @param drawable * The background, which should be set, as an instance of the * class {@link Drawable} or null, if no background should be set * @return True, if the background has been set, false otherwise */ @SuppressWarnings("deprecation") public final boolean setPreferenceScreenBackground(final Drawable drawable) { if (getPreferenceScreenContainer() != null) { getPreferenceScreenContainer().setBackgroundDrawable(drawable); return true; } return false; } /** * Returns the background of the parent view of the fragment, which provides * navigation to each preference header's fragment on devices with a large * screen. * * @return The background of the parent view of the fragment, which provides * navigation to each preference header's fragment, as an instance * of the class {@link Drawable} or null, if no background has been * set or the device has a small screen */ public final Drawable getNavigationBackground() { if (isSplitScreen()) { return getPreferenceHeaderParentView().getBackground(); } else { return null; } } /** * Sets the background of the parent view of the fragment, which provides * navigation to each preference header's fragment. The background is only * set on devices with a large screen. * * @param resourceId * The resource id of the background, which should be set, as an * {@link Integer} value. The resource id must correspond to a * valid drawable resource * @return True, if the background has been set, false otherwise */ public final boolean setNavigationBackground(final int resourceId) { return setNavigationBackground(getResources().getDrawable(resourceId)); } /** * Sets the background color of the parent view of the fragment, which * provides navigation to each preference header's fragment. The background * is only set on devices with a large screen. * * @param color * The background color, which should be set, as an * {@link Integer} value * @return True, if the background has been set, false otherwise */ public final boolean setNavigationBackgroundColor(final int color) { return setNavigationBackground(new ColorDrawable(color)); } /** * Sets the background of the parent view of the fragment, which provides * navigation to each preference header's fragment. The background is only * set on devices with a large screen. * * @param drawable * The background, which should be set, as an instance of the * class {@link Drawable} or null, if no background should be set * @return True, if the background has been set, false otherwise */ @SuppressWarnings("deprecation") public final boolean setNavigationBackground(final Drawable drawable) { if (isSplitScreen()) { getPreferenceHeaderParentView().setBackgroundDrawable(drawable); return true; } return false; } /** * Returns the width of the parent view of the fragment, which provides * navigation to each preference header's fragment on devices with a large * screen. * * @return The width of the parent view of the fragment, which provides * navigation to each preference header's fragment, in dp as an * {@link Integer} value or -1, if the device has a small screen */ public final int getNavigationWidth() { if (isSplitScreen()) { return convertPixelsToDp(this, getPreferenceHeaderParentView() .getLayoutParams().width); } else { return -1; } } /** * Sets the width of the parent view of the fragment, which provides * navigation to each preference header's fragment. The width is only set on * devices with a large screen. * * @param width * The width, which should be set, in dp as an {@link Integer} * value. The width must be greater than 0 * @return True, if the width has been set, false otherwise */ public final boolean setNavigationWidth(final int width) { ensureGreaterThan(width, 0, "The width must be greater than 0"); if (isSplitScreen()) { getPreferenceHeaderParentView().getLayoutParams().width = convertDpToPixels( this, width); getPreferenceHeaderParentView().requestLayout(); return true; } return false; } /** * Returns, whether the behavior of the action bar's back button is * overridden to return to the navigation when a preference header is * currently selected on devices with a small screen, or not. * * @return True, if the behavior of the action bar's back button is * overridden, false otherwise */ public final boolean isBackButtonOverridden() { return overrideBackButton; } /** * Sets, whether the behavior of the action bar's back button should be * overridden to return to the navigation when a preference header is * currently selected on devices with a small screen, or not. * * @param overrideBackButton * True, if the behavior of the action bar's back button should * be overridden, false otherwise */ public final void overrideBackButton(final boolean overrideBackButton) { this.overrideBackButton = overrideBackButton; if (isPreferenceHeaderSelected() && overrideBackButton) { showActionBarBackButton(); } else if (isPreferenceHeaderSelected() && !overrideBackButton) { hideActionBarBackButton(); } } @Override public final void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { showPreferenceScreen(getListAdapter().getItem(position), null); } @Override public final void onPreferenceHeaderAdded( final PreferenceHeaderAdapter adapter, final PreferenceHeader preferenceHeader, final int position) { if (isSplitScreen()) { if (adapter.getCount() == 1) { getListView().setItemChecked(0, true); showPreferenceScreen(getListAdapter().getItem(0), null); } } else { updateSavedInstanceState(); } } @Override public final void onPreferenceHeaderRemoved( final PreferenceHeaderAdapter adapter, final PreferenceHeader preferenceHeader, final int position) { if (isSplitScreen()) { if (adapter.isEmpty()) { removeFragment(preferenceScreenFragment); showBreadCrumbs(null, null); preferenceScreenFragment = null; currentHeader = null; } else { int selectedIndex = getListView().getCheckedItemPosition(); if (selectedIndex == position) { PreferenceHeader selectedPreferenceHeader; try { selectedPreferenceHeader = getListAdapter().getItem( selectedIndex); } catch (IndexOutOfBoundsException e) { getListView().setItemChecked(selectedIndex - 1, true); selectedPreferenceHeader = getListAdapter().getItem( selectedIndex - 1); } showPreferenceScreen(selectedPreferenceHeader, null); } } } else { if (currentHeader == preferenceHeader) { showPreferenceHeaders(); hideActionBarBackButton(); resetTitle(); } updateSavedInstanceState(); } } @Override public boolean onKeyDown(final int keyCode, final KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (!isSplitScreen() && isPreferenceHeaderSelected() && !isNavigationHidden() && !(!isSplitScreen() && isButtonBarShown())) { showPreferenceHeaders(); hideActionBarBackButton(); resetTitle(); return true; } else if (isButtonBarShown()) { if (notifyOnSkip()) { return super.onKeyDown(keyCode, event); } return true; } } return super.onKeyDown(keyCode, event); } @Override public void onFragmentCreated(final Fragment fragment) { getListView().setOnItemClickListener(PreferenceActivity.this); getListAdapter().addListener(PreferenceActivity.this); if (savedInstanceState == null) { onCreatePreferenceHeaders(); } else { ArrayList<PreferenceHeader> preferenceHeaders = savedInstanceState .getParcelableArrayList(PREFERENCE_HEADERS_EXTRA); getListAdapter().addAllItems(preferenceHeaders); } if (isSplitScreen()) { getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (!getListAdapter().isEmpty()) { getListView().setItemChecked(0, true); showPreferenceScreen(getListAdapter().getItem(0), null); } } handleIntent(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { if (!isSplitScreen() && isPreferenceHeaderSelected() && isBackButtonOverridden() && !isNavigationHidden()) { showPreferenceHeaders(); hideActionBarBackButton(); resetTitle(); return true; } else if (isButtonBarShown()) { if (notifyOnSkip()) { return super.onOptionsItemSelected(item); } return true; } } return super.onOptionsItemSelected(item); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.savedInstanceState = savedInstanceState; setContentView(R.layout.preference_activity); preferenceHeaderParentView = (ViewGroup) findViewById(R.id.preference_header_parent); preferenceScreenParentView = (ViewGroup) findViewById(R.id.preference_screen_parent); preferenceScreenContainer = (ViewGroup) findViewById(R.id.preference_screen_container); breadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.bread_crumbs_view); if (breadCrumbs != null) { breadCrumbs.setMaxVisible(2); breadCrumbs.setActivity(this); } breadCrumbsSeperator = findViewById(R.id.bread_crumbs_separator); shadowView = findViewById(R.id.shadow_view); preferenceHeaderFragment = new PreferenceHeaderFragment(); preferenceHeaderFragment.addFragmentListener(this); overrideBackButton(true); setBreadCrumbsSeparatorColor(getResources().getColor(R.color.separator)); setShadowColor(getResources().getColor(R.color.shadow)); showPreferenceHeaders(); } @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(CURRENT_BUNDLE_EXTRA, (currentHeader != null) ? currentHeader.getExtras() : null); outState.putCharSequence(CURRENT_TITLE_EXTRA, currentTitle); outState.putCharSequence(CURRENT_SHORT_TITLE_EXTRA, currentShortTitle); outState.putParcelable(CURRENT_PREFERENCE_HEADER_EXTRA, currentHeader); outState.putParcelableArrayList(PREFERENCE_HEADERS_EXTRA, getListAdapter().getAllItems()); } @Override protected void onRestoreInstanceState(final Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Bundle currentBundle = savedInstanceState .getBundle(CURRENT_BUNDLE_EXTRA); CharSequence title = savedInstanceState .getCharSequence(CURRENT_TITLE_EXTRA); CharSequence shortTitle = savedInstanceState .getCharSequence(CURRENT_SHORT_TITLE_EXTRA); PreferenceHeader currentPreferenceHeader = savedInstanceState .getParcelable(CURRENT_PREFERENCE_HEADER_EXTRA); if (currentPreferenceHeader != null) { showPreferenceScreen(currentPreferenceHeader, currentBundle); showBreadCrumbs(title, shortTitle); if (isSplitScreen()) { int selectedIndex = getListAdapter().indexOf( currentPreferenceHeader); if (selectedIndex != -1) { getListView().setItemChecked(selectedIndex, true); } } } } /** * The method, which is invoked, when the preference headers should be * created. This method has to be overridden by implementing subclasses to * add the preference headers. */ protected void onCreatePreferenceHeaders() { return; } }
package de.mrapp.android.preference; import java.util.Collection; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; import de.mrapp.android.preference.adapter.PreferenceHeaderAdapter; import de.mrapp.android.preference.fragment.FragmentListener; import de.mrapp.android.preference.fragment.PreferenceHeaderFragment; import de.mrapp.android.preference.parser.PreferenceHeaderParser; /** * An activity, which provides a navigation for multiple groups of preferences, * in which each group is represented by an instance of the class * {@link PreferenceHeader}. On devices with small screens, e.g. on smartphones, * the navigation is designed to use the whole available space and selecting an * item causes the corresponding preferences to be shown full screen as well. On * devices with large screens, e.g. on tablets, the navigation and the * preferences of the currently selected item are shown split screen. * * @author Michael Rapp * * @since 1.0.0 */ public abstract class PreferenceActivity extends Activity implements FragmentListener, OnItemClickListener { /** * The fragment, which contains the preference headers and provides the * navigation to each header's fragment. */ private PreferenceHeaderFragment preferenceHeaderFragment; /** * The parent view of the fragment, which provides the navigation to each * preference header's fragment. */ private ViewGroup preferenceHeaderParentView; /** * The parent view of the fragment, which is used to show the preferences of * the currently selected preference header on devices with a large screen. */ private ViewGroup preferenceScreenParentView; /** * The full qualified class name of the fragment, which is currently shown * or null, if no preference header is currently selected. */ private String currentlyShownFragment; /** * Shows the fragment, which corresponds to a specific preference header. * * @param preferenceHeader * The preference header, the fragment, which should be shown, * corresponds to, as an instance of the class * {@link PreferenceHeader}. The preference header may not be * null */ private void showPreferenceScreen(final PreferenceHeader preferenceHeader) { currentlyShownFragment = preferenceHeader.getFragment(); Fragment fragment = Fragment.instantiate(this, currentlyShownFragment); replacePreferenceHeaderFragment(fragment, FragmentTransaction.TRANSIT_FRAGMENT_FADE); } /** * Shows the fragment, which provides the navigation to each preference * header's fragment. */ private void showPreferenceHeaders() { int transition = 0; if (currentlyShownFragment != null) { transition = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; currentlyShownFragment = null; } replacePreferenceHeaderFragment(preferenceHeaderFragment, transition); } /** * Replaces the fragment, which is currently contained by the parent view of * the fragment, which provides the navigation to each preference header's * fragment, by an other fragment. * * @param fragment * The fragment, which should replace the current fragment, as an * instance of the class {@link Fragment}. The fragment may not * be null * @param transition * The transition, which should be shown when replacing the * fragment, as an {@link Integer} value or 0, if no transition * should be shown */ private void replacePreferenceHeaderFragment(final Fragment fragment, final int transition) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.setTransition(transition); transaction.replace(R.id.preference_header_parent, fragment); transaction.commit(); } /** * Returns the parent view of the fragment, which provides the navigation to * each preference header's fragment. On devices with a small screen this * parent view is also used to show a preference header's fragment, when a * header is currently selected. * * @return The parent view of the fragment, which provides the navigation to * each preference header's fragment, as an instance of the class * {@link ViewGroup}. The parent view may not be null */ public final ViewGroup getPreferenceHeaderParentView() { return preferenceHeaderParentView; } /** * Returns the parent view of the fragment, which is used to show the * preferences of the currently selected preference header on devices with a * large screen. * * @return The parent view of the fragment, which is used to show the * preferences of the currently selected preference header, as an * instance of the class {@link ViewGroup} or null, if the device * has a small screen */ public final ViewGroup getPreferenceScreenParentView() { return preferenceScreenParentView; } /** * Returns the list view, which is used to show the preference headers. * * @return The list view, which is used to show the preference header, as an * instance of the class {@link ListView}. The list view may not be * null */ public final ListView getListView() { return preferenceHeaderFragment.getListView(); } /** * Returns the adapter, which provides the preference headers for * visualization using the list view. * * @return The adapter, which provides the preference headers for * visualization using the list view, as an instance of the class * {@link PreferenceHeaderAdapter}. The adapter may not be null */ public final PreferenceHeaderAdapter getListAdapter() { return preferenceHeaderFragment.getListAdapter(); } /** * Adds all preference headers, which are specified by a specific XML * resource. * * @param resourceId * The resource id of the XML file, which specifies the * preference headers, as an {@link Integer} value. The resource * id must correspond to a valid XML resource */ public final void addPreferenceHeadersFromResource(final int resourceId) { getListAdapter().addAllItems( PreferenceHeaderParser.fromResource(this, resourceId)); } /** * Adds a new preference header. * * @param preferenceHeader * The preference header, which should be added, as an instance * of the class {@link PreferenceHeader}. The preference header * may not be null * @return */ public final void addPreferenceHeader( final PreferenceHeader preferenceHeader) { getListAdapter().addItem(preferenceHeader); } /** * Adds all preference headers, which are contained by a specific * collection. * * @param preferenceHeaders * The collection, which contains the preference headers, which * should be added, as an instance of the type {@link Collection} * or an empty collection, if no preference headers should be * added */ public final void addAllPreferenceHeaders( final Collection<PreferenceHeader> preferenceHeaders) { getListAdapter().addAllItems(preferenceHeaders); } /** * Removes a specific preference header. * * @param preferenceHeader * The preference header, which should be removed, as an instance * of the class {@link PreferenceHeader}. The preference header * may not be null * @return True, if the preference header has been removed, false otherwise */ public final boolean removePreferenceHeader( final PreferenceHeader preferenceHeader) { return getListAdapter().removeItem(preferenceHeader); } /** * Removes all preference headers. */ public final void clearPreferenceHeaders() { getListAdapter().clear(); } /** * Returns, whether the preference headers and the corresponding fragments * are shown split screen, or not. * * @return True, if the preference headers and the corresponding fragments * are shown split screen, false otherwise */ public final boolean isSplitScreen() { return getPreferenceScreenParentView() != null; } @Override public final void onFragmentCreated(final Fragment fragment) { getListView().setOnItemClickListener(this); onCreatePreferenceHeaders(); } @Override public final void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { showPreferenceScreen(getListAdapter().getItem(position)); } @Override protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.preference_activity); preferenceHeaderParentView = (ViewGroup) findViewById(R.id.preference_header_parent); preferenceScreenParentView = (ViewGroup) findViewById(R.id.preference_screen_parent); preferenceHeaderFragment = new PreferenceHeaderFragment(); preferenceHeaderFragment.addFragmentListener(this); showPreferenceHeaders(); } /** * The method, which is invoked, when the preference headers should be * created. This method has to be overridden by implementing subclasses to * add the preference headers. */ protected abstract void onCreatePreferenceHeaders(); }
package com.alessiodp.parties.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import com.alessiodp.parties.Parties; import com.alessiodp.parties.configuration.Variables; import com.alessiodp.parties.handlers.LogHandler; import com.alessiodp.parties.objects.Party; import com.alessiodp.parties.objects.ThePlayer; public class SQLDatabase { private Parties plugin; private Connection connection; private boolean failed; private String username; private String password; private String url; public SQLDatabase(Parties instance, String un, String pw, String url) { plugin = instance; username = un; password = pw; this.url = url; failed = false; connection = getConnection(); if(connection==null) failed = true; else initTables(); } public boolean isFailed(){ return failed; } private boolean haveDriver() { try { Class.forName("com.mysql.jdbc.Driver"); return true; } catch (ClassNotFoundException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "MySQL Driver missing: " + ex.getMessage()); LogHandler.log(1, "MySQL Driver missing: " + ex.getMessage()); } return false; } public Connection getConnection() { try { if(!haveDriver()) return null; if (connection == null) return DriverManager.getConnection(url, username, password); if (connection.isValid(3)) { return connection; } return DriverManager.getConnection(url, username, password); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Can't connect to the server SQL: " + ex.getMessage()); LogHandler.log(1, "Can't connect to the server SQL: " + ex.getMessage()); } return null; } /* * Migration */ public ArrayList<String> getAllParties(){ try { connection = getConnection(); if (connection == null) return null; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT name FROM "+Variables.database_sql_tables_parties+";"); ArrayList<String> list = new ArrayList<String>(); while (res.next()) { list.add(res.getString("name")); } return list; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Player get all parties: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Player get all parties: " + ex.getMessage()); } return null; } public ArrayList<String> getAllPlayers(){ try { connection = getConnection(); if (connection == null) return null; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT nickname FROM "+Variables.database_sql_tables_players+";"); ArrayList<String> list = new ArrayList<String>(); while (res.next()) { list.add(res.getString("nickname")); } return list; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Player get all players: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Player get all players: " + ex.getMessage()); } return null; } public ArrayList<UUID> getAllSpies(){ try{ connection = getConnection(); if(connection == null) return null; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT name FROM "+Variables.database_sql_tables_spies+";"); ArrayList<UUID> list = new ArrayList<UUID>(); while(res.next()){ list.add(UUID.fromString(res.getString("name"))); } return list; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Player get all spies: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Player get all spies: " + ex.getMessage()); } return null; } /* * Spies */ public boolean isSpy(UUID uuid){ try { connection = getConnection(); if (connection == null) return false; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM "+Variables.database_sql_tables_spies+" WHERE name='"+uuid.toString()+"';"); if(res.next()) return true; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't check if is a spy: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't check if is a spy: " + ex.getMessage()); } return false; } public void setSpy(UUID uuid, boolean value){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); if(value) statement.executeUpdate("INSERT IGNORE INTO "+Variables.database_sql_tables_spies+" (name) VALUES ('"+uuid.toString()+"');"); else statement.executeUpdate("DELETE FROM "+Variables.database_sql_tables_spies+" WHERE name='"+uuid.toString()+"';"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't set player spy: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't set player spy: " + ex.getMessage()); } } /* * Player based */ public void updatePlayer(ThePlayer tp){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); if(!tp.haveParty()) statement.executeUpdate("INSERT INTO "+Variables.database_sql_tables_players+" (nickname, party, rank) VALUES ('"+tp.getUUID().toString()+"', NULL, "+tp.getRank()+") ON DUPLICATE KEY UPDATE party=VALUES(party), rank=VALUES(rank);"); else statement.executeUpdate("INSERT INTO "+Variables.database_sql_tables_players+" (nickname, party, rank) VALUES ('"+tp.getUUID().toString()+"', '"+tp.getPartyName()+"', "+tp.getRank()+") ON DUPLICATE KEY UPDATE party=VALUES(party), rank=VALUES(rank);"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't update player: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't update player: " + ex.getMessage()); } } public void removePlayer(UUID uuid){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); statement.executeUpdate("DELETE FROM "+Variables.database_sql_tables_players+" WHERE nickname='"+uuid.toString()+"';"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't remove player: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't remove player: " + ex.getMessage()); } } public void setRank(UUID uuid, int rank){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); statement.executeUpdate("UPDATE "+Variables.database_sql_tables_players+" SET rank="+rank+" WHERE nickname='"+uuid.toString()+"';"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't set player rank: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't set player rank: " + ex.getMessage()); } } public int getRank(UUID uuid){ try { connection = getConnection(); if (connection == null) return -1; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM "+Variables.database_sql_tables_players+" WHERE nickname='"+uuid.toString()+"';"); if(res.next()) return res.getInt("rank"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get player rank: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get player rank: " + ex.getMessage()); } return -1; } public String getPlayerPartyName(UUID uuid){ try { connection = getConnection(); if (connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM "+Variables.database_sql_tables_players+" WHERE nickname='"+uuid.toString()+"';"); if(res.next()) return res.getString("party"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get player party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get player party: " + ex.getMessage()); } return ""; } public void setPartyName(UUID uuid, String name){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); statement.executeUpdate("UPDATE "+Variables.database_sql_tables_players+" SET party='"+name+"' WHERE nickname='"+uuid.toString()+"';"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't set player party name: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't set player party name: " + ex.getMessage()); } } /* * Party Based */ public Party getParty(String party){ try{ connection = getConnection(); if(connection == null) return null; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()){ Party pt = new Party(res.getString("name"), plugin); pt.setDescription(res.getString("descr")); pt.setMOTD(res.getString("motd")); pt.setPrefix(res.getString("prefix")); pt.setSuffix(res.getString("suffix")); pt.setKills(res.getInt("kills")); pt.setPassword(res.getString("password")); if(res.getString("home") != null){ String[] split = res.getString("home").split(","); World world; int x,y,z; float yaw,pitch; try{ world = Bukkit.getWorld(split[0]); x = Integer.parseInt(split[1]); y = Integer.parseInt(split[2]); z = Integer.parseInt(split[3]); yaw = Float.parseFloat(split[4]); pitch = Float.parseFloat(split[5]); pt.setHome(new Location(world, x, y, z, yaw, pitch)); } catch(Exception ex){ pt.setHome(null); } } pt.setLeader(UUID.fromString(res.getString("leader"))); pt.setMembers(getMembersParty(party)); return pt; } } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't check if exist party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't check if exist party: " + ex.getMessage()); } return null; } public void updateParty(Party party){ try { connection = getConnection(); if (connection == null) return; String home = ""; if(party.getHome() != null) home = party.getHome().getWorld().getName() + "," + party.getHome().getBlockX() + "," + party.getHome().getBlockY() + "," + party.getHome().getBlockZ() + "," + party.getHome().getYaw() + "," + party.getHome().getPitch(); Statement statement = connection.createStatement(); statement.executeUpdate("INSERT INTO "+Variables.database_sql_tables_parties+" (name, leader, descr, motd, prefix, suffix, kills, password, home) VALUES ('"+party.getName()+"', '"+party.getLeader().toString()+"', '"+party.getDescription()+"', '"+party.getMOTD()+"', '"+party.getPrefix()+"', '"+party.getSuffix()+"', "+party.getKills()+", '"+party.getPassword()+"', '"+home+"') ON DUPLICATE KEY UPDATE leader=VALUES(leader), descr=VALUES(descr), motd=VALUES(motd), prefix=VALUES(prefix), suffix=VALUES(suffix), kills=VALUES(kills), password=VALUES(password), home=VALUES(home);"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't update party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't update party: " + ex.getMessage()); } } public void renameParty(String prev, String next){ Party old = new Party(getParty(prev)); old.setName(next); updateParty(old); removeParty(prev); } public void removeParty(String party){ try { connection = getConnection(); if (connection == null) return; Statement statement = connection.createStatement(); statement.executeUpdate("DELETE FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't remove party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't remove party: " + ex.getMessage()); } } public boolean existParty(String party){ try{ connection = getConnection(); if(connection == null) return false; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return true; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't check if exist party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't check if exist party: " + ex.getMessage()); } return false; } public ArrayList<UUID> getMembersParty(String party){ ArrayList<UUID> list = new ArrayList<UUID>(); try { connection = getConnection(); if (connection == null) return list; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT nickname FROM "+Variables.database_sql_tables_players+" WHERE party='"+party+"';"); while (res.next()) { list.add(UUID.fromString(res.getString("nickname"))); } return list; } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Player get all players in party: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Player get all players in party: " + ex.getMessage()); } return list; } public String getPartyLeader(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT leader FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("leader"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party leader: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party leader: " + ex.getMessage()); } return ""; } public String getPartyDesc(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT descr FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("descr"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party description: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party description: " + ex.getMessage()); } return ""; } public String getPartyMotd(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT motd FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("motd"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party motd: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party motd: " + ex.getMessage()); } return ""; } public String getPartyPrefix(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT prefix FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("prefix"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party prefix: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party prefix: " + ex.getMessage()); } return ""; } public String getPartySuffix(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT suffix FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("suffix"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party suffix: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party suffix: " + ex.getMessage()); } return ""; } public int getPartyKills(String party){ try{ connection = getConnection(); if(connection == null) return 0; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT kills FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getInt("kills"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party kills: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party kills: " + ex.getMessage()); } return 0; } public String getPartyPassword(String party){ try{ connection = getConnection(); if(connection == null) return ""; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT password FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()) return res.getString("password"); } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party kills: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party kills: " + ex.getMessage()); } return ""; } public Location getPartyHome(String party) { try{ connection = getConnection(); if(connection == null) return null; Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT home FROM "+Variables.database_sql_tables_parties+" WHERE name='"+party+"';"); if(res.next()){ String[] split = res.getString("home").split(","); World world; int x,y,z; float yaw,pitch; try{ world = Bukkit.getWorld(split[0]); x = Integer.parseInt(split[1]); y = Integer.parseInt(split[2]); z = Integer.parseInt(split[3]); yaw = Float.parseFloat(split[4]); pitch = Float.parseFloat(split[5]); } catch(Exception ex){ return null; } return new Location(world, x, y, z, yaw, pitch); } } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Query: Can't get party home: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Query: Can't get party home: " + ex.getMessage()); } return null; } /* * TABLES */ public void initTables() { if (!checkTable(Variables.database_sql_tables_parties)) createTable(Variables.database_sql_tables_parties, 1); else convertTableParties(Variables.database_sql_tables_parties); if (!checkTable(Variables.database_sql_tables_players)) createTable(Variables.database_sql_tables_players, 2); else convertTablePlayers(Variables.database_sql_tables_players); if(!checkTable(Variables.database_sql_tables_spies)) createTable(Variables.database_sql_tables_spies, 3); checkConvertedLeaders(); } public boolean checkTable(String name) { try { connection = getConnection(); if (connection == null) { return false; } Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM " + name + ";"); if (result != null) return true; } catch (SQLException ex) { } return false; } public void convertTableParties(String name){ try { connection = getConnection(); if (connection == null) { return; } Statement statement = connection.createStatement(); statement.executeQuery("SELECT leader FROM " + name); return; } catch (SQLException ex) {} plugin.log(ConsoleColors.CYAN.getCode() + "Converting old parties table (MySQL)"); LogHandler.log(1, "Converting old parties table (MySQL)"); try { connection = getConnection(); if (connection == null) { return; } Statement statement = connection.createStatement(); statement.executeUpdate("RENAME TABLE "+name+" TO "+name+"_temp;"); createTable(Variables.database_sql_tables_parties, 1); ResultSet rs = statement.executeQuery("SELECT * FROM "+name+"_temp;"); while(rs.next()){ /* * Search first old leader */ String leader = ""; try { Statement statementsub = connection.createStatement(); ResultSet res = statementsub.executeQuery("SELECT nickname FROM "+Variables.database_sql_tables_players+" WHERE party='"+rs.getString("name")+"' AND isLeader=1;"); while (res.next()) { leader = res.getString("nickname"); } } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error searching old leader in party: " + ex.getMessage()); LogHandler.log(1, "Error searching old leader in party: " + ex.getMessage()); } Statement statement2 = connection.createStatement(); statement2.executeUpdate("INSERT INTO "+name+" (name, leader, descr, motd, prefix, suffix, kills, password, home) VALUES ('"+rs.getString("name")+"', '" + leader + "', '"+rs.getString("descr")+"', '"+rs.getString("motd")+"', '"+rs.getString("prefix")+"', '"+rs.getString("suffix")+"', "+rs.getInt("kills")+", '', '"+rs.getString("home")+"') ON DUPLICATE KEY UPDATE leader=VALUES(leader), descr=VALUES(descr), motd=VALUES(motd), prefix=VALUES(prefix), suffix=VALUES(suffix), kills=VALUES(kills), password=VALUES(password), home=VALUES(home);"); } statement.executeUpdate("DROP TABLE "+name+"_temp"); return; } catch (SQLException ex) { ex.printStackTrace(); } } public void convertTablePlayers(String name){ try { connection = getConnection(); if (connection == null) { return; } Statement statement = connection.createStatement(); statement.executeQuery("SELECT isLeader FROM " + name); /* Here give error if isLeader doesn't exist (so it doesnt is old) */ plugin.log(ConsoleColors.CYAN.getCode() + "Converting old players table (MySQL)"); LogHandler.log(1, "Converting old players table (MySQL)"); Statement substatement = connection.createStatement(); substatement.executeUpdate("RENAME TABLE "+name+" TO "+name+"_temp;"); createTable(name, 2); ResultSet rs = substatement.executeQuery("SELECT * FROM "+name+"_temp;"); while(rs.next()){ Statement statement3 = connection.createStatement(); statement3.executeUpdate("INSERT INTO "+name+" (nickname, party, rank) VALUES ('"+rs.getString("nickname")+"', '"+rs.getString("party")+ "', '"+Variables.rank_default+"') ON DUPLICATE KEY UPDATE party=VALUES(party), rank=VALUES(rank);"); } statement.executeUpdate("DROP TABLE "+Variables.database_sql_tables_players+"_temp" + ";"); } catch (SQLException ex) {} } public void checkConvertedLeaders(){ try { connection = getConnection(); if (connection == null) { return; } Statement statement = connection.createStatement(); ResultSet res = statement.executeQuery("SELECT * FROM " + Variables.database_sql_tables_parties + ";"); while (res.next()) { String leader = res.getString("leader"); if(leader == null || leader.isEmpty()) this.removeParty(res.getString("name")); else setRank(UUID.fromString(leader), Variables.rank_last); } return; } catch (SQLException ex) {} } public void createTable(String name, int type) { try { connection = getConnection(); if (connection == null) { return; } Statement statement = connection.createStatement(); switch (type) { case 1: statement.executeUpdate("CREATE TABLE " + name + " (name VARCHAR(40) NOT NULL, leader VARCHAR(40) DEFAULT '', descr VARCHAR(50) DEFAULT '', motd VARCHAR(255) DEFAULT '', prefix VARCHAR(25) DEFAULT '', suffix VARCHAR(25) DEFAULT '', kills INT DEFAULT 0, password VARCHAR(64) DEFAULT '', home VARCHAR(128) DEFAULT '', PRIMARY KEY (name));"); break; case 2: statement.executeUpdate("CREATE TABLE " + name + " (nickname VARCHAR(40) NOT NULL, party VARCHAR(25) DEFAULT '',rank INT DEFAULT 0, PRIMARY KEY (nickname));"); break; case 3: statement.executeUpdate("CREATE TABLE " + name + " (name VARCHAR(40) NOT NULL, PRIMARY KEY (name));"); } } catch (SQLException ex) { plugin.log(Level.WARNING, ConsoleColors.RED.getCode() + "Error in SQL Table Creation: " + ex.getMessage()); LogHandler.log(1, "Error in SQL Table Creation: " + ex.getMessage()); } } }
package com.bloatit.web.pages.demand; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.bloatit.framework.Demand; import com.bloatit.framework.Translation; import com.bloatit.framework.managers.DemandManager; import com.bloatit.web.htmlrenderer.htmlcomponent.HtmlBlock; import com.bloatit.web.htmlrenderer.htmlcomponent.HtmlComponent; import com.bloatit.web.htmlrenderer.htmlcomponent.HtmlContainer; import com.bloatit.web.htmlrenderer.htmlcomponent.HtmlTitle; import com.bloatit.web.server.Page; import com.bloatit.web.server.Session; import com.bloatit.web.utils.PageNotFoundException; public class DemandPage extends Page { private final Demand demand; public DemandPage(Session session, Map<String, String> parameters) { super(session, parameters); if (parameters.containsKey("id")) { Integer id = null; try { id = new Integer(parameters.get("id")); demand = DemandManager.getDemandById(id); } catch (final NumberFormatException e) { throw new PageNotFoundException("Demand id not found " + id, null); } } else { demand = null; } generateOutputParams(); } public DemandPage(Session session, Map<String, String> parameters, Demand demand) { super(session, parameters); if (demand == null) { throw new PageNotFoundException("Demand shouldn't be null", null); } this.demand = demand; generateOutputParams(); } public DemandPage(Session session, Demand demand) { this(session, new HashMap<String, String>(), demand); } private void generateOutputParams() { parameters.put("id", new Integer(demand.getId()).toString()); parameters.put("title", demand.getTitle()); } @Override public String getCode() { return "demand"; } @Override public String getTitle() { return "Demand ..."; } @Override public boolean isStable() { return true; } public Demand getDemand() { return demand; } @Override protected HtmlComponent generateContent() { needCustomDesign(); final HtmlContainer page = new HtmlContainer(); { Locale defaultLocale = session.getLanguage().getLocale(); Translation translatedDescription = demand.getDescription().getTranslationOrDefault(defaultLocale); page.add(new HtmlTitle(translatedDescription.getTitle(), "pageTitle")); page.add(new DemandHeadComponent(this)); page.add(generateBody()); } return page; } private HtmlComponent generateBodyLeft() { final HtmlBlock left = new HtmlBlock("leftColumn"); { left.add(new DemandTabPane(this)); // Comments left.add(new DemandCommentListComponent(this)); } return left; } private HtmlComponent generateBodyRight() { final HtmlBlock right = new HtmlBlock("rightColumn"); { HtmlBlock rightBlock = new HtmlBlock("right_block"); { rightBlock.add(new DemandSummaryComponent(this)); } right.add(rightBlock); } return right; } private HtmlComponent generateBody() { HtmlBlock demandBody = new HtmlBlock("demand_body"); { demandBody.add(generateBodyLeft()); demandBody.add(generateBodyRight()); } return demandBody; } }
package edu.mit.streamjit.impl.distributed; import java.util.concurrent.CountDownLatch; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionInfo; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionProvider; import edu.mit.streamjit.impl.distributed.node.TCPInputChannel; public class TailChannel extends TCPInputChannel { int limit; int count; CountDownLatch latch; public TailChannel(Buffer buffer, TCPConnectionProvider conProvider, TCPConnectionInfo conInfo, String bufferTokenName, int debugPrint, int limit) { super(buffer, conProvider, conInfo, bufferTokenName, debugPrint); this.limit = limit; count = 0; latch = new CountDownLatch(1); } @Override public void receiveData() { super.receiveData(); count++; // System.err.println(count); if (count > limit) latch.countDown(); } public void awaitForFixInput() throws InterruptedException { latch.await(); } public void reset() { latch.countDown(); latch = new CountDownLatch(1); count = 0; } }
package com.conveyal.taui.models; import com.conveyal.geojson.GeometryDeserializer; import com.conveyal.geojson.GeometrySerializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.vividsolutions.jts.geom.Geometry; import java.util.List; /** * Add a trip pattern. */ public class AddTripPattern extends Modification { public String name; public List<Segment> segments; public boolean bidirectional; public List<Timetable> timetables; public String getType() { return "add-trip-pattern"; } /** represents a single segment of an added trip pattern (between two user-specified points) */ public static class Segment { /** Is there a stop at the start of this segment */ public boolean stopAtStart; /** Is there a stop at the end of this segment */ public boolean stopAtEnd; /** If this segment starts at an existing stop, what is its feed-scoped stop ID? */ public String fromStopId; /** If this segment ends at an existing stop, what is its feed-scoped stop ID? */ public String toStopId; /** spacing between stops in this segment, meters */ public int spacing; /** * Geometry of this segment * Generally speaking, this will be a LineString, but the first segment may be a Point * iff there are no more segments. This is used when someone first starts drawing a line and * they have only drawn one stop so far. Of course a transit line with only one stop would * not be particularly useful. */ @JsonDeserialize(using= GeometryDeserializer.class) @JsonSerialize(using= GeometrySerializer.class) public Geometry geometry; } public static class Timetable { public String id; /** Days of the week on which this service is active */ public boolean monday, tuesday, wednesday, thursday, friday, saturday, sunday; /** allow naming timetables so it's easier to see what's going on */ public String name; /** Speed, kilometers per hour, for each segment */ public int[] segmentSpeeds; /** start time (seconds since GTFS midnight) */ public int startTime; /** end time for frequency-based trips (seconds since GTFS midnight) */ public int endTime; /** Dwell time at each stop, seconds */ public int dwellTime; /** Dwell times at specific stops, seconds */ public int[] dwellTimes; /** headway for frequency-based patterns */ public int headwaySecs; /** should this be specified as an exact schedule */ public boolean exactTimes; /** Phase at a stop that is in this modification */ public String phaseAtStop; /** * Phase from a timetable (frequency entry) on another modification. * Syntax is `${modification.id}:${timetable.id}` */ public String phaseFromTimetable; /** Phase from a stop that can be found in the phased from modification's stops */ public String phaseFromStop; /** Amount of time to phase from the other lines frequency */ public int phaseSeconds; } }
package com.coremedia.iso; import com.coremedia.iso.boxes.Box; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Property file based BoxFactory */ public class PropertyBoxParserImpl extends AbstractBoxParser { Properties mapping; Pattern constuctorPattern = Pattern.compile("(.*)\\((.*?)\\)"); public PropertyBoxParserImpl(String... customProperties) { InputStream is = getClass().getResourceAsStream("/isoparser-default.properties"); try { mapping = new Properties(); try { mapping.load(is); Enumeration<URL> enumeration = Thread.currentThread().getContextClassLoader().getResources("isoparser-custom.properties"); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); InputStream customIS = url.openStream(); try { mapping.load(customIS); } finally { customIS.close(); } } for (String customProperty : customProperties) { mapping.load(getClass().getResourceAsStream(customProperty)); } } catch (IOException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); // ignore - I can't help } } } public PropertyBoxParserImpl(Properties mapping) { this.mapping = mapping; } @Override public Box createBox(String type, byte[] userType, String parent) { invoke(type, userType, parent); try { Class<Box> clazz = (Class<Box>) Class.forName(clazzName); if (param.length > 0) { Class[] constructorArgsClazz = new Class[param.length]; Object[] constructorArgs = new Object[param.length]; for (int i = 0; i < param.length; i++) { if ("userType".equals(param[i])) { constructorArgs[i] = userType; constructorArgsClazz[i] = byte[].class; } else if ("type".equals(param[i])) { constructorArgs[i] = type; constructorArgsClazz[i] = String.class; } else if ("parent".equals(param[i])) { constructorArgs[i] = parent; constructorArgsClazz[i] = String.class; } else { throw new InternalError("No such param: " + param[i]); } } Constructor<Box> constructorObject = clazz.getConstructor(constructorArgsClazz); return constructorObject.newInstance(constructorArgs); } else { return clazz.newInstance(); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } StringBuilder buildLookupStrings = new StringBuilder(); String clazzName; String param[]; static String[] EMPTY_STRING_ARRAY = new String[0]; public void invoke(String type, byte[] userType, String parent) { String constructor; if (userType != null) { if (!"uuid".equals((type))) { throw new RuntimeException("we have a userType but no uuid box type. Something's wrong"); } constructor = mapping.getProperty("uuid[" + Hex.encodeHex(userType).toUpperCase() + "]"); if (constructor == null) { constructor = mapping.getProperty((parent) + "-uuid[" + Hex.encodeHex(userType).toUpperCase() + "]"); } if (constructor == null) { constructor = mapping.getProperty("uuid"); } } else { constructor = mapping.getProperty((type)); if (constructor == null) { String lookup = buildLookupStrings.append(parent).append('-').append(type).toString(); buildLookupStrings.setLength(0); constructor = mapping.getProperty(lookup); } } if (constructor == null) { constructor = mapping.getProperty("default"); } if (constructor == null) { throw new RuntimeException("No box object found for " + type); } if (!constructor.endsWith(")")) { param = EMPTY_STRING_ARRAY; clazzName = constructor; } else { Matcher m = constuctorPattern.matcher(constructor); boolean matches = m.matches(); if (!matches) { throw new RuntimeException("Cannot work with that constructor: " + constructor); } clazzName = m.group(1); if (m.group(2).length() == 0) { param = EMPTY_STRING_ARRAY; } else { param = m.group(2).length() > 0 ? m.group(2).split(",") : new String[]{}; } } } }
package com.elmakers.mine.bukkit.block; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.spell.UndoableSpell; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.inventory.InventoryHolder; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.entity.EntityData; /** * Implements a Collection of Blocks, for quick getting/putting while iterating * over a set or area of blocks. * * This stores BlockData objects, which are hashable via their Persisted * inheritance, and their LocationData id (which itself has a hash function * based on world name and BlockVector's hash function) * */ public class UndoList extends BlockList implements com.elmakers.mine.bukkit.api.block.UndoList { public static Set<Material> attachables; public static Set<Material> attachablesWall; public static Set<Material> attachablesDouble; protected static Map<Long, BlockData> modified = new HashMap<Long, BlockData>(); protected HashSet<Long> attached; private boolean loading = false; protected List<WeakReference<Entity>> entities; protected List<Runnable> runnables; protected HashMap<UUID, EntityData> modifiedEntities; protected final Mage owner; protected final Plugin plugin; protected boolean undone = false; protected int timeToLive = 0; protected boolean applyPhysics = false; protected boolean bypass = false; protected final long createdTime; protected long modifiedTime; protected long scheduledTime; // Doubly-linked list protected UndoableSpell spell; protected CastContext context; protected UndoQueue undoQueue; protected UndoList next; protected UndoList previous; protected String name; private boolean undoEntityEffects = true; private Set<EntityType> undoEntityTypes = null; protected boolean undoBreakable = false; protected boolean undoReflective = false; public UndoList(Mage mage, String name) { this(mage); this.name = name; } public UndoList(Mage mage) { this.owner = mage; this.plugin = owner.getController().getPlugin(); createdTime = System.currentTimeMillis(); modifiedTime = createdTime; } public void setSpell(UndoableSpell spell) { this.spell = spell; this.context = spell == null ? null : spell.getCurrentCast(); } @Override public int size() { return ( (blockList == null ? 0 :blockList.size()) + (entities == null ? 0 : entities.size())) + (runnables == null ? 0 : runnables.size()); } @Override public boolean isEmpty() { return ( (blockList == null || blockList.isEmpty()) && (entities == null || entities.isEmpty()) && (runnables == null || runnables.isEmpty())); } public boolean isComplete() { return undone; } public void setScheduleUndo(int ttl) { timeToLive = ttl; updateScheduledUndo(); } public void updateScheduledUndo() { if (timeToLive > 0) { scheduledTime = System.currentTimeMillis() + timeToLive; } } public int getScheduledUndo() { return timeToLive; } @Override public boolean contains(Block block) { if (blockIdMap == null) return false; Long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(block); if (attached != null && attached.contains(blockId)) return false; return blockIdMap.contains(blockId); } @Override public boolean contains(BlockData blockData) { if (blockIdMap == null || blockData == null) { return false; } Long blockId = blockData.getId(); if (attached != null && attached.contains(blockId)) return false; return blockIdMap.contains(blockData.getId()); } @Override public boolean add(BlockData blockData) { if (bypass) return true; if (!super.add(blockData)) { return false; } modifiedTime = System.currentTimeMillis(); register(blockData); blockData.setUndoList(this); if (loading) return true; if (attached != null) { attached.remove(blockData.getId()); } addAttachable(blockData, BlockFace.NORTH, attachablesWall); addAttachable(blockData, BlockFace.SOUTH, attachablesWall); addAttachable(blockData, BlockFace.EAST, attachablesWall); addAttachable(blockData, BlockFace.WEST, attachablesWall); addAttachable(blockData, BlockFace.UP, attachables); addAttachable(blockData, BlockFace.DOWN, attachables); return true; } protected boolean addAttachable(BlockData block, BlockFace direction, Set<Material> materials) { Block testBlock = block.getBlock().getRelative(direction); Long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); // This gets called recursively, so don't re-process anything if (blockIdMap != null && blockIdMap.contains(blockId)) { return false; } if (attached != null && attached.contains(blockId)) { return false; } Material material = testBlock.getType(); if (material.isBurnable() || (materials != null && materials.contains(material))) { BlockData newBlock = new com.elmakers.mine.bukkit.block.BlockData(testBlock); if (super.add(newBlock)) { register(newBlock); newBlock.setUndoList(this); if (attached == null) { attached = new HashSet<Long>(); } attached.add(blockId); if (attachablesDouble != null && attachablesDouble.contains(material)) { if (direction != BlockFace.UP) { addAttachable(newBlock, BlockFace.DOWN, materials); } else if (direction != BlockFace.DOWN) { addAttachable(newBlock, BlockFace.UP, materials); } } return true; } } return false; } public static BlockData register(Block block) { BlockData blockData = new com.elmakers.mine.bukkit.block.BlockData(block); register(blockData); return blockData; } public static void register(BlockData blockData) { BlockData priorState = modified.get(blockData.getId()); if (priorState != null) { priorState.setNextState(blockData); blockData.setPriorState(priorState); } modified.put(blockData.getId(), blockData); } public void commit() { unlink(); if (blockList == null) return; for (BlockData block : blockList) { commit(block); } } public static void commit(com.elmakers.mine.bukkit.api.block.BlockData block) { modified.remove(block.getId()); BlockData currentState = modified.get(block.getId()); if (currentState == block) { modified.remove(block.getId()); } block.commit(); } @Override public boolean remove(Object o) { if (o instanceof BlockData) { BlockData block = (BlockData)o; removeFromModified(block, block.getPriorState()); } return super.remove(o); } protected static void removeFromModified(BlockData block, BlockData priorState) { BlockData currentState = modified.get(block.getId()); if (currentState == block) { if (priorState == null) { modified.remove(block.getId()); } else { modified.put(block.getId(), priorState); } } } public boolean undo(BlockData undoBlock, boolean applyPhysics) { BlockData priorState = undoBlock.getPriorState(); // Remove any tagged metadata if (undoBreakable) { undoBlock.getBlock().removeMetadata("breakable", plugin); } if (undoReflective) { undoBlock.getBlock().removeMetadata("backfire", plugin); } if (undoBlock.undo(applyPhysics)) { removeFromModified(undoBlock, priorState); return true; } return false; } public void undoEntityEffects() { // This part doesn't happen in a batch, and may lag on large lists if (entities != null || modifiedEntities != null) { if (entities != null) { for (WeakReference<Entity> entityReference : entities) { Entity entity = entityReference.get(); if (entity != null && entity.isValid()) { entity.remove(); } } entities = null; } if (modifiedEntities != null) { for (EntityData data : modifiedEntities.values()) { if (!undoEntityEffects && undoEntityTypes != null && !undoEntityTypes.contains(data.getType())) continue; data.undo(); } modifiedEntities = null; } } } public void undo() { undo(false); } public void undo(boolean blocking) { undo(blocking, true); if (isScheduled()) { owner.getController().cancelScheduledUndo(this); } } public void undoScheduled(boolean blocking) { undo(blocking, false); } public void undoScheduled() { undoScheduled(false); } public void undo(boolean blocking, boolean undoEntities) { undoEntityEffects = undoEntityEffects || undoEntities; unlink(); if (isComplete()) return; undone = true; if (context != null) { context.cancelEffects(); } if (runnables != null) { for (Runnable runnable : runnables) { runnable.run(); } runnables = null; } if (blockList == null) { undoEntityEffects(); return; } // Block changes will be performed in a batch UndoBatch batch = new UndoBatch(this); if (blocking) { while (!batch.isFinished()) { batch.process(1000); } } else { owner.addUndoBatch(batch); } blockList = null; } @Override public void load(ConfigurationSection node) { loading = true; super.load(node); loading = false; timeToLive = node.getInt("time_to_live", timeToLive); name = node.getString("name", name); applyPhysics = node.getBoolean("apply_physics", applyPhysics); } @Override public void save(ConfigurationSection node) { super.save(node); node.set("time_to_live", (Integer)timeToLive); node.set("name", name); node.set("apply_physics", applyPhysics); } public void watch(Entity entity) { if (entity == null) return; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; if (worldName == null) worldName = entity.getWorld().getName(); entity.setMetadata("MagicBlockList", new FixedMetadataValue(plugin, this)); modifiedTime = System.currentTimeMillis(); } public void add(Entity entity) { if (entity == null) return; if (entities == null) entities = new ArrayList<WeakReference<Entity>>(); if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; entities.add(new WeakReference<Entity>(entity)); if (this.isScheduled()) { entity.setMetadata("temporary", new FixedMetadataValue(plugin, true)); } watch(entity); contain(entity.getLocation().toVector()); modifiedTime = System.currentTimeMillis(); } public void add(Runnable runnable) { if (runnable == null) return; if (runnables == null) runnables = new LinkedList<Runnable>(); runnables.add(runnable); modifiedTime = System.currentTimeMillis(); } public EntityData modify(Entity entity) { EntityData entityData = null; if (entity == null) return entityData; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return entityData; if (worldName == null) worldName = entity.getWorld().getName(); // Check to see if this is something we spawned, and has now been destroyed UUID entityId = entity.getUniqueId(); if (entities != null && entities.contains(entityId) && !entity.isValid()) { entities.remove(entityId); } else { if (modifiedEntities == null) modifiedEntities = new HashMap<UUID, EntityData>(); entityData = modifiedEntities.get(entityId); if (entityData == null) { entityData = new EntityData(entity); modifiedEntities.put(entityId, entityData); } } modifiedTime = System.currentTimeMillis(); return entityData; } @Override public EntityData damage(Entity entity, double damage) { EntityData data = modify(entity); // Kind of a hack to prevent dropping things we're going to undo later if (undoEntityTypes != null && undoEntityTypes.contains(entity.getType())) { data.removed(entity); entity.remove(); } return data; } @Override public void move(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasMoved(true); } } @Override public void modifyVelocity(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasVelocity(true); } } @Override public void addPotionEffects(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasPotionEffects(true); } } public void remove(Entity entity) { UUID entityId = entity.getUniqueId(); if (entities != null && entities.contains(entityId)) { entities.remove(entityId); } if (modifiedEntities != null && modifiedEntities.containsKey(entityId)) { entities.remove(entityId); } modifiedTime = System.currentTimeMillis(); } public void convert(Entity fallingBlock, Block block) { if (entities != null) { entities.remove(fallingBlock); } add(block); modifiedTime = System.currentTimeMillis(); } public void fall(Entity fallingBlock, Block block) { add(fallingBlock); add(block); modifiedTime = System.currentTimeMillis(); } public void explode(Entity explodingEntity, List<Block> blocks) { for (Block block : blocks) { add(block); } modifiedTime = System.currentTimeMillis(); } public void finalizeExplosion(Entity explodingEntity, List<Block> blocks) { if (entities != null) { entities.remove(explodingEntity); } // Prevent dropping items if this is going to auto-undo if (isScheduled()) { for (Block block : blocks) { BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder)state; holder.getInventory().clear(); state.update(); } block.setType(Material.AIR); } } modifiedTime = System.currentTimeMillis(); } public void cancelExplosion(Entity explodingEntity) { if (entities != null) { entities.remove(explodingEntity); modifiedTime = System.currentTimeMillis(); } } public boolean bypass() { return bypass; } public void setBypass(boolean bypass) { this.bypass = bypass; } public long getCreatedTime() { return this.createdTime; } public long getModifiedTime() { return this.modifiedTime; } public boolean contains(Location location, int threshold) { if (location == null || area == null || worldName == null) return false; if (!location.getWorld().getName().equals(worldName)) return false; return area.contains(location.toVector(), threshold); } public void prune() { if (blockList == null) return; List<BlockData> current = new ArrayList<BlockData>(blockList); blockList = null; blockIdMap = null; for (BlockData block : current) { if (block.isDifferent()) { super.add(block); } else { removeFromModified(block, block.getPriorState()); block.unlink(); } } modifiedTime = System.currentTimeMillis(); } @Override public String getName() { return name; } public UndoableSpell getSpell() { return spell; } @Override public Mage getOwner() { return owner; } @Override public CastContext getContext() { return context; } @Override public long getScheduledTime() { return scheduledTime; } @Override public boolean isScheduled() { return timeToLive > 0; } @Override public int compareTo(com.elmakers.mine.bukkit.api.block.UndoList o) { return (int)(scheduledTime - o.getScheduledTime()); } @Override public void setEntityUndo(boolean undoEntityEffects) { this.undoEntityEffects = undoEntityEffects; } @Override public void setEntityUndoTypes(Set<EntityType> undoTypes) { this.undoEntityTypes = undoTypes; } public void setNext(UndoList next) { this.next = next; } public void setPrevious(UndoList previous) { this.previous = previous; } public void setUndoQueue(com.elmakers.mine.bukkit.api.block.UndoQueue undoQueue) { if (undoQueue != null && undoQueue instanceof UndoQueue) { this.undoQueue = (UndoQueue)undoQueue; } } public boolean hasUndoQueue() { return this.undoQueue != null; } public void unlink() { if (undoQueue != null) { undoQueue.removed(this); undoQueue = null; } if (this.next != null) { this.next.previous = previous; } if (this.previous != null) { this.previous.next = next; } this.previous = null; this.next = null; } public UndoList getNext() { return next; } public UndoList getPrevious() { return previous; } @Override public void setApplyPhysics(boolean applyPhysics) { this.applyPhysics = applyPhysics; } public boolean getApplyPhysics() { return applyPhysics; } public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Entity entity) { com.elmakers.mine.bukkit.api.block.UndoList blockList = null; if (entity != null && entity.hasMetadata("MagicBlockList")) { List<MetadataValue> values = entity.getMetadata("MagicBlockList"); for (MetadataValue metadataValue : values) { Object value = metadataValue.value(); if (value instanceof com.elmakers.mine.bukkit.api.block.UndoList) { blockList = (com.elmakers.mine.bukkit.api.block.UndoList)value; } } } return blockList; } public static BlockData getBlockData(Location location) { return modified.get(com.elmakers.mine.bukkit.block.BlockData.getBlockId(location.getBlock())); } public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Location location) { com.elmakers.mine.bukkit.api.block.UndoList blockList = null; BlockData modifiedBlock = modified.get(com.elmakers.mine.bukkit.block.BlockData.getBlockId(location.getBlock())); if (modifiedBlock != null) { blockList = modifiedBlock.getUndoList(); } return blockList; } public static Map<Long, BlockData> getModified() { return modified; } public void setUndoBreakable(boolean breakable) { this.undoBreakable = breakable; } public void setUndoReflective(boolean reflective) { this.undoReflective = reflective; } }
package com.example.resource; import java.net.URI; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.CompletionCallback; import javax.ws.rs.container.ConnectionCallback; import javax.ws.rs.container.Suspended; import javax.ws.rs.container.TimeoutHandler; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import com.example.dao.ClienteDAO; import com.example.dao.CuentaDAO; import com.example.dao.DAOFactory; import com.example.dao.MovimientoDAO; import com.example.model.Cliente; import com.example.model.Cuenta; import com.example.model.Movimiento; @Path("clientes/{cliente_id}/cuentas/{cuenta_id}/movimientos") public class MovimientoResource { private final ClienteDAO clienteDao; private final CuentaDAO cuentaDao; private final MovimientoDAO movimientoDao; private static final Logger logger = Logger.getLogger(MovimientoResource.class.toString()); @Context protected UriInfo uriInfo; public MovimientoResource(){ movimientoDao = DAOFactory.getMovimientoDAO(); clienteDao = DAOFactory.getClienteDAO(); cuentaDao = DAOFactory.getCuentaDAO(); } @GET @Path("{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Movimiento show(@PathParam("cuenta_id") Integer cuenta_id, @PathParam("id") Integer id) { logger.info("SHOW"); Movimiento movimiento = movimientoDao.find(id); if(movimiento == null) throw new WebApplicationException(404); return movimiento; } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public List<Movimiento> index(@PathParam("cliente_id") Integer cliente_id, @PathParam("cuenta_id") Integer cuenta_id) { logger.info("SHOW-ALL"); return movimientoDao.findMovimientosCuenta(cuenta_id); } @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response create(@PathParam("cliente_id") Integer cliente_id, @PathParam("cuenta_id") Integer cuenta_id, Movimiento entity) { logger.info("CREATE"); Cliente cliente = clienteDao.find(cliente_id); Cuenta cuenta = cuentaDao.find(cuenta_id); if(cliente == null || cuenta == null) throw new WebApplicationException(404); entity.setCuenta(cuenta); Movimiento mov = (Movimiento) movimientoDao.create(entity); logger.info("Nuevo Movimiento creado: Monto: "+mov.getMonto()+" Tipo: "+mov.getTipo()+" Cuenta: "+mov.getCuenta().getId()); cuentaDao.actualizarCuenta(mov); logger.info("Saldo Actualizado: "+mov.getCuenta().getSaldo()+" Cuenta id: "+mov.getCuenta().getId()); UriBuilder ub = uriInfo.getAbsolutePathBuilder(); URI movUri = ub.path(mov.getId().toString()).build(); return Response.created(movUri).entity(mov).build(); } @POST @Path("async") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void createAsync(@Suspended final AsyncResponse asyncResponse, @PathParam("cliente_id") Integer cliente_id, @PathParam("cuenta_id") Integer cuenta_id, Movimiento entity) { logger.info("CREATE-ASYNC"); asyncResponse.setTimeout(15, TimeUnit.SECONDS); asyncResponse.setTimeoutHandler(new TimeoutHandler() { @Override public void handleTimeout(AsyncResponse asyncResponse) { asyncResponse.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE) .entity("Operation time out.").build()); } }); asyncResponse.register(new CompletionCallback() { @Override public void onComplete(Throwable throwable) { if (throwable == null) { // no throwable - the processing ended successfully // (response already written to the client) logger.info("Exito!"); } else { logger.severe("Falla!"); } } }); asyncResponse.register(new ConnectionCallback() { @Override public void onDisconnect(AsyncResponse arg0) { logger.severe("Conexion perdida!"); } }); final Cliente cliente = clienteDao.find(cliente_id); final Cuenta cuenta = cuentaDao.find(cuenta_id); if(cliente == null || cuenta == null) throw new WebApplicationException(404); entity.setCuenta(cuenta); final UriBuilder ub = uriInfo.getAbsolutePathBuilder(); final Movimiento mov = entity; new Thread(new Runnable() { @Override public void run() { asyncResponse.resume(veryExpensiveOperation(mov)); } private Response veryExpensiveOperation(Movimiento mov) { try { Thread.sleep(25000); } catch (InterruptedException e) { e.printStackTrace(); } mov = (Movimiento) movimientoDao.create(mov); cuentaDao.actualizarCuenta(mov); URI movUri = ub.path(mov.getId().toString()).build(); return Response.created(movUri).entity(mov).build(); } }).start(); } }
package org.voltdb.sysprocs; import java.io.File; import java.net.InetAddress; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.voltdb.BackendTarget; import org.voltdb.DependencyPair; import org.voltdb.ExecutionSite.SystemProcedureExecutionContext; import org.voltdb.HsqlBackend; import org.voltdb.ParameterSet; import org.voltdb.ProcInfo; import org.voltdb.SiteProcedureConnection; import org.voltdb.VoltDB; import org.voltdb.VoltSystemProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltTable.ColumnInfo; import org.voltdb.VoltType; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Connector; import org.voltdb.catalog.Deployment; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.catalog.User; import org.voltdb.dtxn.DtxnConstants; import org.voltdb.logging.VoltLogger; /** * Access key/value tables of cluster info that correspond to the REST * API members/properties */ @ProcInfo( singlePartition = false ) public class SystemInformation extends VoltSystemProcedure { private static final VoltLogger hostLog = new VoltLogger("HOST"); static final int DEP_DISTRIBUTE = (int) SysProcFragmentId.PF_systemInformationOverview | DtxnConstants.MULTIPARTITION_DEPENDENCY; static final int DEP_AGGREGATE = (int) SysProcFragmentId.PF_systemInformationOverviewAggregate; static final int DEP_systemInformationDeployment = (int) SysProcFragmentId.PF_systemInformationDeployment | DtxnConstants.MULTIPARTITION_DEPENDENCY; static final int DEP_systemInformationAggregate = (int) SysProcFragmentId.PF_systemInformationAggregate; private static final ColumnInfo clusterInfoSchema[] = new ColumnInfo[] { new ColumnInfo("PROPERTY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING) }; @Override public void init(int numberOfPartitions, SiteProcedureConnection site, Procedure catProc, BackendTarget eeType, HsqlBackend hsql, Cluster cluster) { super.init(numberOfPartitions, site, catProc, eeType, hsql, cluster); site.registerPlanFragment(SysProcFragmentId.PF_systemInformationOverview, this); site.registerPlanFragment(SysProcFragmentId.PF_systemInformationOverviewAggregate, this); site.registerPlanFragment(SysProcFragmentId.PF_systemInformationDeployment, this); site.registerPlanFragment(SysProcFragmentId.PF_systemInformationAggregate, this); } @Override public DependencyPair executePlanFragment(HashMap<Integer, List<VoltTable>> dependencies, long fragmentId, ParameterSet params, SystemProcedureExecutionContext context) { if (fragmentId == SysProcFragmentId.PF_systemInformationOverview) { VoltTable result = null; // Choose the lowest site ID on this host to do the info gathering // All other sites should just return empty results tables. int host_id = context.getExecutionSite().getCorrespondingHostId(); Integer lowest_site_id = VoltDB.instance().getCatalogContext().siteTracker. getLowestLiveExecSiteIdForHost(host_id); if (context.getExecutionSite().getSiteId() == lowest_site_id) { result = populateOverviewTable(context); } else { result = new VoltTable( new ColumnInfo(CNAME_HOST_ID, CTYPE_ID), new ColumnInfo("KEY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING)); } return new DependencyPair(DEP_DISTRIBUTE, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationOverviewAggregate) { VoltTable result = unionTables(dependencies.get(DEP_DISTRIBUTE)); return new DependencyPair(DEP_AGGREGATE, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationDeployment) { VoltTable result = null; // Choose the lowest site ID on this host to do the info gathering // All other sites should just return empty results tables. int host_id = context.getExecutionSite().getCorrespondingHostId(); Integer lowest_site_id = VoltDB.instance().getCatalogContext().siteTracker. getLowestLiveExecSiteIdForHost(host_id); if (context.getExecutionSite().getSiteId() == lowest_site_id) { result = populateDeploymentProperties(context); } else { result = new VoltTable(clusterInfoSchema); } return new DependencyPair(DEP_systemInformationDeployment, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationAggregate) { VoltTable result = null; // Check for KEY/VALUE consistency List<VoltTable> answers = dependencies.get(DEP_systemInformationDeployment); for (VoltTable answer : answers) { // if we got an empty table from a non-lowest execution site ID, // ignore it if (answer.getRowCount() == 0) { continue; } // Save the first real answer we got and compare all future // answers with it if (result == null) { result = answer; } else { if (!verifyReturnedTablesMatch(answer, result)) { StringBuilder sb = new StringBuilder(); sb.append("Inconsistent results returned for @SystemInformation: \n"); sb.append("Result sb.append(result.toString()); sb.append("\n"); sb.append("Result sb.append(answer.toString()); sb.append("\n"); hostLog.error(sb.toString()); throw new VoltAbortException(sb.toString()); } } } return new DependencyPair(DEP_systemInformationAggregate, result); } assert(false); return null; } boolean verifyReturnedTablesMatch(VoltTable first, VoltTable second) { boolean retval = true; HashMap<String, String> first_map = new HashMap<String, String>(); HashMap<String, String> second_map = new HashMap<String, String>(); while (first.advanceRow()) { first_map.put(first.getString(0), first.getString(1)); } while (second.advanceRow()) { second_map.put(second.getString(0), second.getString(1)); } if (first_map.size() != second_map.size()) { retval = false; } else { for (Entry<String, String> first_entry : first_map.entrySet()) { String second_value = second_map.get(first_entry.getKey()); if (second_value == null || !second_value.equals(first_entry.getValue())) { // Ignore deltas due to LocalCluster's use of // VoltFileRoot if ((((String)(first_entry.getKey())).contains("path") || ((String)(first_entry.getKey())).contains("root")) && (System.getProperty("VoltFilePrefix") != null)) { continue; } else { retval = false; break; } } } } return retval; } /** * Returns the cluster info requested by the provided selector * @param ctx Internal. Not exposed to the end-user. * @param selector Selector requested * @return The property/value table for the provided selector * @throws VoltAbortException */ public VoltTable[] run(SystemProcedureExecutionContext ctx, String selector) throws VoltAbortException { VoltTable[] results; // This selector provides the old @SystemInformation behavior if (selector.toUpperCase().equals("OVERVIEW")) { results = getOverviewInfo(); } else if (selector.toUpperCase().equals("DEPLOYMENT")) { results = getDeploymentInfo(); } else { throw new VoltAbortException(String.format("Invalid @SystemInformation selector %s.", selector)); } return results; } /** * Retrieve basic management information about the cluster. * Use this procedure to read the ipaddress, hostname, buildstring * and version of each node of the cluster. * * @return A table with three columns: * HOST_ID(INTEGER), KEY(STRING), VALUE(STRING). */ private VoltTable[] getOverviewInfo() { SynthesizedPlanFragment spf[] = new SynthesizedPlanFragment[2]; spf[0] = new SynthesizedPlanFragment(); spf[0].fragmentId = SysProcFragmentId.PF_systemInformationOverview; spf[0].outputDepId = DEP_DISTRIBUTE; spf[0].inputDepIds = new int[] {}; spf[0].multipartition = true; spf[0].parameters = new ParameterSet(); spf[1] = new SynthesizedPlanFragment(); spf[1] = new SynthesizedPlanFragment(); spf[1].fragmentId = SysProcFragmentId.PF_systemInformationOverviewAggregate; spf[1].outputDepId = DEP_AGGREGATE; spf[1].inputDepIds = new int[] { DEP_DISTRIBUTE }; spf[1].multipartition = false; spf[1].parameters = new ParameterSet(); return executeSysProcPlanFragments(spf, DEP_AGGREGATE); } private VoltTable[] getDeploymentInfo() { VoltTable[] results; SynthesizedPlanFragment pfs[] = new SynthesizedPlanFragment[2]; // create a work fragment to gather deployment data from each of the sites. pfs[1] = new SynthesizedPlanFragment(); pfs[1].fragmentId = SysProcFragmentId.PF_systemInformationDeployment; pfs[1].outputDepId = DEP_systemInformationDeployment; pfs[1].inputDepIds = new int[]{}; pfs[1].multipartition = true; pfs[1].parameters = new ParameterSet(); //pfs[1].parameters.setParameters((byte)interval, now); // create a work fragment to aggregate the results. pfs[0] = new SynthesizedPlanFragment(); pfs[0].fragmentId = SysProcFragmentId.PF_systemInformationAggregate; pfs[0].outputDepId = DEP_systemInformationAggregate; pfs[0].inputDepIds = new int[]{DEP_systemInformationDeployment}; pfs[0].multipartition = false; pfs[0].parameters = new ParameterSet(); // distribute and execute these fragments providing pfs and id of the // aggregator's output dependency table. results = executeSysProcPlanFragments(pfs, DEP_systemInformationAggregate); return results; } /** * Accumulate per-host information and return as a table. * This function does the real work. Everything else is * boilerplate sysproc stuff. */ private VoltTable populateOverviewTable(SystemProcedureExecutionContext context) { VoltTable vt = new VoltTable( new ColumnInfo(VoltSystemProcedure.CNAME_HOST_ID, VoltSystemProcedure.CTYPE_ID), new ColumnInfo("KEY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING)); // host name and IP address. InetAddress addr = org.voltdb.client.ConnectionUtil.getLocalAddress(); vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "IPADDRESS", addr.getHostAddress()); vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "HOSTNAME", addr.getHostName()); // build string vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "BUILDSTRING", VoltDB.instance().getBuildString()); // version vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "VERSION", VoltDB.instance().getVersionString()); // catalog path String path = VoltDB.instance().getConfig().m_pathToCatalog; if (!path.startsWith("http")) path = (new File(path)).getAbsolutePath(); vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "CATALOG", path); // deployment path path = VoltDB.instance().getConfig().m_pathToDeployment; if (!path.startsWith("http")) path = (new File(path)).getAbsolutePath(); vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "DEPLOYMENT", path); String cluster_state = null; if (VoltDB.instance().inAdminMode()) { cluster_state = "Paused"; } else { cluster_state = "Running"; } vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "CLUSTERSTATE", cluster_state); vt.addRow(VoltDB.instance().getHostMessenger().getHostId(), "LASTCATALOGUPDATETXNID", Long.toString(VoltDB.instance().getCatalogContext().m_transactionId)); return vt; } private VoltTable populateDeploymentProperties(SystemProcedureExecutionContext context) { VoltTable results = new VoltTable(clusterInfoSchema); // it would be awesome if these property names could come // from the RestApiDescription.xml (or the equivalent thereof) someday --izzy results.addRow("voltdbroot", context.getCluster().getVoltroot()); Deployment deploy = context.getCluster().getDeployment().get("deployment"); results.addRow("hostcount", Integer.toString(deploy.getHostcount())); results.addRow("kfactor", Integer.toString(deploy.getKfactor())); results.addRow("sitesperhost", Integer.toString(deploy.getSitesperhost())); String http_enabled = "false"; int http_port = context.getCluster().getHttpdportno(); if (http_port != -1) { http_enabled = "true"; results.addRow("httpport", Integer.toString(http_port)); } results.addRow("httpenabled", http_enabled); String json_enabled = "false"; if (context.getCluster().getJsonapi()) { json_enabled = "true"; } results.addRow("jsonenabled", json_enabled); SnapshotSchedule snaps = context.getDatabase().getSnapshotschedule().get("default"); String snap_enabled = "false"; if (snaps != null) { snap_enabled = "true"; String snap_freq = Integer.toString(snaps.getFrequencyvalue()) + snaps.getFrequencyunit(); results.addRow("snapshotpath", snaps.getPath()); results.addRow("snapshotprefix", snaps.getPrefix()); results.addRow("snapshotfrequency", snap_freq); results.addRow("snapshotretain", Integer.toString(snaps.getRetain())); } results.addRow("snapshotenabled", snap_enabled); Connector export_conn = context.getDatabase().getConnectors().get("0"); String export_enabled = "false"; if (export_conn != null && export_conn.getEnabled()) { export_enabled = "true"; results.addRow("exportoverflowpath", context.getCluster().getExportoverflow()); } results.addRow("export", export_enabled); String partition_detect_enabled = "false"; if (context.getCluster().getNetworkpartition()) { partition_detect_enabled = "true"; String partition_detect_snapshot_path = context.getCluster().getFaultsnapshots().get("CLUSTER_PARTITION").getPath(); String partition_detect_snapshot_prefix = context.getCluster().getFaultsnapshots().get("CLUSTER_PARTITION").getPrefix(); results.addRow("partitiondetectionsnapshotpath", partition_detect_snapshot_path); results.addRow("partitiondetectionsnapshotprefix", partition_detect_snapshot_prefix); } results.addRow("partitiondetection", partition_detect_enabled); results.addRow("heartbeattimeout", Integer.toString(context.getCluster().getHeartbeattimeout())); results.addRow("adminport", Integer.toString(context.getCluster().getAdminport())); String adminstartup = "false"; if (context.getCluster().getAdminstartup()) { adminstartup = "true"; } results.addRow("adminstartup", adminstartup); String users = ""; for (User user : context.getDatabase().getUsers()) { users += addEscapes(user.getTypeName()); if (user.getGroups() != null && user.getGroups().size() > 0) { users += ":"; for (GroupRef gref : user.getGroups()) { users += addEscapes(gref.getGroup().getTypeName()); users += ","; } users = users.substring(0, users.length() - 1); } users += ";"; } results.addRow("users", users); return results; } private String addEscapes(String name) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == ';' || name.charAt(i) == ':' || name.charAt(i) == '\\') { sb.append('\\'); } sb.append(name.charAt(i)); } return sb.toString(); } }
package com.facebook.litho; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.v4.util.Pools; import android.support.v4.util.SparseArrayCompat; import android.util.SparseArray; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConfig; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaExperimentalFeature; import com.facebook.yoga.YogaNode; import com.facebook.yoga.YogaNodeAPI; import com.facebook.yoga.CSSNodeDEPRECATED; import com.facebook.yoga.Spacing; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; /** * Pools of recycled resources. * * FUTURE: Consider customizing the pool implementation such that we can match buffer sizes. Without * this we will tend to expand all buffers to the largest size needed. */ public class ComponentsPools { private static YogaConfig sYogaConfig; private static final int SCRAP_ARRAY_INITIAL_SIZE = 4; private ComponentsPools() { } // FUTURE: tune pool max sizes private static final Object mountContentLock = new Object(); private static final Pools.SynchronizedPool<LayoutState> sLayoutStatePool = new Pools.SynchronizedPool<>(64); private static final Pools.SynchronizedPool<InternalNode> sInternalNodePool = new Pools.SynchronizedPool<>(256); private static final Pools.SynchronizedPool<NodeInfo> sNodeInfoPool = new Pools.SynchronizedPool<>(256); private static final Pools.SynchronizedPool<ViewNodeInfo> sViewNodeInfoPool = new Pools.SynchronizedPool<>(64); private static final Pools.SynchronizedPool<YogaNodeAPI> sYogaNodePool = new Pools.SynchronizedPool<>(256); private static final Pools.SynchronizedPool<MountItem> sMountItemPool = new Pools.SynchronizedPool<>(256); private static final Map<Context, SparseArray<PoolWithCount>> sMountContentPoolsByContext = new ConcurrentHashMap<>(4); private static final Pools.SynchronizedPool<LayoutOutput> sLayoutOutputPool = new Pools.SynchronizedPool<>(256); private static final Pools.SynchronizedPool<VisibilityOutput> sVisibilityOutputPool = new Pools.SynchronizedPool<>(64); // These are lazily initialized as they are only needed when we're in a test environment. private static Pools.SynchronizedPool<TestOutput> sTestOutputPool = null; private static Pools.SynchronizedPool<TestItem> sTestItemPool = null; private static final Pools.SynchronizedPool<VisibilityItem> sVisibilityItemPool = new Pools.SynchronizedPool<>(64); private static final Pools.SynchronizedPool<Output<?>> sOutputPool = new Pools.SynchronizedPool<>(20); private static final Pools.SynchronizedPool<DiffNode> sDiffNodePool = new Pools.SynchronizedPool<>(256); private static final Pools.SynchronizedPool<Diff<?>> sDiffPool = new Pools.SynchronizedPool<>(20); private static final Pools.SynchronizedPool<ComponentTree.Builder> sComponentTreeBuilderPool = new Pools.SynchronizedPool<>(2); private static final Pools.SynchronizedPool<StateHandler> sStateHandlerPool = new Pools.SynchronizedPool<>(10); private static final Pools.SimplePool<SparseArrayCompat<MountItem>> sMountItemScrapArrayPool = new Pools.SimplePool<>(8); private static final Pools.SimplePool<SparseArrayCompat<Touchable>> sTouchableScrapArrayPool = new Pools.SimplePool<>(4); private static final Pools.SynchronizedPool<RectF> sRectFPool = new Pools.SynchronizedPool<>(4); private static final Pools.SynchronizedPool<Rect> sRectPool = new Pools.SynchronizedPool<>(30); private static final Pools.SynchronizedPool<Spacing> sSpacingPool = new Pools.SynchronizedPool<>(30); private static final Pools.SynchronizedPool<TransitionContext> sTransitionContextPool = new Pools.SynchronizedPool<>(2); private static final Pools.SimplePool<TransitionManager> sTransitionManagerPool = new Pools.SimplePool<>(2); static final Pools.Pool<DisplayListDrawable> sDisplayListDrawablePool = new Pools.SimplePool<>(10); private static final Pools.SynchronizedPool<TreeProps> sTreePropsMapPool = new Pools.SynchronizedPool<>(10); // Lazily initialized when acquired first time, as this is not a common use case. private static Pools.Pool<BorderColorDrawable> sBorderColorDrawablePool = null; private static PoolsActivityCallback sActivityCallbacks; /** * To support Gingerbread (where the registerActivityLifecycleCallbacks API * doesn't exist), we allow apps to explicitly invoke activity callbacks. If * this is enabled we'll throw if we are passed a context for which we have * no record. */ static boolean sIsManualCallbacks; /** * Local cache of ComponentsConfiguration.shouldUseCSSNodeJNI which ensures * the value is only read once. * Once any InternalNode uses any of CSSNodeDEPRECATED or * YogaNode all future InternalNodes must do the same as to not mix and match. */ private static Boolean sShouldUseCSSNodeJNI = null; static LayoutState acquireLayoutState(ComponentContext context) { LayoutState state = sLayoutStatePool.acquire(); if (state == null) { state = new LayoutState(); } state.init(context); return state; } static synchronized YogaNodeAPI acquireYogaNode() { YogaNodeAPI node = sYogaNodePool.acquire(); if (node == null) { if (sShouldUseCSSNodeJNI == null) { sShouldUseCSSNodeJNI = ComponentsConfiguration.shouldUseCSSNodeJNI; } if (sShouldUseCSSNodeJNI) { if (sYogaConfig == null) { sYogaConfig = new YogaConfig(); sYogaConfig.setUseWebDefaults(true); sYogaConfig.setExperimentalFeatureEnabled(YogaExperimentalFeature.ROUNDING, true); } node = new YogaNode(sYogaConfig); } else { node = new CSSNodeDEPRECATED(); } } return node; } static synchronized InternalNode acquireInternalNode( ComponentContext componentContext, Resources resources) { InternalNode node = sInternalNodePool.acquire(); if (node == null) { node = new InternalNode(); } node.init(acquireYogaNode(), componentContext, resources); return node; } static synchronized NodeInfo acquireNodeInfo() { NodeInfo nodeInfo = sNodeInfoPool.acquire(); if (nodeInfo == null) { nodeInfo = new NodeInfo(); } return nodeInfo; } static synchronized ViewNodeInfo acquireViewNodeInfo() { ViewNodeInfo viewNodeInfo = sViewNodeInfoPool.acquire(); if (viewNodeInfo == null) { viewNodeInfo = new ViewNodeInfo(); } return viewNodeInfo; } static MountItem acquireRootHostMountItem( Component<?> component, ComponentHost host, Object content) { MountItem item = sMountItemPool.acquire(); if (item == null) { item = new MountItem(); } final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setLayoutDirection(YogaDirection.INHERIT); item.init( component, host, content, null, viewNodeInfo, null, 0, IMPORTANT_FOR_ACCESSIBILITY_AUTO); return item; } static MountItem acquireMountItem( Component<?> component, ComponentHost host, Object content, LayoutOutput layoutOutput) { MountItem item = sMountItemPool.acquire(); if (item == null) { item = new MountItem(); } item.init(component, host, content, layoutOutput, null); return item; } static Object acquireMountContent(Context context, int componentId) { if (context instanceof ComponentContext) { context = ((ComponentContext) context).getBaseContext(); if (context instanceof ComponentContext) { throw new IllegalStateException("Double wrapped ComponentContext."); }
package com.justjournal.ctl.api; import com.justjournal.WebLogin; import com.justjournal.db.*; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * @author Lucas Holt */ @Controller @RequestMapping("/api/entry") final public class EntryController { private static final Logger log = Logger.getLogger(EntryController.class); /** * Get an individual entry * * @param id entry id * @return entry */ @RequestMapping("/api/entry/{id}") @ResponseBody public EntryTo getById(@PathVariable Integer id) { return EntryDAO.viewSinglePublic(id); } @RequestMapping(method = RequestMethod.GET, produces = "application/json") public @ResponseBody Collection<EntryTo> getEntries(@RequestParam String username) { return EntryDAO.viewAll(username, false); } /** * Creates a new entry resource * * @param entry * @param session * @param response * @return */ @RequestMapping(method = RequestMethod.POST, produces = "application/json") public @ResponseBody Map<String, String> post(@RequestBody EntryTo entry, HttpSession session, HttpServletResponse response) { if (!WebLogin.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return java.util.Collections.singletonMap("error", "The login timed out or is invalid."); } // TODO: validate boolean result = EntryDAO.add(entry); if (!result) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Could not add the entry."); } return java.util.Collections.singletonMap("id", Integer.toString(entry.getId())); } /** * PUT generally allows for add or edit in REST. * * @param entry * @param session * @param response * @return */ @RequestMapping(method = RequestMethod.PUT, produces = "application/json") public @ResponseBody Map<String, String> put(@RequestBody EntryTo entry, HttpSession session, HttpServletResponse response) { if (!WebLogin.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return java.util.Collections.singletonMap("error", "The login timed out or is invalid."); } // TODO: validate boolean result; EntryTo entryTo = EntryDAO.viewSingle(entry.getId(), WebLogin.currentLoginId(session)); if (entryTo != null && entryTo.getId() > 0) result = EntryDAO.update(entry); else result = EntryDAO.add(entry); if (!result) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Could not add/edit entry."); } return java.util.Collections.singletonMap("id", Integer.toString(entry.getId())); } @RequestMapping(method = RequestMethod.DELETE) public @ResponseBody Map<String, String> delete(@RequestBody int entryId, HttpSession session, HttpServletResponse response) throws Exception { if (!WebLogin.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return java.util.Collections.singletonMap("error", "The login timed out or is invalid."); } if (entryId < 1) return Collections.singletonMap("error", "The entry id was invalid."); try { boolean result2; boolean result = EntryDAO.delete(entryId, WebLogin.currentLoginId(session)); if (!result) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Could not delete entry."); } result2 = CommentDao.deleteByEntry(entryId); if (!result2) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Could not delete comments associated with entry."); } return java.util.Collections.singletonMap("id", Integer.toString(entryId)); } catch (Exception e) { log.error(e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Could not delete the comment."); } } }
package gov.nih.nci.calab.service.util; public class CananoConstants { public static final String PARTICLE_PROPERTY = "particle.properties"; public static final String PHYSICAL_CHARACTERIZATION = "Physical"; public static final String COMPOSITION_CHARACTERIZATION = "Composition"; public static final String INVITRO_CHARACTERIZATION = "In Vitro"; public static final String INVIVO_CHARACTERIZATION = "In Vivo"; public static final String TOXICITY_CHARACTERIZATION = "Toxicity"; public static final String CYTOXICITY_CHARACTERIZATION = "Cytoxicity"; public static final String APOPTOSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "apoptosis"; public static final String NECROSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "necrosis"; public static final String BLOOD_CONTACT_IMMUNOTOXICITY_CHARACTERIZATION = "Blood Contact"; public static final String IMMUNE_CELL_FUNCTION_IMMUNOTOXICITY_CHARACTERIZATION = "Immune Cell Function"; public static final String METABOLIC_STABILITY_TOXICITY_CHARACTERIZATION = "Metabolic Stability"; public static final String PHYSICAL_SIZE = "Size"; public static final String PHYSICAL_SHAPE = "Shape"; public static final String PHYSICAL_MOLECULAR_WEIGHT = "Molecular Weight"; public static final String PHYSICAL_SOLUBILITY = "Solubility"; public static final String PHYSICAL_SURFACE = "Surface"; public static final String PHYSICAL_STABILITY = "Stability"; public static final String PHYSICAL_PURITY = "Purity"; public static final String PHYSICAL_FUNCTIONAL = "Functional"; public static final String PHYSICAL_MORPHOLOGY = "Morphology"; public static final String PHYSICAL_COMPOSITION = "Composition"; public static final String TOXICITY_OXIDATIVE_STRESS = "Oxidative Stress"; public static final String TOXICITY_ENZYME_FUNCTION = "Enzyme Function"; public static final String CYTOTOXICITY_CELL_VIABILITY = "Cell Viability"; public static final String CYTOTOXICITY_CASPASE3_ACTIVIATION = "Caspase 3 Activation"; public static final String BLOODCONTACTTOX_PLATE_AGGREGATION = "Plate Aggregation"; public static final String BLOODCONTACTTOX_HEMOLYSIS = "Hemolysis"; public static final String BLOODCONTACTTOX_COAGULATION = "Coagulation"; public static final String BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING = "Plasma Protein Binding"; public static final String IMMUNOCELLFUNCTOX_PHAGOCYTOSIS = "Phagocytosis"; public static final String IMMUNOCELLFUNCTOX_OXIDATIVE_BURST = "Oxidative Burst"; public static final String IMMUNOCELLFUNCTOX_CHEMOTAXIS = "Chemotaxis"; public static final String IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION = "Cytokine Induction"; public static final String IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION = "Complement Activation"; public static final String IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION = "Leukocyte Proliferation"; public static final String IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY = "Cytotoxic Activity of NK Cells"; public static final String METABOLIC_STABILITY_CYP450 = "CYP450"; public static final String METABOLIC_STABILITY_ROS = "ROS"; public static final String METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION = "Glucuronidation Sulphation"; public static final String IMMUNOCELLFUNCTOX_CFU_GM = "CFU_GM"; public static final String DENDRIMER_TYPE = "Dendrimer"; public static final String POLYMER_TYPE = "Polymer"; public static final String LIPOSOME_TYPE = "Liposome"; public static final String CARBON_NANOTUBE_TYPE = "Carbon Nanotube"; public static final String FULLERENE_TYPE = "Fullerene"; public static final String QUANTUM_DOT_TYPE = "Quantum Dot"; public static final String METAL_PARTICLE_TYPE = "Metal Particle"; public static final String EMULSION_TYPE = "Emulsion"; public static final String COMPLEX_PARTICLE_TYPE = "Complex Particle"; public static final String CORE = "core"; public static final String SHELL = "shell"; public static final String COATING = "coating"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String[] CHARACTERIZATION_SOURCES = new String[] { "NCL", "Vendor" }; public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] { "Single (SWNT)", "Double (DWMT)", "Multiple (MWNT)" }; public static final String[] REPORT_TYPES = new String[] { "NCL Report", "Other Associated File" }; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String[]DEFAULT_DENDRIMER_BRANCHES = new String[] { "1-2", "1-3"}; public static final String[]DEFAULT_DENDRIMER_GENERATIONS = new String[] { "0","0.5","1.0","1.5","2.0","2.5","3.0","3.5","4.0","4.5","5.0","5.5","6.0","6.5","7.0","7.5","8.0","8.5","9.0","9.5","10.0"}; public static final String OTHER = "Other"; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final String DNA = "DNA"; public static final String PEPTIDE = "Peptide"; public static final String SMALL_MOLECULE = "Small Molecule"; public static final String PROBE = "Probe"; public static final String ANTIBODY = "Antibody"; public static final String IMAGE_CONTRAST_AGENT ="Image Contrast Agent"; public static final String ATTACHMENT = "Attachment"; public static final String ENCAPSULATION = "Encapsulation"; public static final String RECEPTOR = "Receptor"; public static final String ANTIGEN = "Antigen"; public static final String NCL_REPORT = "NCL Report"; public static final int MAX_VIEW_TITLE_LENGTH=25; public static final String[] DEFAULT_CELLLINES = new String[] {"LLC-PK1", "Hep-G2"}; public static final String[] DEFAULT_SHAPE_TYPES = new String[] { "Cubic", "Hexagonal", "Irregular", "Needle", "Oblate", "Rod", "Spherical", "Tetrahedron", "Tetrapod", "Triangle", "Eliptical", "Composite", "Cylindrical", "Vesicular", "Elliposid" }; public static final String[] DEFAULT_MORPHOLOGY_TYPES = new String[] {"Power", "Liquid", "Solid", "Crystalline", "Copolymer", "Fibril", "Colloid", "Oil" }; public static final String[] DEFAULT_SURFACE_GROUP_NAMES = new String[] {"Amine", "Carboxyl", "Hydroxyl" }; }
package com.k13n.soliton; import java.util.Random; public class RobustSolitonGenerator implements SolitonGenerator { private Random random; private int k, M; private double c, delta, R, beta; public RobustSolitonGenerator(int k, double c, double delta, long seed) { this.k = k; this.c = c; this.delta = delta; random = new Random(seed); R = computeR(); M = computeM(); beta = computeBeta(); } public RobustSolitonGenerator(int k, double c, double delta) { this(k, c, delta, new Random().nextLong()); } private double computeR() { return c * Math.log(k / delta) * Math.sqrt(k); } private int computeM() { return (int) Math.floor(k / R); } public RobustSolitonGenerator(int k, int M, double delta, long seed) { this.k = k; this.M = M; this.delta = delta; random = new Random(seed); R = k / ((double) M); beta = computeBeta(); } public RobustSolitonGenerator(int k, int M, double delta) { this(k, M, delta, new Random().nextLong()); } private double computeBeta() { double sum = 0; for (int i = 1; i <= k; i++) sum += idealSoliton(i) + unnormalizedRobustSoliton(i); return sum; } @Override public int next() { double u = random.nextDouble(); return inverseTransformSampling(u); } private int inverseTransformSampling(double u) { double sum = 0; int index = 1; while (sum <= u) sum += normalizedRobustSoliton(index++); return index - 1; } private double normalizedRobustSoliton(int i) { return (idealSoliton(i) + unnormalizedRobustSoliton(i)) / beta; } private double unnormalizedRobustSoliton(int i) { if (1 <= i && i <= M-1) return 1.0 / (i*M); else if (i == M) return Math.log(R / delta) / M; else return 0; } private double idealSoliton(int i) { if (i == 1) return 1.0 / k; else return 1.0 / (i * (i-1)); } }
/** * @author dgeorge * * $Id: UserManagerImpl.java,v 1.11 2005-11-08 22:32:44 georgeda Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.10 2005/11/07 13:58:29 georgeda * Dynamically update roles * * Revision 1.9 2005/10/24 13:28:06 georgeda * Cleanup changes * * Revision 1.8 2005/10/17 13:10:16 georgeda * Get contact information * * Revision 1.7 2005/10/13 17:00:06 georgeda * Cleanup * * Revision 1.6 2005/09/30 19:49:58 georgeda * Make sure user is in db * * Revision 1.5 2005/09/22 18:55:49 georgeda * Get coordinator from user in properties file * * Revision 1.4 2005/09/22 15:15:17 georgeda * More changes * * Revision 1.3 2005/09/16 15:52:57 georgeda * Changes due to manager re-write * * */ package gov.nih.nci.camod.service.impl; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.*; import gov.nih.nci.camod.service.UserManager; import gov.nih.nci.camod.util.LDAPUtil; import gov.nih.nci.common.persistence.Search; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.exceptions.CSException; import java.util.*; import javax.servlet.http.HttpServletRequest; /** * Implementation of class used to wrap the CSM implementation */ public class UserManagerImpl extends BaseManager implements UserManager { private AuthenticationManager theAuthenticationMgr = null; /** * Constructor gets reference to authorization manager */ UserManagerImpl() { log.trace("Entering UserManagerImpl"); try { theAuthenticationMgr = SecurityServiceProvider.getAuthenticationManager(Constants.UPT_CONTEXT_NAME); } catch (CSException ex) { log.error("Error getting authentication managers", ex); } catch (Throwable e) { log.error("Error getting authentication managers", e); } log.trace("Exiting UserManagerImpl"); } /** * Get a list of roles for a user * * @param inUsername * the login name of the user * * @return the list of roles associated with the user * @throws Exception */ public List getRolesForUser(String inUsername) throws Exception { log.trace("Entering getRolesForUser"); List theRoles = new ArrayList(); try { Person thePerson = new Person(); thePerson.setUsername(inUsername); List thePeople = Search.query(thePerson); if (thePeople.size() > 0) { thePerson = (Person) thePeople.get(0); List theRoleList = thePerson.getRoleCollection(); Iterator theIterator = theRoleList.iterator(); while (theIterator.hasNext()) { Role theRole = (Role) theIterator.next(); theRoles.add(theRole.getName()); } } else { throw new IllegalArgumentException("User: " + inUsername + " not in caMOD database"); } } catch (Exception e) { log.error("Unable to get roles for user (" + inUsername + ": ", e); throw e; } log.info("User: " + inUsername + " and roles: " + theRoles); log.trace("Exiting getRolesForUser"); return theRoles; } /** * Get a list of users for a particular role * * @param inRoleName * is the name of the role * * @return the list of users associated with the role * @throws Exception */ public List getUsersForRole(String inRoleName) throws Exception { log.trace("Entering getUsersForRole"); List theUsersForRole = new ArrayList(); Role theRole = new Role(); theRole.setName(inRoleName); try { List theRoles = Search.query(theRole); if (theRoles.size() > 0) { theRole = (Role) theRoles.get(0); // Get the users for the role List theUsers = theRole.getPartyCollection(); Iterator theIterator = theUsers.iterator(); // Go through the list of returned Party objects while (theIterator.hasNext()) { Object theObject = theIterator.next(); // Only add when it's actually a person if (theObject instanceof Person) { Person thePerson = (Person) theObject; theUsersForRole.add(thePerson.getUsername()); } } } else { log.warn("Role not found in database: " + inRoleName); } } catch (Exception e) { log.error("Unable to get roles for user: ", e); throw e; } log.info("Role: " + inRoleName + " and users: " + theUsersForRole); log.trace("Exiting getUsersForRole"); return theUsersForRole; } /** * Get an e-mail address for a user * * @param inUsername * is the login name of the user * * @return the list of users associated with the role */ public String getEmailForUser(String inUsername) { log.trace("Entering getEmailForUser"); log.debug("Username: " + inUsername); String theEmail = ""; try { theEmail = LDAPUtil.getEmailAddressForUser(inUsername); } catch (Exception e) { log.warn("Could not fetch user from LDAP", e); } log.trace("Exiting getEmailForUser"); return theEmail; } /** * Update the roles for the current user */ public void updateCurrentUserRoles(HttpServletRequest inRequest) { String theCurrentUser = (String) inRequest.getSession().getAttribute(Constants.CURRENTUSER); try { List theRoles = getRolesForUser(theCurrentUser); inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES, theRoles); } catch (Exception e) { log.info("Unable to update user roles for " + theCurrentUser, e); } } /** * Get an e-mail address for a user * * @param inUsername * is the login name of the user * * @return the list of users associated with the role */ public ContactInfo getContactInformationForUser(String inUsername) { log.trace("Entering getContactInformationForUser"); log.debug("Username: " + inUsername); ContactInfo theContactInfo = new ContactInfo(); try { theContactInfo.setInstitute(""); theContactInfo.setEmail(LDAPUtil.getEmailAddressForUser(inUsername)); theContactInfo.setPhone(""); } catch (Exception e) { log.warn("Could not fetch user from LDAP", e); } log.trace("Exiting getEmailForUser"); return theContactInfo; } /** * Get an e-mail address for the coordinator * * @return the list of users associated with the role */ public String getEmailForCoordinator() { log.trace("Entering getEmailForCoordinator"); String theEmail = ""; try { // Get from default bundle ResourceBundle theBundle = ResourceBundle.getBundle(Constants.CAMOD_BUNDLE); String theCoordinator = theBundle.getString(Constants.BundleKeys.COORDINATOR_USERNAME_KEY); theEmail = getEmailForUser(theCoordinator); } catch (Exception e) { log.warn("Unable to get coordinator email: ", e); } log.trace("Exiting getEmailForCoordinator"); return theEmail; } /** * Log in a user and get roles. * * @param inUsername * is the login name of the user * @param inPassword * password * @param inRequest * Used to store the roles * * @return the list of users associated with the role */ public boolean login(String inUsername, String inPassword, HttpServletRequest inRequest) { boolean loginOk = false; try { loginOk = theAuthenticationMgr.login(inUsername, inPassword); // Does the user exist? Must also be in our database to login List theRoles = getRolesForUser(inUsername); inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES, theRoles); } catch (Exception e) { log.error("Error logging in user: ", e); loginOk = false; } return loginOk; } }
package com.laytonsmith.core.functions; import com.laytonsmith.annotations.api; import com.laytonsmith.core.*; import com.laytonsmith.core.constructs.*; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.util.List; /** * * @author layton */ public class Compiler { public static String docs(){ return "Compiler internal functions should be declared here. If you're reading this from anywhere" + " but the source code, there's a bug, because these functions shouldn't be public or used" + " in a script."; } @api public static class p extends AbstractFunction { public String getName() { return "p"; } public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } public String docs() { return "mixed {c...} Used internally by the compiler. You shouldn't use it."; } public Exceptions.ExceptionType[] thrown() { return null; } public boolean isRestricted() { return false; } public CHVersion since() { return CHVersion.V3_1_2; } public Boolean runAsync() { return null; } @Override public boolean useSpecialExec() { return true; } @Override public Construct execs(Target t, Env env, Script parent, GenericTreeNode<Construct>... nodes) { if(nodes.length == 1){ return parent.eval(nodes[0], env); } else { return new __autoconcat__().execs(t, env, parent, nodes); } } public Construct exec(Target t, Env env, Construct... args) throws ConfigRuntimeException { return new CVoid(t); } @Override public boolean appearInDocumentation() { return false; } } @api public static class centry extends AbstractFunction{ public String getName() { return "centry"; } public Integer[] numArgs() { return new Integer[]{2}; } public String docs() { return "CEntry {label, content} Dynamically creates a CEntry. This is used internally by the " + "compiler."; } public Exceptions.ExceptionType[] thrown() { return null; } public boolean isRestricted() { return false; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env environment, Construct... args) throws ConfigRuntimeException { return new CEntry(args[0], args[1], t); } public CHVersion since() { return CHVersion.V3_3_1; } @Override public boolean appearInDocumentation() { return false; } @Override public boolean canOptimize() { return true; } @Override public Construct optimize(Target t, Construct... args) throws ConfigCompileException { return exec(t, null, args); } } @api public static class __autoconcat__ extends AbstractFunction { public String getName() { return "__autoconcat__"; } public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { throw new Error("Should not have gotten here"); } public String docs() { return "string {var1, [var2...]} This function should only be used by the compiler, behavior" + " may be undefined if it is used in code."; } public Exceptions.ExceptionType[] thrown() { return new Exceptions.ExceptionType[]{}; } public boolean isRestricted() { return false; } public CHVersion since() { return CHVersion.V0_0_0; } public Boolean runAsync() { return null; } @Override public boolean canOptimizeDynamic() { return true; } @Override public GenericTreeNode<Construct> optimizeDynamic(Target t, List<GenericTreeNode<Construct>> list) throws ConfigCompileException { return optimizeSpecial(t, list, true); } /** * __autoconcat__ has special optimization techniques needed, since it's * really a part of the compiler itself, and not so much a function. It * being a function is merely a convenience, so we can defer processing * until after parsing. While it is tightly coupled with the compiler, * this is ok, since it's really a compiler mechanism more than a * function. * * @param t * @param list * @return */ public GenericTreeNode<Construct> optimizeSpecial(Target t, List<GenericTreeNode<Construct>> list, boolean returnSConcat) throws ConfigCompileException { //If any of our nodes are CSymbols, we have different behavior boolean inSymbolMode = false; //catching this can save Xn //postfix for (int i = 0; i < list.size(); i++) { GenericTreeNode<Construct> node = list.get(i); if (node.data instanceof CSymbol) { inSymbolMode = true; } if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isPostfix()) { if (i - 1 >= 0 && list.get(i - 1).data instanceof IVariable) { CSymbol sy = (CSymbol) node.data; GenericTreeNode<Construct> conversion; if (sy.val().equals("++")) { conversion = new GenericTreeNode<Construct>(new CFunction("postinc", t)); } else { conversion = new GenericTreeNode<Construct>(new CFunction("postdec", t)); } conversion.addChild(list.get(i - 1)); list.set(i - 1, conversion); list.remove(i); i } } } if (inSymbolMode) { try { //look for unary operators for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> node = list.get(i); if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isUnary()) { GenericTreeNode<Construct> conversion; if (node.data.val().equals("-") || node.data.val().equals("+")) { //These are special, because if the values to the left isn't a symbol, //it's not unary if ((i == 0 || list.get(i - 1).data instanceof CSymbol) && !(list.get(i + 1).data instanceof CSymbol)) { if (node.data.val().equals("-")) { //We have to negate it conversion = new GenericTreeNode<Construct>(new CFunction("neg", t)); } else { conversion = new GenericTreeNode<Construct>(new CFunction("p", t)); } } else { continue; } } else { conversion = new GenericTreeNode<Construct>(new CFunction(( (CSymbol) node.data ).convert(), t)); } conversion.addChild(list.get(i + 1)); list.set(i, conversion); list.remove(i + 1); i } } for(int i = 0; i < list.size() - 1; i++){ GenericTreeNode<Construct> next = list.get(i + 1); if(next.data instanceof CSymbol){ if(((CSymbol)next.data).isExponential()){ GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(((CSymbol)next.data).convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } } //Multiplicative for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> next = list.get(i + 1); if (next.data instanceof CSymbol) { if (( (CSymbol) next.data ).isMultaplicative()) { GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(( (CSymbol) next.data ).convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } } //Additive for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> next = list.get(i + 1); if (next.data instanceof CSymbol && ( (CSymbol) next.data ).isAdditive()) { GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(( (CSymbol) next.data ).convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } //relational for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> node = list.get(i + 1); if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isRelational()) { CSymbol sy = (CSymbol) node.data; GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(sy.convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } //equality for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> node = list.get(i + 1); if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isEquality()) { CSymbol sy = (CSymbol) node.data; GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(sy.convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } //logical and for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> node = list.get(i + 1); if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isLogicalAnd()) { CSymbol sy = (CSymbol) node.data; GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(sy.convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } //logical or for (int i = 0; i < list.size() - 1; i++) { GenericTreeNode<Construct> node = list.get(i + 1); if (node.data instanceof CSymbol && ( (CSymbol) node.data ).isLogicalOr()) { CSymbol sy = (CSymbol) node.data; GenericTreeNode<Construct> conversion = new GenericTreeNode<Construct>(new CFunction(sy.convert(), t)); conversion.addChild(list.get(i)); conversion.addChild(list.get(i + 2)); list.set(i, conversion); list.remove(i + 1); list.remove(i + 1); i } } } catch (IndexOutOfBoundsException e) { throw new ConfigCompileException("Unexpected symbol (" + list.get(list.size() - 1).data.val() + "). Did you forget to quote your symbols?", t); } } //Look for a CEntry here if (list.size() >= 1) { GenericTreeNode<Construct> node = list.get(0); if (node.data instanceof CLabel) { GenericTreeNode<Construct> value = new GenericTreeNode<Construct>(new CFunction("__autoconcat__", t)); for (int i = 1; i < list.size(); i++) { value.addChild(list.get(i)); } GenericTreeNode<Construct> ce = new GenericTreeNode<Construct>(new CFunction("centry", t)); ce.addChild(node); ce.addChild(value); return ce; } } //We've eliminated the need for __autoconcat__ either way, however, if there are still arguments //left, it needs to go to sconcat, which MAY be able to be further optimized, but that will //be handled in MethodScriptCompiler's optimize function. Also, we must scan for CPreIdentifiers, //which may be turned into a function if (list.size() == 1) { return list.get(0); } else { for(int i = 0; i < list.size(); i++){ if(list.get(i).data.getCType() == Construct.ConstructType.IDENTIFIER){ if(i == 0){ //Yup, it's an identifier CFunction identifier = new CFunction(list.get(i).data.val(), t); list.remove(0); GenericTreeNode<Construct> child = list.get(0); if(list.size() > 1){ child = new GenericTreeNode<Construct>(new CFunction("sconcat", t)); child.setChildren(list); } try{ Function f = (Function)FunctionList.getFunction(identifier); GenericTreeNode<Construct> node = new GenericTreeNode<Construct>(f.execs(t, null, null, child)); return node; } catch(Exception e){ throw new Error("Unknown function " + identifier.val() + "?"); } } else { //Hmm, this is weird. I'm not sure what condition this can happen in throw new ConfigCompileException("Unexpected IDENTIFIER? O.o Please report a bug," + " and include the script you used to get this error.", t); } } } GenericTreeNode<Construct> tree; if (returnSConcat) { tree = new GenericTreeNode<Construct>(new CFunction("sconcat", t)); } else { tree = new GenericTreeNode<Construct>(new CFunction("concat", t)); } tree.setChildren(list); return tree; } } @Override public boolean appearInDocumentation() { return false; } } @api public static class npe extends AbstractFunction { public String getName() { return "npe"; } public Integer[] numArgs() { return new Integer[]{0}; } public String docs() { return "void {}"; } public Exceptions.ExceptionType[] thrown() { return null; } public boolean isRestricted() { return true; } public CHVersion since() { return CHVersion.V0_0_0; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env env, Construct... args) throws ConfigRuntimeException { Object o = null; o.toString(); return new CVoid(t); } @Override public boolean appearInDocumentation() { return false; } } @api public static class dyn extends AbstractFunction{ public String getName() { return "dyn"; } public Integer[] numArgs() { return new Integer[]{0, 1}; } public String docs() { return "exception {[argument]} Registers as a dynamic component, for optimization testing; that is" + " to say, this will not be optimizable ever." + " It simply returns the argument provided, or void if none."; } public ExceptionType[] thrown() { return null; } public boolean isRestricted() { return false; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env environment, Construct... args) throws ConfigRuntimeException { if(args.length == 0){ return new CVoid(t); } return args[0]; } public CHVersion since() { return CHVersion.V0_0_0; } @Override public boolean appearInDocumentation() { return false; } } }
package gov.nih.nci.rembrandt.web.ajax; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import gov.nih.nci.caintegrator.application.configuration.SpringContext; import gov.nih.nci.caintegrator.application.lists.ListOrigin; import gov.nih.nci.caintegrator.application.lists.UserList; import gov.nih.nci.caintegrator.application.lists.UserListBeanHelper; import gov.nih.nci.caintegrator.application.workspace.TreeStructureType; import gov.nih.nci.caintegrator.application.workspace.Workspace; import gov.nih.nci.caintegrator.application.workspace.WorkspaceList; import gov.nih.nci.caintegrator.security.UserCredentials; import gov.nih.nci.rembrandt.util.RembrandtConstants; import gov.nih.nci.rembrandt.util.RembrandtListLoader; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import uk.ltd.getahead.dwr.WebContext; import uk.ltd.getahead.dwr.WebContextFactory; public class WorkspaceHelper { private static RembrandtListLoader myListLoader = (RembrandtListLoader) SpringContext.getBean("listLoader"); public WorkspaceHelper() {} public static Workspace fetchWorkspaceFromDB(Long userId){ Workspace workspace = null; if(userId != null){ workspace = myListLoader.loadTreeStructure(userId, TreeStructureType.LIST); } return workspace; } public static String fetchTreeStructures() { String trees = ""; WebContext ctx = WebContextFactory.get(); HttpServletRequest req = ctx.getHttpServletRequest(); HttpSession sess = req.getSession(); JSONArray jsa = generateJSONArray(sess); trees = jsa.toString(); //store it to DB when DAOs are ready sess.setAttribute(RembrandtConstants.OLIST_STRUCT, trees); return trees; } public static JSONArray generateJSONArray(HttpSession sess) { String trees; UserCredentials credentials = (UserCredentials)sess.getAttribute(RembrandtConstants.USER_CREDENTIALS); ////// NOTE: we want to read this from the DB, if null then create and persist Workspace workspace = fetchWorkspaceFromDB(credentials.getUserId()); if(workspace != null && workspace.getTreeStructure()!= null) { trees = workspace.getTreeStructure(); sess.setAttribute(RembrandtConstants.WORKSPACE, workspace); }else{ trees = null; } //check the DB first (using session for testing), create initial struct if none exists //if(trees == null) { ////////////// TEST DATA String //trees = "[ { 'id' : 'root', 'txt' : 'Lists', 'editable': false, 'items' : [ { 'id' : 'ast', 'txt' : 'ASTROCYTOMA', 'editable': false, 'acceptdrop' : false }, { 'id' : 'branch_t21', 'txt' : 'high survival patients', 'img' : 'folder.gif', 'items' : [ { 'id': 'sub11', 'txt': 'my patient list', 'editable': false, 'acceptdrop' : false } ] }, { 'id' : 'branch_t22', 'txt' : 'ALL GLIOMA', 'editable': false, 'acceptdrop' : false }, { 'id' : 'branch_t23', 'txt' : 'MySaved Patients', 'editable': false, 'acceptdrop' : false }, { 'id' : 'branch_t24', 'txt' : 'Patients_good_survival', 'editable': false, 'acceptdrop' : false }, { 'id' : 'trash', 'last' : true, 'draggable' : false, 'txt' : 'Trash', 'img' : 'trash.gif', 'imgopen' : 'trash.gif', 'imgclose' : 'trash.gif', 'open' : false, 'editable': false, 'tooltip' : 'Items here will be removed when the workspace is saved', 'items' : [ { 'id': 'sub1', 'txt': 'one to delete' , 'editable': false, 'acceptdrop' : false } ] } ] } ]"; //generate the Tree on the first time thru, and persist UserListBeanHelper ulbh = new UserListBeanHelper(sess.getId()); List<UserList> uls = ulbh.getAllLists(); //getAllLists() for testing, getAllCustomLists() for prod //convert this into the JSON format we need JSONArray jsa = new JSONArray(); JSONObject root = null; JSONObject customList = null; JSONArray customItems = null; JSONArray rootItems = null; if(trees != null){ List<String> listNames = new ArrayList<String>(); Object obj=JSONValue.parse(trees); jsa=(JSONArray)obj; Iterator jsa_iterator = jsa.iterator(); while(jsa_iterator.hasNext()){ obj = jsa_iterator.next(); if( obj instanceof JSONObject){ root = (JSONObject)obj; if(root.containsValue("Lists")){ rootItems = (JSONArray) root.get("items"); Iterator root_iterator = rootItems.iterator(); while(root_iterator.hasNext()){ obj = root_iterator.next(); if( obj instanceof JSONObject){ JSONObject jsaObj = (JSONObject)obj; String txt = (String)jsaObj.get("txt"); String id = (String)jsaObj.get("id"); if(txt != null && id !=null && txt.equals(id)){ listNames.add(id); } if(jsaObj.containsValue("Custom Lists")){ customList = jsaObj; customItems = (JSONArray) customList.get("items"); } } } } } } JSONArray newItems = new JSONArray(); for(String name: listNames){ for(UserList ul : uls){ if(ul.getListOrigin().equals(ListOrigin.Custom)){ if(!name.equals(ul.getName())){ JSONObject theList = new JSONObject(); theList.put("id", ul.getName()); //can nodes contain spaces? theList.put("editable", false); theList.put("txt", ul.getName()); theList.put("acceptdrop", false); theList.put("tooltip", ul.getListOrigin() + " " + ul.getListType() + " (" + ul.getItemCount() + ")"); //TODO: set the style att for a CSS class that will color by list type? newItems.add(theList); } } } } customItems.addAll(newItems); }else { root= new JSONObject(); root.put("id", "root"); root.put("txt", "Lists"); root.put("editable", false); rootItems = new JSONArray(); //for each list, add it to the root folder, since they arent organized yet customList = new JSONObject(); customList.put("id", "custom"); customList.put("txt", "Custom Lists"); customList.put("editable", false); customItems = new JSONArray(); for(UserList ul : uls){ if(ul.getListOrigin().equals(ListOrigin.Custom)){ //if(!jsaObj.containsValue(ul.getName())){ JSONObject theList = new JSONObject(); theList.put("id", ul.getName()); //can nodes contain spaces? theList.put("editable", false); theList.put("txt", ul.getName()); theList.put("acceptdrop", false); theList.put("tooltip", ul.getListOrigin() + " " + ul.getListType() + " (" + ul.getItemCount() + ")"); //TODO: set the style att for a CSS class that will color by list type? customItems.add(theList); } } customList.put("items", customItems); rootItems.add(customList); root.put("items", customItems); //add the trash JSONObject trashList = new JSONObject(); trashList.put("id", "trash"); trashList.put("last", true); trashList.put("draggable", false); trashList.put("txt", "Trash"); trashList.put("editable", false); trashList.put("img", "trash.gif"); trashList.put("imgopen", "trash.gif"); trashList.put("imgclose", "trash.gif"); trashList.put("open", false); trashList.put("tooltip", "Items here will be removed when the workspace is saved"); rootItems.add(trashList); root.put("items", rootItems); jsa.add(root); } return jsa; } public static String saveTreeStructures(String treeString) { //this should be an array or hash //for testing, its just 1 string now //need to decouple this from DWR, so other classes (i.e. logoutAction can call this and access the session) WebContext ctx = WebContextFactory.get(); HttpServletRequest req = ctx.getHttpServletRequest(); HttpSession sess = req.getSession(); UserListBeanHelper ulbh = new UserListBeanHelper(sess.getId()); JSONObject node = findNode( treeString, "Trash" ); String tree = removeNodeItems( ulbh, node, treeString ); sess.setAttribute(RembrandtConstants.OLIST_STRUCT, tree); saveWorkspace( req.getSession().getId(), req, sess ); return "pass"; } public static String saveWorkspace(String sessionId, HttpServletRequest req, HttpSession sess ){ /* * User has selected to save the current session and log out of the * application */ UserCredentials credentials = (UserCredentials)req.getSession().getAttribute(RembrandtConstants.USER_CREDENTIALS); if(!"RBTuser".equals(credentials.getUserName())) { //Check to see user also created some custom lists. // UserListBeanHelper userListBeanHelper = new UserListBeanHelper(req.getSession().getId()); // List<UserList> customLists = userListBeanHelper.getAllCustomLists(); // if (!customLists.isEmpty()){ // myListLoader.saveUserCustomLists(req.getSession().getId(), credentials.getUserName()); // List<UserList> removedLists = userListBeanHelper.getAllDeletedCustomLists(); // if (!removedLists.isEmpty()){ // myListLoader.deleteUserCustomLists(req.getSession().getId(), credentials.getUserName()); //get Tree from session to save to DB String tree = (String) req.getSession().getAttribute(RembrandtConstants.OLIST_STRUCT); Workspace workspace = (Workspace) req.getSession().getAttribute(RembrandtConstants.WORKSPACE); Long userId = credentials.getUserId(); //Save Lists if(tree != null && userId != null){ myListLoader.saveTreeStructure(userId, TreeStructureType.LIST, tree, workspace); } return "pass"; } return "fail"; } public static JSONObject findNode( String tree, String inName ) { JSONArray workspaceList=(JSONArray)JSONValue.parse(tree); JSONObject root = null; JSONArray rootItems = null; JSONObject node = null; Iterator iterator = workspaceList.iterator(); Object obj = null; while(iterator.hasNext()){ obj = iterator.next(); root = (JSONObject)obj; if(root.containsValue("Lists")){ if( inName.equals( "Lists")) // User wants the top root { return root; } rootItems = (JSONArray) root.get("items"); node = findNodeInTree(rootItems, inName ); // recursive call to find the node in the tree } } return node; } private static JSONObject findNodeInTree(JSONArray items, String inName ) { Object obj; Iterator iterator = items.iterator(); while(iterator.hasNext()){ obj = iterator.next(); JSONObject jsaObj = (JSONObject)obj; if(jsaObj.containsValue(inName)) { // found the node return jsaObj; } else // search recursively { JSONArray customItems = (JSONArray) jsaObj.get("items"); jsaObj = findNodeInTree(customItems, inName ); if ( jsaObj != null ) return jsaObj; } } return null; } private static String removeNodeItems(UserListBeanHelper ulbh, JSONObject node, String treeString) { Object obj; JSONArray customItems; customItems = (JSONArray) node.get("items"); List<UserList> uls = ulbh.getAllCustomLists(); Iterator custom_iterator = customItems.iterator(); while(custom_iterator.hasNext()){ obj = custom_iterator.next(); JSONObject customObj = (JSONObject)obj; boolean found = ulbh.listExists((String)customObj.get("txt") ); if ( found ) { ulbh.removeList( (String)customObj.get("txt") ); } else // then it is a folder. search recursively { removeNodeItems( ulbh, customObj, treeString ); } } JSONArray workspaceList = cleanTree(ulbh, node, treeString); return workspaceList.toString(); } private static JSONArray cleanTree(UserListBeanHelper ulbh, JSONObject node, String treeString) { JSONArray workspaceList=(JSONArray)JSONValue.parse(treeString); JSONObject root = null; JSONArray rootItems = null; JSONObject customObj = null; root = (JSONObject)workspaceList.get(0); // the first item is Lists rootItems = (JSONArray) root.get("items"); Iterator iterator = rootItems.iterator(); while(iterator.hasNext()){ customObj = (JSONObject)iterator.next(); if(customObj.containsValue( node.get("txt") )){ customObj.clear(); break; } boolean found = ulbh.listExists((String)customObj.get("txt") ); if ( ! found ) // then it is a folder. search recursively { cleanTree( ulbh, customObj, treeString ); } } return workspaceList; } }
package gov.nih.nci.sdk.server.management; import java.util.List; import org.apache.log4j.Logger; import gov.nih.nci.sdk.common.ApplicationException; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import net.sf.hibernate.Criteria; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.Transaction; import net.sf.hibernate.expression.Example; /** * @author kumarvi * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class HibernateDAO { private SessionFactory sf; static final Logger log = Logger.getLogger(HibernateDAO.class.getName()); public HibernateDAO(){ this.sf=ApplicationSessionFactory.getSessionFactory(); } public Object createObject(Object obj) throws ApplicationException{ Session s = null; Transaction t = null; try { s = sf.openSession(); t = s.beginTransaction(); s.save(obj); t.commit(); } catch (Exception ex) { log.error(ex); try { t.rollback(); } catch (Exception ex3){ if (log.isDebugEnabled()) log.debug("createObject|Failure|Error in Rolling Back Transaction|"+ ex3.getMessage()); } if (log.isDebugEnabled()) log .debug("createObject|Failure|Error in creating the "+ obj.getClass().getName()+ ex.getMessage()); throw new ApplicationException("An error occured in creating the "+obj.getClass().getName() + "\n" + ex.getMessage(), ex); } finally { try { s.close(); } catch (Exception ex2) { if (log.isDebugEnabled()) log.debug("createObject|Failure|Error in Closing Session |" + ex2.getMessage()); } } if (log.isDebugEnabled()) log .debug("createObject|Success|Successful in creating the "+ obj.getClass().getName()); return obj; } public Object updateObject(Object obj) throws ApplicationException{ Session s = null; Transaction t = null; try { s = sf.openSession(); t = s.beginTransaction(); s.update(obj); t.commit(); } catch (Exception ex) { log.error(ex); try { t.rollback(); } catch (Exception ex3){ if (log.isDebugEnabled()) log.debug("updateObject|Failure|Error in Rolling Back Transaction|"+ ex3.getMessage()); } if (log.isDebugEnabled()) log .debug("updateObject|Failure|Error in updating the "+ obj.getClass().getName()+ ex.getMessage()); throw new ApplicationException("An error occured in updating the "+obj.getClass().getName() + "\n" + ex.getMessage(), ex); } finally { try { s.close(); } catch (Exception ex2) { if (log.isDebugEnabled()) log.debug("updateObject|Failure|Error in Closing Session |" + ex2.getMessage()); } } if (log.isDebugEnabled()) log .debug("updateObject|Success|Successful in updating the "+ obj.getClass().getName()); return obj; } public void removeObject(Object obj) throws ApplicationException{ Session s = null; Transaction t = null; try { s = sf.openSession(); t = s.beginTransaction(); s.delete(obj); t.commit(); } catch (Exception ex) { log.error(ex); try { t.rollback(); } catch (Exception ex3){ if (log.isDebugEnabled()) log.debug("deleteObject|Failure|Error in Rolling Back Transaction|"+ ex3.getMessage()); } if (log.isDebugEnabled()) log .debug("deleteObject|Failure|Error in removing the "+ obj.getClass().getName()+ ex.getMessage()); throw new ApplicationException("An error occured in removing the "+obj.getClass().getName() + "\n" + ex.getMessage(), ex); } finally { try { s.close(); } catch (Exception ex2) { if (log.isDebugEnabled()) log.debug("deleteObject|Failure|Error in Closing Session |" + ex2.getMessage()); } } if (log.isDebugEnabled()) log .debug("deleteObject|Success|Successful in deleting the "+ obj.getClass().getName()); } public List getObjects(Object obj) throws ApplicationException{ Session s = null; List list = null; try { s = sf.openSession(); Criteria c = s.createCriteria(obj.getClass()); c.add(Example.create(obj)); list = c.list(); } catch (Exception ex){ log.error(ex); if (log.isDebugEnabled()) log .debug("getObjects|Failure|Error in getting objects"+ ex.getMessage()); throw new ApplicationException("An error occured in getting objects" + "\n" + ex.getMessage(), ex); }finally { try { s.close(); } catch (Exception ex2) { if (log.isDebugEnabled()) log.debug("getObjects|Failure|Error in Closing Session |" + ex2.getMessage()); } } if (log.isDebugEnabled()) log .debug("getObjects|Success|Successful in deleting the "+ obj.getClass().getName()); return list; } }
package com.machinezoo.sourceafis; import static java.util.stream.Collectors.*; import java.util.*; import java.util.stream.*; import com.machinezoo.fingerprintio.*; import com.machinezoo.fingerprintio.ansi378v2004.*; import com.machinezoo.fingerprintio.ansi378v2009.*; import com.machinezoo.fingerprintio.ansi378v2009am1.*; import com.machinezoo.fingerprintio.iso19794p2v2005.*; import com.machinezoo.fingerprintio.iso19794p2v2011.*; abstract class TemplateCodec { abstract byte[] encode(List<MutableTemplate> templates); abstract List<MutableTemplate> decode(byte[] serialized, boolean strict); List<MutableTemplate> decode(byte[] serialized) { try { return decode(serialized, true); } catch (Throwable ex) { return decode(serialized, false); } } static final Map<TemplateFormat, TemplateCodec> ALL = new HashMap<>(); static { ALL.put(TemplateFormat.ANSI_378_2004, new Ansi378v2004Codec()); ALL.put(TemplateFormat.ANSI_378_2009, new Ansi378v2009Codec()); ALL.put(TemplateFormat.ANSI_378_2009_AM1, new Ansi378v2009Am1Codec()); ALL.put(TemplateFormat.ISO_19794_2_2005, new Iso19794p2v2005Codec()); ALL.put(TemplateFormat.ISO_19794_2_2011, new Iso19794p2v2011Codec()); } static class Resolution { double dpiX; double dpiY; } static IntPoint decode(int x, int y, Resolution resolution) { return new IntPoint(decode(x, resolution.dpiX), decode(y, resolution.dpiY)); } static int decode(int value, double dpi) { return (int)Math.round(value / dpi * 500); } private static class Ansi378v2004Codec extends TemplateCodec { @Override byte[] encode(List<MutableTemplate> templates) { int resolution = (int)Math.round(500 / 2.54); Ansi378v2004Template iotemplate = new Ansi378v2004Template(); iotemplate.width = templates.stream().mapToInt(t -> t.size.x).max().orElse(500); iotemplate.height = templates.stream().mapToInt(t -> t.size.y).max().orElse(500); iotemplate.resolutionX = resolution; iotemplate.resolutionY = resolution; iotemplate.fingerprints = IntStream.range(0, templates.size()) .mapToObj(n -> encode(n, templates.get(n))) .collect(toList()); return iotemplate.toByteArray(); } @Override List<MutableTemplate> decode(byte[] serialized, boolean strict) { Ansi378v2004Template iotemplate = new Ansi378v2004Template(serialized, strict); Resolution resolution = new Resolution(); resolution.dpiX = iotemplate.resolutionX * 2.54; resolution.dpiY = iotemplate.resolutionY * 2.54; return iotemplate.fingerprints.stream() .map(fp -> decode(fp, iotemplate, resolution)) .collect(toList()); } static Ansi378v2004Fingerprint encode(int offset, MutableTemplate template) { Ansi378v2004Fingerprint iofingerprint = new Ansi378v2004Fingerprint(); iofingerprint.view = offset; iofingerprint.minutiae = template.minutiae.stream() .map(m -> encode(m)) .collect(toList()); return iofingerprint; } static MutableTemplate decode(Ansi378v2004Fingerprint iofingerprint, Ansi378v2004Template iotemplate, Resolution resolution) { MutableTemplate template = new MutableTemplate(); template.size = decode(iotemplate.width, iotemplate.height, resolution); template.minutiae = iofingerprint.minutiae.stream() .map(m -> decode(m, resolution)) .collect(toList()); return template; } static Ansi378v2004Minutia encode(MutableMinutia minutia) { Ansi378v2004Minutia iominutia = new Ansi378v2004Minutia(); iominutia.positionX = minutia.position.x; iominutia.positionY = minutia.position.y; iominutia.angle = encodeAngle(minutia.direction); iominutia.type = encode(minutia.type); return iominutia; } static MutableMinutia decode(Ansi378v2004Minutia iominutia, Resolution resolution) { MutableMinutia minutia = new MutableMinutia(); minutia.position = decode(iominutia.positionX, iominutia.positionY, resolution); minutia.direction = decodeAngle(iominutia.angle); minutia.type = decode(iominutia.type); return minutia; } static int encodeAngle(double angle) { return (int)Math.ceil(DoubleAngle.complementary(angle) * DoubleAngle.INV_PI2 * 360 / 2) % 180; } static double decodeAngle(int ioangle) { return DoubleAngle.complementary(((2 * ioangle - 1 + 360) % 360) / 360.0 * DoubleAngle.PI2); } static Ansi378v2004MinutiaType encode(MinutiaType type) { switch (type) { case ENDING: return Ansi378v2004MinutiaType.ENDING; case BIFURCATION: return Ansi378v2004MinutiaType.BIFURCATION; default: return Ansi378v2004MinutiaType.ENDING; } } static MinutiaType decode(Ansi378v2004MinutiaType iotype) { switch (iotype) { case ENDING: return MinutiaType.ENDING; case BIFURCATION: return MinutiaType.BIFURCATION; default: return MinutiaType.ENDING; } } } private static class Ansi378v2009Codec extends TemplateCodec { @Override byte[] encode(List<MutableTemplate> templates) { Ansi378v2009Template iotemplate = new Ansi378v2009Template(); iotemplate.fingerprints = IntStream.range(0, templates.size()) .mapToObj(n -> encode(n, templates.get(n))) .collect(toList()); return iotemplate.toByteArray(); } @Override List<MutableTemplate> decode(byte[] serialized, boolean strict) { return new Ansi378v2009Template(serialized, strict).fingerprints.stream() .map(fp -> decode(fp)) .collect(toList()); } static Ansi378v2009Fingerprint encode(int offset, MutableTemplate template) { int resolution = (int)Math.round(500 / 2.54); Ansi378v2009Fingerprint iofingerprint = new Ansi378v2009Fingerprint(); iofingerprint.view = offset; iofingerprint.width = template.size.x; iofingerprint.height = template.size.y; iofingerprint.resolutionX = resolution; iofingerprint.resolutionY = resolution; iofingerprint.minutiae = template.minutiae.stream() .map(m -> encode(m)) .collect(toList()); return iofingerprint; } static MutableTemplate decode(Ansi378v2009Fingerprint iofingerprint) { Resolution resolution = new Resolution(); resolution.dpiX = iofingerprint.resolutionX * 2.54; resolution.dpiY = iofingerprint.resolutionY * 2.54; MutableTemplate template = new MutableTemplate(); template.size = decode(iofingerprint.width, iofingerprint.height, resolution); template.minutiae = iofingerprint.minutiae.stream() .map(m -> decode(m, resolution)) .collect(toList()); return template; } static Ansi378v2009Minutia encode(MutableMinutia minutia) { Ansi378v2009Minutia iominutia = new Ansi378v2009Minutia(); iominutia.positionX = minutia.position.x; iominutia.positionY = minutia.position.y; iominutia.angle = encodeAngle(minutia.direction); iominutia.type = encode(minutia.type); return iominutia; } static MutableMinutia decode(Ansi378v2009Minutia iominutia, Resolution resolution) { MutableMinutia minutia = new MutableMinutia(); minutia.position = decode(iominutia.positionX, iominutia.positionY, resolution); minutia.direction = decodeAngle(iominutia.angle); minutia.type = decode(iominutia.type); return minutia; } static int encodeAngle(double angle) { return (int)Math.ceil(DoubleAngle.complementary(angle) * DoubleAngle.INV_PI2 * 360 / 2) % 180; } static double decodeAngle(int ioangle) { return DoubleAngle.complementary(((2 * ioangle - 1 + 360) % 360) / 360.0 * DoubleAngle.PI2); } static Ansi378v2009MinutiaType encode(MinutiaType type) { switch (type) { case ENDING: return Ansi378v2009MinutiaType.ENDING; case BIFURCATION: return Ansi378v2009MinutiaType.BIFURCATION; default: return Ansi378v2009MinutiaType.ENDING; } } static MinutiaType decode(Ansi378v2009MinutiaType iotype) { switch (iotype) { case ENDING: return MinutiaType.ENDING; case BIFURCATION: return MinutiaType.BIFURCATION; default: return MinutiaType.ENDING; } } } private static class Ansi378v2009Am1Codec extends TemplateCodec { @Override byte[] encode(List<MutableTemplate> templates) { Ansi378v2009Am1Template iotemplate = new Ansi378v2009Am1Template(); iotemplate.fingerprints = IntStream.range(0, templates.size()) .mapToObj(n -> encode(n, templates.get(n))) .collect(toList()); return iotemplate.toByteArray(); } @Override List<MutableTemplate> decode(byte[] serialized, boolean strict) { return new Ansi378v2009Am1Template(serialized, strict).fingerprints.stream() .map(fp -> decode(fp)) .collect(toList()); } static Ansi378v2009Am1Fingerprint encode(int offset, MutableTemplate template) { int resolution = (int)Math.round(500 / 2.54); Ansi378v2009Am1Fingerprint iofingerprint = new Ansi378v2009Am1Fingerprint(); iofingerprint.view = offset; iofingerprint.width = template.size.x; iofingerprint.height = template.size.y; iofingerprint.resolutionX = resolution; iofingerprint.resolutionY = resolution; iofingerprint.minutiae = template.minutiae.stream() .map(m -> encode(m)) .collect(toList()); return iofingerprint; } static MutableTemplate decode(Ansi378v2009Am1Fingerprint iofingerprint) { Resolution resolution = new Resolution(); resolution.dpiX = iofingerprint.resolutionX * 2.54; resolution.dpiY = iofingerprint.resolutionY * 2.54; MutableTemplate template = new MutableTemplate(); template.size = decode(iofingerprint.width, iofingerprint.height, resolution); template.minutiae = iofingerprint.minutiae.stream() .map(m -> decode(m, resolution)) .collect(toList()); return template; } static Ansi378v2009Am1Minutia encode(MutableMinutia minutia) { Ansi378v2009Am1Minutia iominutia = new Ansi378v2009Am1Minutia(); iominutia.positionX = minutia.position.x; iominutia.positionY = minutia.position.y; iominutia.angle = encodeAngle(minutia.direction); iominutia.type = encode(minutia.type); return iominutia; } static MutableMinutia decode(Ansi378v2009Am1Minutia iominutia, Resolution resolution) { MutableMinutia minutia = new MutableMinutia(); minutia.position = decode(iominutia.positionX, iominutia.positionY, resolution); minutia.direction = decodeAngle(iominutia.angle); minutia.type = decode(iominutia.type); return minutia; } static int encodeAngle(double angle) { return (int)Math.ceil(DoubleAngle.complementary(angle) * DoubleAngle.INV_PI2 * 360 / 2) % 180; } static double decodeAngle(int ioangle) { return DoubleAngle.complementary(((2 * ioangle - 1 + 360) % 360) / 360.0 * DoubleAngle.PI2); } static Ansi378v2009Am1MinutiaType encode(MinutiaType type) { switch (type) { case ENDING: return Ansi378v2009Am1MinutiaType.ENDING; case BIFURCATION: return Ansi378v2009Am1MinutiaType.BIFURCATION; default: return Ansi378v2009Am1MinutiaType.ENDING; } } static MinutiaType decode(Ansi378v2009Am1MinutiaType iotype) { switch (iotype) { case ENDING: return MinutiaType.ENDING; case BIFURCATION: return MinutiaType.BIFURCATION; default: return MinutiaType.ENDING; } } } private static class Iso19794p2v2005Codec extends TemplateCodec { @Override byte[] encode(List<MutableTemplate> templates) { int resolution = (int)Math.round(500 / 2.54); Iso19794p2v2005Template iotemplate = new Iso19794p2v2005Template(); iotemplate.width = templates.stream().mapToInt(t -> t.size.x).max().orElse(500); iotemplate.height = templates.stream().mapToInt(t -> t.size.y).max().orElse(500); iotemplate.resolutionX = resolution; iotemplate.resolutionY = resolution; iotemplate.fingerprints = IntStream.range(0, templates.size()) .mapToObj(n -> encode(n, templates.get(n))) .collect(toList()); return iotemplate.toByteArray(); } @Override List<MutableTemplate> decode(byte[] serialized, boolean strict) { Iso19794p2v2005Template iotemplate = new Iso19794p2v2005Template(serialized, strict); Resolution resolution = new Resolution(); resolution.dpiX = iotemplate.resolutionX * 2.54; resolution.dpiY = iotemplate.resolutionY * 2.54; return iotemplate.fingerprints.stream() .map(fp -> decode(fp, iotemplate, resolution)) .collect(toList()); } static Iso19794p2v2005Fingerprint encode(int offset, MutableTemplate template) { Iso19794p2v2005Fingerprint iofingerprint = new Iso19794p2v2005Fingerprint(); iofingerprint.view = offset; iofingerprint.minutiae = template.minutiae.stream() .map(m -> encode(m)) .collect(toList()); return iofingerprint; } static MutableTemplate decode(Iso19794p2v2005Fingerprint iofingerprint, Iso19794p2v2005Template iotemplate, Resolution resolution) { MutableTemplate template = new MutableTemplate(); template.size = decode(iotemplate.width, iotemplate.height, resolution); template.minutiae = iofingerprint.minutiae.stream() .map(m -> decode(m, resolution)) .collect(toList()); return template; } static Iso19794p2v2005Minutia encode(MutableMinutia minutia) { Iso19794p2v2005Minutia iominutia = new Iso19794p2v2005Minutia(); iominutia.positionX = minutia.position.x; iominutia.positionY = minutia.position.y; iominutia.angle = encodeAngle(minutia.direction); iominutia.type = encode(minutia.type); return iominutia; } static MutableMinutia decode(Iso19794p2v2005Minutia iominutia, Resolution resolution) { MutableMinutia minutia = new MutableMinutia(); minutia.position = decode(iominutia.positionX, iominutia.positionY, resolution); minutia.direction = decodeAngle(iominutia.angle); minutia.type = decode(iominutia.type); return minutia; } static int encodeAngle(double angle) { return (int)Math.round(DoubleAngle.complementary(angle) * DoubleAngle.INV_PI2 * 256) & 0xff; } static double decodeAngle(int ioangle) { return DoubleAngle.complementary(ioangle / 256.0 * DoubleAngle.PI2); } static Iso19794p2v2005MinutiaType encode(MinutiaType type) { switch (type) { case ENDING: return Iso19794p2v2005MinutiaType.ENDING; case BIFURCATION: return Iso19794p2v2005MinutiaType.BIFURCATION; default: return Iso19794p2v2005MinutiaType.ENDING; } } static MinutiaType decode(Iso19794p2v2005MinutiaType iotype) { switch (iotype) { case ENDING: return MinutiaType.ENDING; case BIFURCATION: return MinutiaType.BIFURCATION; default: return MinutiaType.ENDING; } } } private static class Iso19794p2v2011Codec extends TemplateCodec { @Override byte[] encode(List<MutableTemplate> templates) { Iso19794p2v2011Template iotemplate = new Iso19794p2v2011Template(); iotemplate.fingerprints = IntStream.range(0, templates.size()) .mapToObj(n -> encode(n, templates.get(n))) .collect(toList()); return iotemplate.toByteArray(); } @Override List<MutableTemplate> decode(byte[] serialized, boolean strict) { Iso19794p2v2011Template iotemplate = new Iso19794p2v2011Template(serialized, strict); return iotemplate.fingerprints.stream() .map(fp -> decode(fp)) .collect(toList()); } static Iso19794p2v2011Fingerprint encode(int offset, MutableTemplate template) { int resolution = (int)Math.round(500 / 2.54); Iso19794p2v2011Fingerprint iofingerprint = new Iso19794p2v2011Fingerprint(); iofingerprint.view = offset; iofingerprint.width = template.size.x; iofingerprint.height = template.size.y; iofingerprint.resolutionX = resolution; iofingerprint.resolutionY = resolution; iofingerprint.endingType = Iso19794p2v2011EndingType.RIDGE_SKELETON_ENDPOINT; iofingerprint.minutiae = template.minutiae.stream() .map(m -> encode(m)) .collect(toList()); return iofingerprint; } static MutableTemplate decode(Iso19794p2v2011Fingerprint iofingerprint) { Resolution resolution = new Resolution(); resolution.dpiX = iofingerprint.resolutionX * 2.54; resolution.dpiY = iofingerprint.resolutionY * 2.54; MutableTemplate template = new MutableTemplate(); template.size = decode(iofingerprint.width, iofingerprint.height, resolution); template.minutiae = iofingerprint.minutiae.stream() .map(m -> decode(m, resolution)) .collect(toList()); return template; } static Iso19794p2v2011Minutia encode(MutableMinutia minutia) { Iso19794p2v2011Minutia iominutia = new Iso19794p2v2011Minutia(); iominutia.positionX = minutia.position.x; iominutia.positionY = minutia.position.y; iominutia.angle = encodeAngle(minutia.direction); iominutia.type = encode(minutia.type); return iominutia; } static MutableMinutia decode(Iso19794p2v2011Minutia iominutia, Resolution resolution) { MutableMinutia minutia = new MutableMinutia(); minutia.position = decode(iominutia.positionX, iominutia.positionY, resolution); minutia.direction = decodeAngle(iominutia.angle); minutia.type = decode(iominutia.type); return minutia; } static int encodeAngle(double angle) { return (int)Math.round(DoubleAngle.complementary(angle) * DoubleAngle.INV_PI2 * 256) & 0xff; } static double decodeAngle(int ioangle) { return DoubleAngle.complementary(ioangle / 256.0 * DoubleAngle.PI2); } static Iso19794p2v2011MinutiaType encode(MinutiaType type) { switch (type) { case ENDING: return Iso19794p2v2011MinutiaType.ENDING; case BIFURCATION: return Iso19794p2v2011MinutiaType.BIFURCATION; default: return Iso19794p2v2011MinutiaType.ENDING; } } static MinutiaType decode(Iso19794p2v2011MinutiaType iotype) { switch (iotype) { case ENDING: return MinutiaType.ENDING; case BIFURCATION: return MinutiaType.BIFURCATION; default: return MinutiaType.ENDING; } } } }
package ie.broadsheet.app.fragments; import ie.broadsheet.app.BaseFragmentActivity; import ie.broadsheet.app.BroadsheetApplication; import ie.broadsheet.app.CommentListActivity; import ie.broadsheet.app.PostDetailActivity; import ie.broadsheet.app.PostListActivity; import ie.broadsheet.app.R; import ie.broadsheet.app.dialog.MakeCommentDialog; import ie.broadsheet.app.model.json.Comment; import ie.broadsheet.app.model.json.Post; import ie.broadsheet.app.model.json.SinglePost; import ie.broadsheet.app.requests.PostRequest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebSettings.PluginState; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.ShareActionProvider; import com.octo.android.robospice.persistence.DurationInMillis; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.request.listener.RequestListener; /** * A fragment representing a single Post detail screen. This fragment is either contained in a {@link PostListActivity} * in two-pane mode (on tablets) or a {@link PostDetailActivity} on handsets. */ public class PostDetailFragment extends SherlockFragment implements MakeCommentDialog.CommentMadeListener, OnClickListener { private static final String TAG = "PostDetailFragment"; /** * The fragment argument representing the item ID that this fragment represents. */ public static final String ARG_ITEM_ID = "item_id"; public static final String ARG_ITEM_URL = "item_url"; private Post mPost; private WebView mWebview; private int mPostIndex = -1; private ShareActionProvider mActionProvider; private Button mNext; private Button mPrevious; private BroadsheetApplication mApp; /** * Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon screen orientation * changes). */ public PostDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String url = getArguments().getString(ARG_ITEM_URL); if (url != null) { ((BaseFragmentActivity) getActivity()).onPreExecute(getResources().getString(R.string.posting_comment)); BaseFragmentActivity activity = (BaseFragmentActivity) getActivity(); PostRequest postRequest = new PostRequest(url); activity.getSpiceManager().execute(postRequest, url, DurationInMillis.ONE_MINUTE, new PostListener()); } else if (getArguments().containsKey(ARG_ITEM_ID)) { mApp = (BroadsheetApplication) getActivity().getApplication(); mPostIndex = getArguments().getInt(ARG_ITEM_ID); mPost = mApp.getPosts().get(mPostIndex); } setHasOptionsMenu(true); getActivity().setTitle(""); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); if (mPost != null) { inflater.inflate(R.menu.post_detail, menu); menu.findItem(R.id.menu_make_comment).setVisible(mPost.getComment_status().equals("open")); menu.findItem(R.id.menu_view_comments).setVisible((mPost.getComment_count() > 0)); MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar); mActionProvider = (ShareActionProvider) actionItem.getActionProvider(); mActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME); mActionProvider.setShareIntent(createShareIntent()); } } @Override public void onPrepareOptionsMenu(Menu menu) { } @Override public void onStart() { super.onStart(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_post_detail, container, false); mWebview = (WebView) rootView.findViewById(R.id.webview); mWebview.getSettings().setJavaScriptEnabled(true); mWebview.setWebViewClient(new MyWebViewClient(this.getActivity())); if (android.os.Build.VERSION.SDK_INT < 8) { mWebview.getSettings().setPluginsEnabled(true); } else { mWebview.getSettings().setPluginState(PluginState.ON); } mNext = (Button) rootView.findViewById(R.id.next); mPrevious = (Button) rootView.findViewById(R.id.previous); mNext.setOnClickListener(this); mPrevious.setOnClickListener(this); if (mPostIndex == -1) { mNext.setVisibility(View.GONE); mPrevious.setVisibility(View.GONE); } if (mPost != null) { layoutView(); } return rootView; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_view_comments) { Intent commentIntent = new Intent(this.getActivity(), CommentListActivity.class); commentIntent.putExtra(PostDetailFragment.ARG_ITEM_ID, mPostIndex); startActivity(commentIntent); return true; } else if (item.getItemId() == R.id.menu_make_comment) { MakeCommentDialog dialog = new MakeCommentDialog(); dialog.setPostId(mPost.getId()); dialog.setCommentMadeListener(this); dialog.show(getActivity().getSupportFragmentManager(), "MakeCommentDialog"); } return super.onOptionsItemSelected(item); } private Intent createShareIntent() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); String shareBody = mPost.getTitle() + " - " + mPost.getUrl(); sharingIntent.setType("text/plain").putExtra(android.content.Intent.EXTRA_SUBJECT, "Broadsheet.ie") .putExtra(android.content.Intent.EXTRA_TEXT, shareBody); return sharingIntent; } @Override public void onCommentMade(Comment comment) { mPost.addComment(comment); } @SuppressLint("SetJavaScriptEnabled") private void layoutView() { String postHTML = "<html><head>"; postHTML += "<style>#singlentry {font-size: 16px;}</style><link href='default.css' rel='stylesheet' type='text/css' />"; postHTML += "</head><body id=\"contentbody\"><div id='maincontent' class='content'><div class='post'><div id='title'>" + mPost.getTitle() + "</div><div><span class='date-color'>" + mPost.getDate() + "</span>&nbsp;<a class='author' href=\"kmwordpress: + mPost.getAuthor().getName() + "</a></div>"; postHTML += "<div id='singlentry'>" + mPost.getContent() + "</div></div>"; postHTML += "</div></body></html>"; mWebview.loadDataWithBaseURL("file:///android_asset/", postHTML, "text/html", "UTF-8", null); mNext.setEnabled((mPostIndex > 0)); mPrevious.setEnabled(((mPostIndex + 1) < mApp.getPosts().size())); mApp.getTracker().sendView( "Post " + Html.fromHtml(mPost.getTitle_plain()) + " " + Integer.toString(mPost.getId())); } @Override public void onClick(View v) { if (v.getId() == R.id.next) { mPostIndex } else if (v.getId() == R.id.previous) { mPostIndex++; } mPost = mApp.getPosts().get(mPostIndex); layoutView(); } // Via public class MyWebViewClient extends WebViewClient { public Activity mActivity; public MyWebViewClient(Activity activity) { super(); mActivity = activity; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getHost().contains("youtube.com")) { viewYoutube(mActivity, url); return true; } else if (url.contains("broadsheet.ie/20")) { viewBroadsheetPost(mActivity, url); return true; } return false; } public void viewYoutube(Context context, String url) { viewWithPackageName(context, url, "com.google.android.youtube"); } public void viewBroadsheetPost(Context context, String url) { Intent postIntent = new Intent(getActivity(), PostDetailActivity.class); postIntent.putExtra(PostDetailFragment.ARG_ITEM_URL, url); startActivity(postIntent); } public void viewWithPackageName(Context context, String url, String packageName) { try { Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (isAppInstalled(context, packageName)) { viewIntent.setPackage(packageName); } context.startActivity(viewIntent); } catch (Exception e) { Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(viewIntent); } } public boolean isAppInstalled(Context context, String packageName) { PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); return true; } catch (NameNotFoundException e) { } return false; } @Override public void onPageFinished(final WebView view, String url) { String javascript = "javascript:" + "var iframes = document.getElementsByTagName('iframe');" + "for (var i = 0, l = iframes.length; i < l; i++) {" + " var iframe = iframes[i]," + " a = document.createElement('a');" + " a.setAttribute('href', iframe.src);" + " d = document.createElement('div');" + " d.style.width = iframe.offsetWidth + 'px';" + " d.style.height = iframe.offsetHeight + 'px';" + " d.style.top = iframe.offsetTop + 'px';" + " d.style.left = iframe.offsetLeft + 'px';" + " d.style.position = 'absolute';" + " d.style.opacity = '0';" + " d.style.filter = 'alpha(opacity=0)';" + " d.style.background = 'black';" + " a.appendChild(d);" + " iframe.offsetParent.appendChild(a);" + "}"; view.loadUrl(javascript); super.onPageFinished(view, url); } } public final class PostListener implements RequestListener<SinglePost> { @Override public void onRequestFailure(SpiceException spiceException) { Log.d(TAG, "Failed to get post"); ((BaseFragmentActivity) getActivity()).onPostExecute(); BaseFragmentActivity activity = (BaseFragmentActivity) getActivity(); activity.showError(getActivity().getString(R.string.post_load_problem)); } @Override public void onRequestSuccess(final SinglePost result) { Log.d(TAG, "we got a post: " + result.toString()); PostDetailFragment.this.mPost = result.getPost(); ((BaseFragmentActivity) getActivity()).onPostExecute(); PostDetailFragment.this.getActivity().invalidateOptionsMenu(); PostDetailFragment.this.layoutView(); } } }
package com.oneliang.tools.builder.base; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Project { public static final String CLASSES = "classes"; public static final String CACHE = "cache"; public static final String BUILD = "build"; protected String workspace = null; protected String name = null; protected String home = null; protected String outputHome = null; protected String classesOutput = null; protected String cacheOutput = null; protected String prepareOutput = null; protected String[] sources = null; protected String[] dependProjects = null; protected List<String> sourceDirectoryList = new ArrayList<String>(); protected Set<String> dependJarSet = new HashSet<String>(); // use in building private List<Project> parentProjectList = null; public Project() { } public Project(String workspace, String name) { this(workspace, name, workspace); } public Project(String workspace, String name, String outputHome) { if (workspace == null || name == null) { throw new NullPointerException("workspace or name is null"); } this.workspace = workspace; this.name = name; this.outputHome = outputHome; } public void initialize() { File file = new File(this.workspace); this.workspace = file.getAbsolutePath(); this.home = this.workspace + "/" + this.name; file = new File(this.outputHome); this.outputHome = file.getAbsolutePath() + "/" + this.name + "/" + BUILD; this.classesOutput = this.outputHome + "/" + CLASSES; this.cacheOutput = this.outputHome + "/" + CACHE; this.prepareOutput = this.outputHome + "/prepare"; } /** * @return the workspace */ public String getWorkspace() { return workspace; } /** * @param workspace * the workspace to set */ public void setWorkspace(String workspace) { this.workspace = workspace; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the home */ public String getHome() { return home; } /** * @param sources * the sources to set */ public void setSources(String[] sources) { if (sources != null && sources.length > 0) { this.sources = sources; } } /** * @return the sourceDirectoryList */ public List<String> getSourceDirectoryList() { return sourceDirectoryList; } /** * @param dependJarSet * the dependJarSet to set */ public void addDependJar(String dependJar) { this.dependJarSet.add(dependJar); } /** * @return the dependJarSet */ public Set<String> getDependJarSet() { return dependJarSet; } /** * @param outputHome * the outputHome to set */ public void setOutputHome(String outputHome) { this.outputHome = outputHome; } /** * @return the outputHome */ public String getOutputHome() { return outputHome; } /** * @param classesOutput * the classesOutput to set */ public void setClassesOutput(String classesOutput) { this.classesOutput = classesOutput; } /** * @return the classesOutput */ public String getClassesOutput() { return classesOutput; } /** * @return the cacheOutput */ public String getCacheOutput() { return cacheOutput; } /** * @return the dependProjects */ public String[] getDependProjects() { return dependProjects; } /** * @param dependProjects * the dependProjects to set */ public void setDependProjects(String[] dependProjects) { this.dependProjects = dependProjects; } /** * @return the prepareOutput */ public String getPrepareOutput() { return prepareOutput; } /** * @return the parentProjectList */ public List<Project> getParentProjectList() { return parentProjectList; } /** * @param parentProjectList * the parentProjectList to set */ public void setParentProjectList(List<Project> parentProjectList) { this.parentProjectList = parentProjectList; } }
package com.plaid.client; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.joda.time.LocalDate; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.plaid.client.exception.PlaidClientsideException; import com.plaid.client.exception.PlaidMfaException; import com.plaid.client.http.HttpDelegate; import com.plaid.client.http.HttpResponseWrapper; import com.plaid.client.http.PlaidHttpRequest; import com.plaid.client.request.ConnectOptions; import com.plaid.client.request.Credentials; import com.plaid.client.response.AccountsResponse; import com.plaid.client.response.MessageResponse; import com.plaid.client.response.PlaidUserResponse; import com.plaid.client.response.TransactionsResponse; public class DefaultPlaidUserClient implements PlaidUserClient { private String accessToken; private String clientId; private String secret; private ObjectMapper jsonMapper; private HttpDelegate httpDelegate; public DefaultPlaidUserClient(HttpDelegate httpDelegate, String clientId, String secret) { this.httpDelegate = httpDelegate; this.clientId = clientId; this.secret = secret; ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setSerializationInclusion(Include.NON_NULL); this.jsonMapper = jsonMapper; } @Override public void setAccessToken(String accesstoken) { this.accessToken = accesstoken; } @Override public String getAccessToken() { return this.accessToken; } @Override public TransactionsResponse addUser(Credentials credentials, String type, String email, ConnectOptions connectOptions) throws PlaidMfaException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("type", type); requestParams.put("email", email); requestParams.put("options", connectOptions); return handlePost("/connect", requestParams, TransactionsResponse.class); } @Override public TransactionsResponse mfaStep(String mfa, String type) throws PlaidMfaException { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect/step", authenticationParams()); request.addParameter("mfa", mfa); if (type != null) { request.addParameter("type", type); } } public AccountsResponse achAuth(Credentials credentials, String type, ConnectOptions connectOptions) throws PlaidMfaException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("type", type); requestParams.put("options", connectOptions); return handlePost("/auth", requestParams, AccountsResponse.class); } @Override public TransactionsResponse mfaConnectStep(String mfa, String type) throws PlaidMfaException { return handleMfa("/connect/step", mfa, type, TransactionsResponse.class); } @Override public TransactionsResponse mfaAuthStep(String mfa, String type) throws PlaidMfaException { return handleMfa("/auth/step", mfa, type, TransactionsResponse.class); } @Override public TransactionsResponse updateTransactions() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams()); HttpResponseWrapper<TransactionsResponse> response = httpDelegate.doGet(request, TransactionsResponse.class); TransactionsResponse body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } @Override public TransactionsResponse updateTransactions(LocalDate from, LocalDate to, String accountId) { throw new UnsupportedOperationException("Not implemented yet"); } @Override public TransactionsResponse updateCredentials(Credentials credentials, String type) { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams()); try { String credentialsString = jsonMapper.writeValueAsString(credentials); request.addParameter("credentials", credentialsString); request.addParameter("type", type); HttpResponseWrapper<TransactionsResponse> response = httpDelegate.doPatch(request, TransactionsResponse.class); TransactionsResponse body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } catch (JsonProcessingException e) { throw new PlaidClientsideException(e); } } @Override public MessageResponse deleteUser() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams()); HttpResponseWrapper<MessageResponse> response = httpDelegate.doDelete(request, MessageResponse.class); return response.getResponseBody(); } @Override public AccountsResponse checkBalance() { throw new UnsupportedOperationException("Not implemented yet"); } private <T extends PlaidUserResponse> T handleMfa(String path, String mfa, String type, Class<T> returnTypeClass) throws PlaidMfaException { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("mfa", mfa); if (type != null) { requestParams.put("type", type); } return handlePost(path, requestParams, returnTypeClass); } private <T extends PlaidUserResponse> T handlePost(String path, Map<String, Object> requestParams, Class<T> returnTypeClass) throws PlaidMfaException { PlaidHttpRequest request = new PlaidHttpRequest(path, authenticationParams()); try { for (String param : requestParams.keySet()) { Object value = requestParams.get(param); if (value == null) { continue; } String stringValue; if (value instanceof String) { stringValue = (String) value; // strings can be used as is } else { stringValue = jsonMapper.writeValueAsString(value); // other objects need to be serialized } request.addParameter(param, stringValue); } } catch (JsonProcessingException e) { throw new PlaidClientsideException(e); } try { HttpResponseWrapper<T> response = httpDelegate.doPost(request, returnTypeClass); T body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } catch (PlaidMfaException e) { setAccessToken(e.getMfaResponse().getAccessToken()); throw e; } } private Map<String, String> authenticationParams() { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("client_id", clientId); parameters.put("secret", secret); if (!StringUtils.isEmpty(accessToken)) { parameters.put("access_token", accessToken); } return parameters; } @Override public HttpDelegate getHttpDelegate() { return httpDelegate; } }
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.loader.MetamodelGenerator; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Constructor; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.SiteVariance; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; /** A convenience class to help with the handling of certain type declarations. */ public class TypeUtils { static final List<String> splitMetamodelAnnotations = Arrays.asList("ceylon.language::doc", "ceylon.language::throws", "ceylon.language::see", "ceylon.language::by"); /** Prints the type arguments, usually for their reification. */ public static void printTypeArguments(final Node node, final Map<TypeParameter,ProducedType> targs, final GenerateJsVisitor gen, final boolean skipSelfDecl, final Map<TypeParameter, SiteVariance> overrides) { gen.out("{"); boolean first = true; for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) { if (first) { first = false; } else { gen.out(","); } gen.out(e.getKey().getName(), "$", e.getKey().getDeclaration().getName(), ":"); final ProducedType pt = e.getValue(); if (pt == null) { gen.out("'", e.getKey().getName(), "'"); } else if (!outputTypeList(node, pt, gen, skipSelfDecl)) { boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty(); boolean closeBracket = false; final TypeDeclaration d = pt.getDeclaration(); if (d instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)d, gen, skipSelfDecl); } else { closeBracket = pt.getDeclaration() instanceof TypeAlias==false; if (closeBracket)gen.out("{t:"); outputQualifiedTypename(node, node != null && gen.isImported(node.getUnit().getPackage(), pt.getDeclaration()), pt, gen, skipSelfDecl); } if (hasParams) { gen.out(",a:"); printTypeArguments(node, pt.getTypeArguments(), gen, skipSelfDecl, pt.getVarianceOverrides()); } SiteVariance siteVariance = overrides == null ? null : overrides.get(e.getKey()); if (siteVariance != null) { gen.out(",", MetamodelGenerator.KEY_US_VARIANCE, ":"); if (siteVariance == SiteVariance.IN) { gen.out("'in'"); } else { gen.out("'out'"); } } if (closeBracket) { gen.out("}"); } } } gen.out("}"); } static void outputQualifiedTypename(final Node node, final boolean imported, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration t = pt.getDeclaration(); final String qname = t.getQualifiedNameString(); if (qname.equals("ceylon.language::Nothing")) { //Hack in the model means hack here as well gen.out(gen.getClAlias(), "Nothing"); } else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) { gen.out(gen.getClAlias(), "Null"); } else if (pt.isUnknown()) { if (!gen.isInDynamicBlock()) { gen.out("/*WARNING unknown type"); gen.location(node); gen.out("*/"); } gen.out(gen.getClAlias(), "Anything"); } else { gen.out(qualifiedTypeContainer(node, imported, t, gen)); boolean _init = (!imported && pt.getDeclaration().isDynamic()) || t.isAnonymous(); if (_init && !pt.getDeclaration().isToplevel()) { Declaration dynintc = Util.getContainingClassOrInterface(node.getScope()); if (dynintc == null || dynintc instanceof Scope==false || !Util.contains((Scope)dynintc, pt.getDeclaration())) { _init=false; } } if (_init) { gen.out("$init$"); } if (!outputTypeList(null, pt, gen, skipSelfDecl)) { if (t.isAnonymous()) { gen.out(gen.getNames().objectName(t)); } else { gen.out(gen.getNames().name(t)); } } if (_init && !(t.isAnonymous() && t.isToplevel())) { gen.out("()"); } } } static String qualifiedTypeContainer(final Node node, final boolean imported, final TypeDeclaration t, final GenerateJsVisitor gen) { final String modAlias = imported ? gen.getNames().moduleAlias(t.getUnit().getPackage().getModule()) : null; final StringBuilder sb = new StringBuilder(); if (modAlias != null && !modAlias.isEmpty()) { sb.append(modAlias).append('.'); } if (t.getContainer() instanceof ClassOrInterface) { final Scope scope = node == null ? null : Util.getContainingClassOrInterface(node.getScope()); ClassOrInterface parent = (ClassOrInterface)t.getContainer(); final List<ClassOrInterface> parents = new ArrayList<>(3); parents.add(0, parent); while (parent != scope && parent.getContainer() instanceof ClassOrInterface) { parent = (ClassOrInterface)parent.getContainer(); parents.add(0, parent); } for (ClassOrInterface p : parents) { if (p==scope) { if (gen.opts.isOptimize()) { sb.append(gen.getNames().self(p)).append('.'); } } else { sb.append(gen.getNames().name(p)); if (gen.opts.isOptimize()) { sb.append(".$$.prototype"); } sb.append('.'); } } } return sb.toString(); } /** Prints out an object with a type constructor under the property "t" and its type arguments under * the property "a", or a union/intersection type with "u" or "i" under property "t" and the list * of types that compose it in an array under the property "l", or a type parameter as a reference to * already existing params. */ static void typeNameOrList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration type = pt.getDeclaration(); if (!outputTypeList(node, pt, gen, skipSelfDecl)) { if (type instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)type, gen, skipSelfDecl); } else if (type instanceof TypeAlias) { outputQualifiedTypename(node, node != null && gen.isImported(node.getUnit().getPackage(), type), pt, gen, skipSelfDecl); } else { gen.out("{t:"); outputQualifiedTypename(node, node != null && gen.isImported(node.getUnit().getPackage(), type), pt, gen, skipSelfDecl); if (!pt.getTypeArgumentList().isEmpty()) { final Map<TypeParameter,ProducedType> targs; if (pt.getDeclaration().isToplevel()) { targs = pt.getTypeArguments(); } else { //Gather all type parameters from containers Scope scope = node.getScope(); final HashSet<TypeParameter> parenttp = new HashSet<>(); while (scope != null) { if (scope instanceof Generic) { for (TypeParameter tp : ((Generic)scope).getTypeParameters()) { parenttp.add(tp); } } scope = scope.getScope(); } targs = new HashMap<>(); targs.putAll(pt.getTypeArguments()); Declaration cd = Util.getContainingDeclaration(pt.getDeclaration()); while (cd != null) { if (cd instanceof Generic) { for (TypeParameter tp : ((Generic)cd).getTypeParameters()) { if (parenttp.contains(tp)) { targs.put(tp, tp.getType()); } } } cd = Util.getContainingDeclaration(cd); } } gen.out(",a:"); printTypeArguments(node, targs, gen, skipSelfDecl, pt.getVarianceOverrides()); } gen.out("}"); } } } /** Appends an object with the type's type and list of union/intersection types. */ static boolean outputTypeList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration d = pt.getDeclaration(); final List<ProducedType> subs; int seq=0; if (d instanceof IntersectionType) { gen.out("{t:'i"); subs = d.getSatisfiedTypes(); } else if (d instanceof UnionType) { gen.out("{t:'u"); subs = d.getCaseTypes(); } else if ("ceylon.language::Tuple".equals(d.getQualifiedNameString())) { subs = d.getUnit().getTupleElementTypes(pt); final ProducedType lastType = subs.get(subs.size()-1); if (lastType.isUnknown() || lastType.getDeclaration() instanceof TypeParameter) { //Revert to outputting normal Tuple with its type arguments gen.out("{t:", gen.getClAlias(), "Tuple,a:"); printTypeArguments(node, pt.getTypeArguments(), gen, skipSelfDecl, pt.getVarianceOverrides()); gen.out("}"); return true; } if (!d.getUnit().getEmptyDeclaration().equals(lastType.getDeclaration())) { if (d.getUnit().getSequentialDeclaration().equals(lastType.getDeclaration())) { seq = 1; } if (d.getUnit().getSequenceDeclaration().equals(lastType.getDeclaration())) { seq = 2; } } if (seq > 0) { //Non-empty, non-tuple tail; union it with its type parameter UnionType utail = new UnionType(d.getUnit()); utail.setCaseTypes(Arrays.asList(lastType.getTypeArgumentList().get(0), lastType)); subs.remove(subs.size()-1); subs.add(utail.getType()); } gen.out("{t:'T"); } else { return false; } gen.out("',l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); if (t==subs.get(subs.size()-1) && seq>0) { //The non-empty, non-tuple tail gen.out("{t:'u',l:["); typeNameOrList(node, t.getCaseTypes().get(0), gen, skipSelfDecl); gen.out(","); typeNameOrList(node, t.getCaseTypes().get(1), gen, skipSelfDecl); gen.out("],seq:", Integer.toString(seq), "}"); } else { typeNameOrList(node, t, gen, skipSelfDecl); } first = false; } gen.out("]}"); return true; } /** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */ static void resolveTypeParameter(final Node node, final TypeParameter tp, final GenerateJsVisitor gen, final boolean skipSelfDecl) { Scope parent = Util.getRealScope(node.getScope()); int outers = 0; while (parent != null && parent != tp.getContainer()) { if (parent instanceof TypeDeclaration && !(parent instanceof Constructor || ((TypeDeclaration) parent).isAnonymous())) { outers++; } parent = parent.getScope(); } if (tp.getContainer() instanceof ClassOrInterface) { if (parent == tp.getContainer()) { if (!skipSelfDecl) { TypeDeclaration ontoy = Util.getContainingClassOrInterface(node.getScope()); while (ontoy.isAnonymous())ontoy=Util.getContainingClassOrInterface(ontoy.getScope()); gen.out(gen.getNames().self(ontoy)); for (int i = 0; i < outers; i++) { gen.out(".outer$"); } gen.out("."); } gen.out("$$targs$$.", tp.getName(), "$", tp.getDeclaration().getName()); } else { //This can happen in expressions such as Singleton(n) when n is dynamic gen.out("{/*NO PARENT*/t:", gen.getClAlias(), "Anything}"); } } else if (tp.getContainer() instanceof TypeAlias) { if (parent == tp.getContainer()) { gen.out("'", tp.getName(), "$", tp.getDeclaration().getName(), "'"); } else { //This can happen in expressions such as Singleton(n) when n is dynamic gen.out("{/*NO PARENT ALIAS*/t:", gen.getClAlias(), "Anything}"); } } else { //it has to be a method, right? //We need to find the index of the parameter where the argument occurs //...and it could be null... int plistCount = -1; ProducedType type = null; for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator(); type == null && iter0.hasNext();) { plistCount++; for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator(); type == null && iter1.hasNext();) { if (type == null) { type = typeContainsTypeParameter(iter1.next().getType(), tp); } } } //The ProducedType that we find corresponds to a parameter, whose type can be: //A type parameter in the method, in which case we just use the argument's type (may be null) //A component of a union/intersection type, in which case we just use the argument's type (may be null) //A type argument of the argument's type, in which case we must get the reified generic from the argument if (tp.getContainer() == parent) { gen.out("$$$mptypes.", tp.getName(), "$", tp.getDeclaration().getName()); } else { if (parent == null && node instanceof Tree.StaticMemberOrTypeExpression) { if (tp.getContainer() == ((Tree.StaticMemberOrTypeExpression)node).getDeclaration()) { type = ((Tree.StaticMemberOrTypeExpression)node).getTarget().getTypeArguments().get(tp); typeNameOrList(node, type, gen, skipSelfDecl); return; } } gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#", tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "' container " + tp.getContainer() + " y yo estoy en " + node); } } } static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) { TypeDeclaration d = td.getDeclaration(); if (d == tp) { return td; } else if (d instanceof UnionType || d instanceof IntersectionType) { List<ProducedType> comps = td.getCaseTypes(); if (comps == null) comps = td.getSupertypes(); for (ProducedType sub : comps) { td = typeContainsTypeParameter(sub, tp); if (td != null) { return td; } } } else if (d instanceof ClassOrInterface) { for (ProducedType sub : td.getTypeArgumentList()) { if (typeContainsTypeParameter(sub, tp) != null) { return td; } } } return null; } /** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */ static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) { if (pt.getDeclaration().equals(d)) { return pt; } List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes(); for (ProducedType t : list) { if (t.getDeclaration().equals(d)) { return t; } } return null; } static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) { if (params != null && targs != null && params.size() == targs.size()) { HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>(); for (int i = 0; i < targs.size(); i++) { r.put(params.get(i), targs.get(i)); } return r; } return null; } static Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) { HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>(); final TypeDeclaration iterable = pt.getDeclaration().getUnit().getIterableDeclaration(); r.put(iterable.getTypeParameters().get(0), pt); r.put(iterable.getTypeParameters().get(1), pt.getDeclaration().getUnit().getNullDeclaration().getType()); return r; } static boolean isUnknown(Declaration d) { return d == null || d.getQualifiedNameString().equals("UnknownType"); } static void spreadArrayCheck(final Tree.Term term, final GenerateJsVisitor gen) { String tmp = gen.getNames().createTempVariable(); gen.out("(", tmp, "="); term.visit(gen); gen.out(",Array.isArray(", tmp, ")?", tmp); gen.out(":function(){throw new TypeError('Expected JS Array (", term.getUnit().getFilename(), " ", term.getLocation(), ")')}())"); } /** Generates the code to throw an Exception if a dynamic object is not of the specified type. */ static void generateDynamicCheck(final Tree.Term term, ProducedType t, final GenerateJsVisitor gen, final boolean skipSelfDecl, final Map<TypeParameter,ProducedType> typeArguments) { if (t.getDeclaration().isDynamic()) { gen.out(gen.getClAlias(), "dre$$("); term.visit(gen); gen.out(","); TypeUtils.typeNameOrList(term, t, gen, skipSelfDecl); gen.out(",'", term.getUnit().getFilename(), " ", term.getLocation(), "')"); } else { final boolean checkFloat = term.getUnit().getFloatDeclaration().equals(t.getDeclaration()); final boolean checkInt = checkFloat ? false : term.getUnit().getIntegerDeclaration().equals(t.getDeclaration()); String tmp = gen.getNames().createTempVariable(); gen.out("(", tmp, "="); term.visit(gen); final String errmsg; if (checkFloat) { gen.out(",typeof(", tmp, ")==='number'?", gen.getClAlias(), "Float(", tmp, ")"); errmsg = "Expected Float"; } else if (checkInt) { gen.out(",typeof(", tmp, ")==='number'?Math.floor(", tmp, ")"); errmsg = "Expected Integer"; } else { gen.out(",", gen.getClAlias(), "is$(", tmp, ","); if (t.getDeclaration() instanceof TypeParameter && typeArguments != null && typeArguments.containsKey(t.getDeclaration())) { t = typeArguments.get(t.getDeclaration()); } TypeUtils.typeNameOrList(term, t, gen, skipSelfDecl); gen.out(")?", tmp); errmsg = "Expected " + t.getProducedTypeQualifiedName(); } gen.out(":function(){throw new TypeError('", errmsg, " (", term.getUnit().getFilename(), " ", term.getLocation(), ")')}())"); } } static void encodeParameterListForRuntime(Node n, ParameterList plist, GenerateJsVisitor gen) { boolean first = true; gen.out("["); for (Parameter p : plist.getParameters()) { if (first) first=false; else gen.out(","); gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',"); gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',"); ProducedType ptype = p.getType(); if (p.getModel() instanceof Method) { gen.out("$pt:'f',"); ptype = ((Method)p.getModel()).getTypedReference().getFullType(); } if (p.isSequenced()) { gen.out("seq:1,"); } if (p.isDefaulted()) { gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,"); } gen.out(MetamodelGenerator.KEY_TYPE, ":"); metamodelTypeNameOrList(n, gen.getCurrentPackage(), ptype, gen); if (p.getModel().getAnnotations() != null && !p.getModel().getAnnotations().isEmpty()) { new ModelAnnotationGenerator(gen, p.getModel(), n).generateAnnotations(); } gen.out("}"); } gen.out("]"); } /** Turns a Tuple type into a parameter list. */ static List<Parameter> convertTupleToParameters(ProducedType _tuple) { ArrayList<Parameter> rval = new ArrayList<>(); int pos = 0; TypeDeclaration tdecl = _tuple.getDeclaration(); final TypeDeclaration empty = tdecl.getUnit().getEmptyDeclaration(); final TypeDeclaration tuple = tdecl.getUnit().getTupleDeclaration(); while (!(empty.equals(tdecl) || tdecl instanceof TypeParameter)) { Parameter _p = null; if (tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null && tdecl.getCaseTypeDeclarations().size()==2 && tdecl.getCaseTypeDeclarations().contains(tuple))) { _p = new Parameter(); _p.setModel(new Value()); if (tuple.equals(tdecl)) { _p.getModel().setType(_tuple.getTypeArgumentList().get(1)); _tuple = _tuple.getTypeArgumentList().get(2); } else { //Handle union types for defaulted parameters for (ProducedType mt : _tuple.getCaseTypes()) { if (tuple.equals(mt.getDeclaration())) { _p.getModel().setType(mt.getTypeArgumentList().get(1)); _tuple = mt.getTypeArgumentList().get(2); break; } } _p.setDefaulted(true); } } else if (tdecl.inherits(tdecl.getUnit().getSequentialDeclaration())) { //Handle Sequence, for nonempty variadic parameters _p = new Parameter(); _p.setModel(new Value()); _p.getModel().setType(_tuple.getTypeArgumentList().get(0)); _p.setSequenced(true); _tuple = empty.getType(); } else { if (pos > 100) { return rval; } } if (_tuple != null) tdecl = _tuple.getDeclaration(); if (_p != null) { _p.setName("arg" + pos); rval.add(_p); } pos++; } return rval; } /** This method encodes the type parameters of a Tuple in the same way * as a parameter list for runtime. */ private static void encodeTupleAsParameterListForRuntime(final Node node, ProducedType _tuple, boolean nameAndMetatype, GenerateJsVisitor gen) { gen.out("["); int pos = 1; TypeDeclaration tdecl = _tuple.getDeclaration(); final TypeDeclaration empty = tdecl.getUnit().getEmptyDeclaration(); final TypeDeclaration tuple = tdecl.getUnit().getTupleDeclaration(); while (!(empty.equals(tdecl) || tdecl instanceof TypeParameter)) { if (pos > 1) gen.out(","); gen.out("{"); pos++; if (nameAndMetatype) { gen.out(MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos), "',"); gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',"); } gen.out(MetamodelGenerator.KEY_TYPE, ":"); if (tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null && tdecl.getCaseTypeDeclarations().size()==2 && tdecl.getCaseTypeDeclarations().contains(tuple))) { if (tuple.equals(tdecl)) { metamodelTypeNameOrList(node, gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen); _tuple = _tuple.getTypeArgumentList().get(2); } else { //Handle union types for defaulted parameters for (ProducedType mt : _tuple.getCaseTypes()) { if (tuple.equals(mt.getDeclaration())) { metamodelTypeNameOrList(node, gen.getCurrentPackage(), mt.getTypeArgumentList().get(1), gen); _tuple = mt.getTypeArgumentList().get(2); break; } } gen.out(",", MetamodelGenerator.KEY_DEFAULT,":1"); } } else if (tdecl.inherits(tdecl.getUnit().getSequentialDeclaration())) { ProducedType _t2 = _tuple.getSupertype(tdecl.getUnit().getSequentialDeclaration()); //Handle Sequence, for nonempty variadic parameters metamodelTypeNameOrList(node, gen.getCurrentPackage(), _t2.getTypeArgumentList().get(0), gen); gen.out(",seq:1"); _tuple = empty.getType(); } else if (tdecl instanceof UnionType) { metamodelTypeNameOrList(node, gen.getCurrentPackage(), _tuple, gen); tdecl = empty; _tuple=null; } else { gen.out("\n/*WARNING3! Tuple is actually ", _tuple.getProducedTypeQualifiedName(), ", ", tdecl.getName(),"*/"); if (pos > 100) { break; } } gen.out("}"); if (_tuple != null) tdecl = _tuple.getDeclaration(); } gen.out("]"); } /** This method encodes the Arguments type argument of a Callable the same way * as a parameter list for runtime. */ static void encodeCallableArgumentsAsParameterListForRuntime(final Node node, ProducedType _callable, GenerateJsVisitor gen) { if (_callable.getCaseTypes() != null) { for (ProducedType pt : _callable.getCaseTypes()) { if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) { _callable = pt; break; } } } else if (_callable.getSatisfiedTypes() != null) { for (ProducedType pt : _callable.getSatisfiedTypes()) { if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) { _callable = pt; break; } } } if (!_callable.getProducedTypeQualifiedName().contains("ceylon.language::Callable<")) { gen.out("[/*WARNING1: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]"); return; } List<ProducedType> targs = _callable.getTypeArgumentList(); if (targs == null || targs.size() != 2) { gen.out("[/*WARNING2: missing argument types for Callable*/]"); return; } encodeTupleAsParameterListForRuntime(node, targs.get(1), true, gen); } static void encodeForRuntime(Node that, final Declaration d, final GenerateJsVisitor gen) { if (d.getAnnotations() == null || d.getAnnotations().isEmpty() || (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAnonymous())) { encodeForRuntime(that, d, gen, null); } else { encodeForRuntime(that, d, gen, new ModelAnnotationGenerator(gen, d, that)); } } /** Output a metamodel map for runtime use. */ static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) { encodeForRuntime(annotations, d, gen, new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { outputAnnotationsFunction(annotations, d, gen); } }); } /** Returns the list of keys to get from the package to the declaration, in the model. */ public static List<String> generateModelPath(final Declaration d) { final ArrayList<String> sb = new ArrayList<>(); final String pkgName = d.getUnit().getPackage().getNameAsString(); sb.add(Module.LANGUAGE_MODULE_NAME.equals(pkgName)?"$":pkgName); if (d.isToplevel()) { sb.add(d.getName()); if (d instanceof Setter) { sb.add("$set"); } } else { Declaration p = d; final int i = sb.size(); while (p instanceof Declaration) { if (p instanceof Setter) { sb.add(i, "$set"); } sb.add(i, TypeUtils.modelName(p)); //Build the path in reverse if (!p.isToplevel()) { if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { sb.add(i, p.isAnonymous() ? MetamodelGenerator.KEY_OBJECTS : MetamodelGenerator.KEY_CLASSES); } else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { sb.add(i, MetamodelGenerator.KEY_INTERFACES); } else if (p instanceof Method) { sb.add(i, MetamodelGenerator.KEY_METHODS); } else if (p instanceof TypeAlias || p instanceof Setter) { sb.add(i, MetamodelGenerator.KEY_ATTRIBUTES); } else if (p instanceof Constructor) { sb.add(i, MetamodelGenerator.KEY_CONSTRUCTORS); } else { //It's a value TypeDeclaration td=((TypedDeclaration)p).getTypeDeclaration(); sb.add(i, (td!=null&&td.isAnonymous())? MetamodelGenerator.KEY_OBJECTS : MetamodelGenerator.KEY_ATTRIBUTES); } } p = Util.getContainingDeclaration(p); } } return sb; } static void outputModelPath(final Declaration d, GenerateJsVisitor gen) { List<String> parts = generateModelPath(d); gen.out("["); boolean first = true; for (String p : parts) { if (p.startsWith("anon$") || p.startsWith("anonymous#"))continue; if (first)first=false;else gen.out(","); gen.out("'", p, "'"); } gen.out("]"); } static void encodeForRuntime(final Node that, final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) { gen.out("function(){return{mod:$CCMM$"); List<TypeParameter> tparms = d instanceof Generic ? ((Generic)d).getTypeParameters() : null; List<ProducedType> satisfies = null; List<ProducedType> caseTypes = null; if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { com.redhat.ceylon.compiler.typechecker.model.Class _cd = (com.redhat.ceylon.compiler.typechecker.model.Class)d; if (_cd.getExtendedType() != null) { gen.out(",'super':"); metamodelTypeNameOrList(that, d.getUnit().getPackage(), _cd.getExtendedType(), gen); } //Parameter types if (_cd.getParameterList()!=null) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); encodeParameterListForRuntime(that, _cd.getParameterList(), gen); } satisfies = _cd.getSatisfiedTypes(); caseTypes = _cd.getCaseTypes(); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes(); caseTypes = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getCaseTypes(); } else if (d instanceof MethodOrValue) { gen.out(",", MetamodelGenerator.KEY_TYPE, ":"); //This needs a new setting to resolve types but not type parameters metamodelTypeNameOrList(that, d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen); if (d instanceof Method) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); //Parameter types of the first parameter list encodeParameterListForRuntime(that, ((Method)d).getParameterLists().get(0), gen); tparms = ((Method) d).getTypeParameters(); } } else if (d instanceof Constructor) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); encodeParameterListForRuntime(that, ((Constructor)d).getParameterLists().get(0), gen); } if (!d.isToplevel()) { //Find the first container that is a Declaration Declaration _cont = Util.getContainingDeclaration(d); gen.out(",$cont:"); boolean generateName = true; if (_cont.getName() != null && _cont.getName().startsWith("anonymous //Anon functions don't have metamodel so go up until we find a non-anon container Declaration _supercont = Util.getContainingDeclaration(_cont); while (_supercont != null && _supercont.getName() != null && _supercont.getName().startsWith("anonymous _supercont = Util.getContainingDeclaration(_supercont); } if (_supercont == null) { //If the container is a package, add it because this isn't really toplevel generateName = false; gen.out("0"); } else { _cont = _supercont; } } if (generateName) { if (_cont instanceof Value) { if (gen.defineAsProperty(_cont)) { gen.qualify(that, _cont); } gen.out(gen.getNames().getter(_cont, true)); } else if (_cont instanceof Setter) { gen.out("{setter:"); if (gen.defineAsProperty(_cont)) { gen.qualify(that, _cont); gen.out(gen.getNames().getter(((Setter) _cont).getGetter(), true), ".set"); } else { gen.out(gen.getNames().setter(((Setter) _cont).getGetter())); } gen.out("}"); } else { boolean inProto = gen.opts.isOptimize() && (_cont.getContainer() instanceof TypeDeclaration); final String path = gen.qualifiedPath(that, _cont, inProto); if (path != null && !path.isEmpty()) { gen.out(path, "."); } gen.out(gen.getNames().name(_cont)); } } } if (tparms != null && !tparms.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{"); encodeTypeParametersForRuntime(that, d, tparms, true, gen); gen.out("}"); } if (satisfies != null && !satisfies.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_SATISFIES, ":["); boolean first = true; for (ProducedType st : satisfies) { if (!first)gen.out(","); first=false; metamodelTypeNameOrList(that, d.getUnit().getPackage(), st, gen); } gen.out("]"); } if (caseTypes != null && !caseTypes.isEmpty()) { gen.out(",of:["); boolean first = true; for (ProducedType st : caseTypes) { if (!first)gen.out(","); first=false; if (st.getDeclaration().isAnonymous()) { gen.out(gen.getNames().getter(st.getDeclaration(), true)); } else { metamodelTypeNameOrList(that, d.getUnit().getPackage(), st, gen); } } gen.out("]"); } if (annGen != null) { annGen.generateAnnotations(); } //Path to its model gen.out(",d:"); outputModelPath(d, gen); gen.out("};}"); } static boolean encodeTypeParametersForRuntime(final Node node, final Declaration d, final List<TypeParameter> tparms, boolean first, final GenerateJsVisitor gen) { for(TypeParameter tp : tparms) { boolean comma = false; if (!first)gen.out(","); first=false; gen.out(tp.getName(), "$", tp.getDeclaration().getName(), ":{"); if (tp.isCovariant()) { gen.out(MetamodelGenerator.KEY_DS_VARIANCE, ":'out'"); comma = true; } else if (tp.isContravariant()) { gen.out(MetamodelGenerator.KEY_DS_VARIANCE, ":'in'"); comma = true; } List<ProducedType> typelist = tp.getSatisfiedTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out(MetamodelGenerator.KEY_SATISFIES, ":["); boolean first2 = true; for (ProducedType st : typelist) { if (!first2)gen.out(","); first2=false; metamodelTypeNameOrList(node, d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } typelist = tp.getCaseTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("of:["); boolean first3 = true; for (ProducedType st : typelist) { if (!first3)gen.out(","); first3=false; metamodelTypeNameOrList(node, d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } if (tp.getDefaultTypeArgument() != null) { if (comma)gen.out(","); gen.out("def:"); metamodelTypeNameOrList(node, d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen); } gen.out("}"); } return first; } /** Prints out an object with a type constructor under the property "t" and its type arguments under * the property "a", or a union/intersection type with "u" or "i" under property "t" and the list * of types that compose it in an array under the property "l", or a type parameter as a reference to * already existing params. */ static void metamodelTypeNameOrList(final Node node, final com.redhat.ceylon.compiler.typechecker.model.Package pkg, ProducedType pt, GenerateJsVisitor gen) { if (pt == null) { //In dynamic blocks we sometimes get a null producedType pt = node.getUnit().getAnythingDeclaration().getType(); } if (!outputMetamodelTypeList(node, pkg, pt, gen)) { TypeDeclaration type = pt.getDeclaration(); if (type instanceof TypeParameter) { gen.out("'", type.getNameAsString(), "$", ((TypeParameter)type).getDeclaration().getName(), "'"); } else if (type instanceof TypeAlias) { outputQualifiedTypename(node, gen.isImported(pkg, type), pt, gen, false); } else { gen.out("{t:"); outputQualifiedTypename(node, gen.isImported(pkg, type), pt, gen, false); //Type Parameters if (!pt.getTypeArgumentList().isEmpty()) { gen.out(",a:{"); boolean first = true; for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) { if (first) first=false; else gen.out(","); gen.out(e.getKey().getNameAsString(), "$", e.getKey().getDeclaration().getName(), ":"); metamodelTypeNameOrList(node, pkg, e.getValue(), gen); } gen.out("}"); } gen.out("}"); } } } /** Appends an object with the type's type and list of union/intersection types; works only with union, * intersection and tuple types. * @return true if output was generated, false otherwise (it was a regular type) */ static boolean outputMetamodelTypeList(final Node node, final com.redhat.ceylon.compiler.typechecker.model.Package pkg, ProducedType pt, GenerateJsVisitor gen) { TypeDeclaration type = pt.getDeclaration(); final List<ProducedType> subs; if (type instanceof IntersectionType) { gen.out("{t:'i"); subs = type.getSatisfiedTypes(); } else if (type instanceof UnionType) { //It still could be a Tuple with first optional type List<TypeDeclaration> cts = type.getCaseTypeDeclarations(); if (cts.size()==2 && cts.contains(type.getUnit().getEmptyDeclaration()) && cts.contains(type.getUnit().getTupleDeclaration())) { //yup... gen.out("{t:'T',l:"); encodeTupleAsParameterListForRuntime(node, pt,false,gen); gen.out("}"); return true; } gen.out("{t:'u"); subs = type.getCaseTypes(); } else if (type.getQualifiedNameString().equals("ceylon.language::Tuple")) { gen.out("{t:'T',l:"); encodeTupleAsParameterListForRuntime(node, pt,false, gen); gen.out("}"); return true; } else { return false; } gen.out("',l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); metamodelTypeNameOrList(node, pkg, t, gen); first = false; } gen.out("]}"); return true; } static String pathToModelDoc(final Declaration d) { if (d == null)return null; final StringBuilder sb = new StringBuilder(); for (String p : generateModelPath(d)) { sb.append(sb.length() == 0 ? '\'' : ':').append(p); } sb.append('\''); return sb.toString(); } /** Outputs a function that returns the specified annotations, so that they can be loaded lazily. * @param annotations The annotations to be output. * @param d The declaration to which the annotations belong. * @param gen The generator to use for output. */ static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final Declaration d, final GenerateJsVisitor gen) { List<Tree.Annotation> anns = annotations == null ? null : annotations.getAnnotations(); if (d != null) { int mask = MetamodelGenerator.encodeAnnotations(d, null); if (mask > 0) { gen.out(",", MetamodelGenerator.KEY_PACKED_ANNS, ":", Integer.toString(mask)); } if (annotations == null || (anns.isEmpty() && annotations.getAnonymousAnnotation() == null)) { return; } anns = new ArrayList<>(annotations.getAnnotations().size()); anns.addAll(annotations.getAnnotations()); for (Iterator<Tree.Annotation> iter = anns.iterator(); iter.hasNext();) { final String qn = ((Tree.StaticMemberOrTypeExpression)iter.next().getPrimary()).getDeclaration().getQualifiedNameString(); if (qn.startsWith("ceylon.language::") && MetamodelGenerator.annotationBits.contains(qn.substring(17))) { iter.remove(); } } if (anns.isEmpty() && annotations.getAnonymousAnnotation() == null) { return; } gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":"); } if (annotations == null || (anns.isEmpty() && annotations.getAnonymousAnnotation()==null)) { gen.out("[]"); } else { gen.out("function(){return["); boolean first = true; //Leave the annotation but remove the doc from runtime for brevity if (annotations.getAnonymousAnnotation() != null) { first = false; final Tree.StringLiteral lit = annotations.getAnonymousAnnotation().getStringLiteral(); final String ptmd = pathToModelDoc(d); if (ptmd != null && ptmd.length() < lit.getText().length()) { gen.out(gen.getClAlias(), "doc$($CCMM$,", ptmd); } else { gen.out(gen.getClAlias(), "doc("); lit.visit(gen); } gen.out(")"); } for (Tree.Annotation a : anns) { if (first) first=false; else gen.out(","); gen.getInvoker().generateInvocation(a); } gen.out("];}"); } } /** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */ static interface RuntimeMetamodelAnnotationGenerator { public void generateAnnotations(); } static class ModelAnnotationGenerator implements RuntimeMetamodelAnnotationGenerator { private final GenerateJsVisitor gen; private final Declaration d; private final Node node; ModelAnnotationGenerator(GenerateJsVisitor generator, Declaration decl, Node n) { gen = generator; d = decl; node = n; } @Override public void generateAnnotations() { List<Annotation> anns = d.getAnnotations(); final int bits = MetamodelGenerator.encodeAnnotations(d, null); if (bits > 0) { gen.out(",", MetamodelGenerator.KEY_PACKED_ANNS, ":", Integer.toString(bits)); //Remove these annotations from the list anns = new ArrayList<Annotation>(d.getAnnotations().size()); anns.addAll(d.getAnnotations()); for (Iterator<Annotation> iter = anns.iterator(); iter.hasNext();) { final Annotation a = iter.next(); final Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false); final String qn = ad.getQualifiedNameString(); if (qn.startsWith("ceylon.language::") && MetamodelGenerator.annotationBits.contains(qn.substring(17))) { iter.remove(); } } if (anns.isEmpty()) { return; } } gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return["); boolean first = true; for (Annotation a : anns) { Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false); if (ad instanceof Method) { if (first) first=false; else gen.out(","); final boolean isDoc = "ceylon.language::doc".equals(ad.getQualifiedNameString()); if (!isDoc) { gen.qualify(node, ad); gen.out(gen.getNames().name(ad), "("); } if (a.getPositionalArguments() == null) { for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) { String v = a.getNamedArguments().get(p.getName()); gen.out(v == null ? "undefined" : v); } } else { if (isDoc) { //Use ref if it's too long final String ref = pathToModelDoc(d); final String doc = a.getPositionalArguments().get(0); if (ref != null && ref.length() < doc.length()) { gen.out(gen.getClAlias(), "doc$($CCMM$,", ref); } else { gen.out(gen.getClAlias(), "doc(\"", gen.escapeStringLiteral(doc), "\""); } } else { boolean farg = true; for (String s : a.getPositionalArguments()) { if (farg)farg=false; else gen.out(","); gen.out("\"", gen.escapeStringLiteral(s), "\""); } } } gen.out(")"); } else { gen.out("/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/"); } } gen.out("];}"); } } /** Generates the right type arguments for operators that are sugar for method calls. * @param left The left term of the operator * @param right The right term of the operator * @param methodName The name of the method that is to be invoked * @param rightTpName The name of the type argument on the right term * @param leftTpName The name of the type parameter on the method * @return A map with the type parameter of the method as key * and the produced type belonging to the type argument of the term on the right. */ static Map<TypeParameter, ProducedType> mapTypeArgument(final Tree.BinaryOperatorExpression expr, final String methodName, final String rightTpName, final String leftTpName) { Method md = (Method)expr.getLeftTerm().getTypeModel().getDeclaration().getMember(methodName, null, false); if (md == null) { expr.addUnexpectedError("Left term of intersection operator should have method named " + methodName); return null; } Map<TypeParameter, ProducedType> targs = expr.getRightTerm().getTypeModel().getTypeArguments(); ProducedType otherType = null; for (TypeParameter tp : targs.keySet()) { if (tp.getName().equals(rightTpName)) { otherType = targs.get(tp); break; } } if (otherType == null) { expr.addUnexpectedError("Right term of intersection operator should have type parameter named " + rightTpName); return null; } targs = new HashMap<>(); TypeParameter mtp = null; for (TypeParameter tp : md.getTypeParameters()) { if (tp.getName().equals(leftTpName)) { mtp = tp; break; } } if (mtp == null) { expr.addUnexpectedError("Left term of intersection should have type parameter named " + leftTpName); } targs.put(mtp, otherType); return targs; } /** Returns the qualified name of a declaration, skipping any containing methods. */ public static String qualifiedNameSkippingMethods(Declaration d) { final StringBuilder p = new StringBuilder(d.getName()); Scope s = d.getContainer(); while (s != null) { if (s instanceof com.redhat.ceylon.compiler.typechecker.model.Package) { final String pkname = ((com.redhat.ceylon.compiler.typechecker.model.Package)s).getNameAsString(); if (!pkname.isEmpty()) { p.insert(0, "::"); p.insert(0, pkname); } } else if (s instanceof TypeDeclaration) { p.insert(0, '.'); p.insert(0, ((TypeDeclaration)s).getName()); } s = s.getContainer(); } return p.toString(); } public static String modelName(Declaration d) { String dname = d.getName(); if (dname == null && d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { dname = ((com.redhat.ceylon.compiler.typechecker.model.Class)d.getContainer()).getName(); } if (dname.startsWith("anonymous dname = "anon$" + dname.substring(10); } if (d.isToplevel() || d.isShared()) { return dname; } if (d instanceof Setter) { d = ((Setter)d).getGetter(); } return dname+"$"+Long.toString(Math.abs((long)d.hashCode()), 36); } }
package com.rox.emu.p6502.dbg.ui; import com.rox.emu.Memory; import com.rox.emu.p6502.CPU; import com.rox.emu.p6502.Registers; import com.rox.emu.SimpleMemory; import javax.swing.*; import java.awt.*; import static com.rox.emu.p6502.InstructionSet.*; import static com.rox.emu.p6502.InstructionSet.OP_BNE; import static com.rox.emu.p6502.InstructionSet.OP_CPX_I; /** * A DebuggerWindow for debugging 6502 CPU code * * @author Ross Drew */ public class DebuggerWindow extends JFrame{ private CPU processor; private Memory memory; private final RegistersPanel registersPanel = new RegistersPanel(); private final MemoryPanel memoryPanel = new MemoryPanel(); private String instructionName = "..."; private final JLabel instruction = new JLabel(instructionName); private final DefaultListModel<String> listModel; public DebuggerWindow() { super("6502 Debugger"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(1000, 500); listModel = new DefaultListModel<>(); setLayout(new BorderLayout()); instruction.setHorizontalAlignment(JLabel.CENTER); add(instruction, BorderLayout.NORTH); add(getInstructionScroller(), BorderLayout.EAST); add(getControlPanel(), BorderLayout.SOUTH); add(memoryPanel, BorderLayout.WEST); add(registersPanel, BorderLayout.CENTER); loadProgram(getProgram()); setVisible(true); } private JScrollPane getInstructionScroller(){ JList<String> instructionList = new JList<>(listModel); JScrollPane instructionScroller = new JScrollPane(instructionList); return instructionScroller; } private JPanel getControlPanel() { JButton stepButton = new JButton("Step >>"); stepButton.addActionListener(e -> step()); JButton resetButton = new JButton("Reset!"); resetButton.addActionListener(e -> reset()); JPanel controls = new JPanel(); controls.setLayout(new FlowLayout()); controls.add(resetButton); controls.add(stepButton); return controls; } private int[] getProgram(){ int data_offset = 0x32; int MPD = data_offset + 0x10; int MPR = data_offset + 0x11; int TMP = data_offset + 0x20; int RESAD_0 = data_offset + 0x30; int RESAD_1 = data_offset + 0x31; int valMPD = 7; int valMPR = 4; int[] countToTenProgram = new int[] { OP_LDX_I, 10, OP_LDA_I, 0, OP_CLC, OP_ADC_I, 0x01, OP_DEX, OP_CPX_I, 0, OP_BNE, 0b11110111 }; int[] program = new int[]{ OP_LDA_I, valMPD, OP_STA_Z, MPD, OP_LDA_I, valMPR, OP_STA_Z, MPR, OP_LDA_I, 0, OP_STA_Z, TMP, //Clear OP_STA_Z, RESAD_0, OP_STA_Z, RESAD_1, OP_LDX_I, 8, //X counts each bit //:MULT(18) OP_LSR_Z, MPR, //LSR(MPR) OP_BCC, 13, //Test carry and jump (forward 13) to NOADD OP_LDA_Z, RESAD_0, //RESAD -> A OP_CLC, //Prepare to add OP_ADC_Z, MPD, //+MPD OP_STA_Z, RESAD_0, //Save result OP_LDA_Z, RESAD_1, //RESAD+1 -> A OP_ADC_Z, TMP, //+TMP OP_STA_Z, RESAD_1, //RESAD+1 <- A //:NOADD(35) OP_ASL_Z, MPD, //ASL(MPD) OP_ROL_Z, TMP, //Save bit from MPD OP_DEX, OP_BNE, 0b11100111 //Test equal and jump (back 24) to MULT}); }; return program; } public void loadProgram(int[] program){ memory = new SimpleMemory(); memory.setMemory(0, program); processor = new CPU(memory); registersPanel.setRegisters(processor.getRegisters()); memoryPanel.setMemory(memory); reset(); } public void reset(){ processor.reset(); listModel.clear(); invalidate(); repaint(); } public void step(){ //Get the next instruction Registers registers = processor.getRegisters(); int pointer = registers.getRegister(Registers.REG_PC_LOW) | (registers.getRegister(Registers.REG_PC_HIGH) << 8); int instr = memory.getByte(pointer); //TODO get arguments instructionName = getOpCodeName(instr); instruction.setText(instructionName); listModel.add(0, instructionName); processor.step(); invalidate(); repaint(); } public static void main(String[] args){ new DebuggerWindow(); } private class MemoryPanel extends JPanel { private Memory memory; private void setMemory(Memory memory){ this.memory = memory; } @Override public void paint(Graphics g) { super.paint(g); //Draw memory g.setColor(Color.BLACK); g.drawRect(20, 20, 40, 40); int[] zeroPage = memory.getBlock(0, 256); for (int i=0; i<zeroPage.length; i++){ String value = Integer.toHexString(zeroPage[i]); g.drawChars(value.toCharArray(), 0, 1, 10, 10 + (i*10)); } } } private class RegistersPanel extends JPanel { private Registers registers; private final int bitSize = 40; private final int byteSize = (bitSize*8); private final int padding = 10; private final int bitFontSize = 40; private final int valueFontSize = 10; @Override public void paint(Graphics g) { super.paint(g); if (registers != null) drawRegisters(g, 20, 20); } private void drawRegisters(Graphics g, int x, int y) { int yLocation = y; int xLocation = x; int rowSize = padding + bitSize; int secondByteColumn = byteSize + xLocation + padding; drawByte(g, secondByteColumn, yLocation, registers.getRegister(Registers.REG_ACCUMULATOR), Registers.getRegisterName(Registers.REG_ACCUMULATOR)); yLocation += rowSize; drawByte(g, secondByteColumn, yLocation, registers.getRegister(Registers.REG_Y_INDEX), Registers.getRegisterName(Registers.REG_Y_INDEX)); yLocation += rowSize; drawByte(g, secondByteColumn, yLocation, registers.getRegister(Registers.REG_X_INDEX), Registers.getRegisterName(Registers.REG_X_INDEX)); //TODO this needs a combined value display yLocation += rowSize; drawByte(g, xLocation, yLocation, registers.getRegister(Registers.REG_PC_HIGH), Registers.getRegisterName(Registers.REG_PC_HIGH)); drawByte(g, secondByteColumn, yLocation, registers.getRegister(Registers.REG_PC_LOW), Registers.getRegisterName(Registers.REG_PC_LOW)); yLocation += rowSize; g.setColor(Color.lightGray); g.fillRect(secondByteColumn + (2 * bitSize), yLocation, bitSize, bitSize); drawFlags(g, secondByteColumn, yLocation, registers.getRegister(Registers.REG_STATUS), "NV BDIZC".toCharArray()); } private void drawFlags(Graphics g, int startX, int startY, int byteValue, char[] values){ char[] bitValues = to8BitString(byteValue).toCharArray(); g.setColor(Color.lightGray); for (int i=0; i<8; i++){ g.setColor((bitValues[i] == '1') ? Color.black : Color.lightGray); drawBit(g, startX + (i*bitSize), startY, values[i]); } g.setColor(Color.BLACK); g.drawRect(startX, startY, byteSize, bitSize); } private void drawByte(Graphics g, int startX, int startY, int byteValue, String name){ char[] bitValues = to8BitString(byteValue).toCharArray(); g.setColor(Color.lightGray); for (int i=0; i<8; i++){ drawBit(g, startX + (i*bitSize), startY, bitValues[i]); } g.setColor(Color.BLACK); g.drawRect(startX, startY, byteSize, bitSize); g.setColor(Color.RED); g.setFont(new Font("Courier New", Font.PLAIN, valueFontSize)); String values = "(" + fromSignedByte(byteValue) + ", 0x" + Integer.toHexString(byteValue) + ")"; g.drawChars(values.toCharArray(), 0, values.length(), (startX+byteSize-bitSize), startY-1); g.setColor(Color.blue); g.drawChars(name.toCharArray(), 0, name.length(), startX, startY); } private void drawBit(Graphics g, int startX, int startY, char val){ g.setFont(new Font("Courier New", Font.PLAIN, bitFontSize)); g.drawRect(startX, startY, bitSize, bitSize); //XXX Don't like these numbers, they're not relative to anything g.drawChars(new char[] {val}, 0, 1, startX+5, startY+35); } public void setRegisters(Registers registers) { this.registers = registers; } private int fromSignedByte(int signedByte){ int signedByteByte = signedByte & 0xFF; if ((signedByteByte & 128) == 128) return -( ( (~signedByteByte) +1) & 0xFF); //Twos compliment compensation else return signedByteByte & 0b01111111; } private String to8BitString(int fakeByte){ String formattedByteString = Integer.toBinaryString(fakeByte); if (formattedByteString.length() < 8){ for (int i=formattedByteString.length(); i<8; i++){ formattedByteString = "0" + formattedByteString; } } return formattedByteString; } } }
package com.rox.emu.processor.mos6502; import com.rox.emu.env.RoxByte; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A representation of the MOS 6502 CPU registers * * @author Ross Drew */ public class Registers { private final Logger LOG = LoggerFactory.getLogger(this.getClass()); /** * A single register for a MOS 6502 containing information on register id and name */ public enum Register { ACCUMULATOR(0), Y_INDEX(1), X_INDEX(2), PROGRAM_COUNTER_HI(3), PROGRAM_COUNTER_LOW(4), STACK_POINTER_LOW(5), STACK_POINTER_HI(6), STATUS_FLAGS(7); private final String description; private final int index; Register(int index){ this.index = index; description = prettifyName(name()); } private static String prettifyName(String originalName){ String name = originalName.replaceAll("_"," ") .toLowerCase() .replace("hi","(High)") .replace("low","(Low)"); name = name.substring(0, 1).toUpperCase() + name.substring(1); int spaceIndex = name.indexOf(' '); if (spaceIndex > 0) name = name.substring(0, spaceIndex) + name.substring(spaceIndex, spaceIndex+2).toUpperCase() + name.substring(spaceIndex+2); return name; } public String getDescription(){ return description; } public int getIndex(){ return this.index; } } /** * A MOS 6502 status flag */ public enum Flag { CARRY(0), ZERO(1), IRQ_DISABLE(2), DECIMAL_MODE(3), BREAK(4), UNUSED(5), OVERFLOW(6), NEGATIVE(7); private final int index; private final int placeValue; private final String description; private static String prettifyName(String originalName){ String name = originalName.replaceAll("_"," ").toLowerCase(); name = name.substring(0, 1).toUpperCase() + name.substring(1); int spaceIndex = name.indexOf(' '); if (spaceIndex > 0) name = name.substring(0, spaceIndex) + name.substring(spaceIndex, spaceIndex+2).toUpperCase() + name.substring(spaceIndex+2); return name; } Flag(int index) { this.index = index; this.placeValue = (1 << index); //TODO this doesn't work description = prettifyName(name()); } public String getDescription() { return description; } public int getIndex() { return index; } } public static void main(String[] args) { for (Flag flag : Flag.values()) { System.out.println(flag.getIndex() + "." + flag.getDescription() + " (" + Integer.toBinaryString(flag.index) + ")"); } } /** Place value of Carry status flag in bit {@value #C} */ public static final int STATUS_FLAG_CARRY = 0x1; /** Place value of Zero status flag in bit {@value #Z} */ public static final int STATUS_FLAG_ZERO = 0x2; /** Place value of Interrupt status flag in bit {@value #I} */ public static final int STATUS_FLAG_IRQ_DISABLE = 0x4; /** Place value of Binary Coded Decimal status flag in bit {@value #D} */ public static final int STATUS_FLAG_DEC = 0x8; /** Place value of Break status flag in bit {@value #B} */ public static final int STATUS_FLAG_BREAK = 0x10; private static final int STATUS_FLAG_UNUSED = 0x20; //Placeholder only /** Place value of Overflow status flag in bit {@value #V} */ public static final int STATUS_FLAG_OVERFLOW = 0x40; /** Place value of Negative status flag in bit {@value #N} */ public static final int STATUS_FLAG_NEGATIVE = 0x80; /** Bit place of Negative status flag */ public static final int N = 7; /** Bit place of Overflow status flag */ public static final int V = 6; /** - <em>UNUSED</em> (Placeholder flag only) **/ private static final int U = 5; //Placeholder only /** Bit place of Break status flag */ public static final int B = 4; /** Bit place of Binary Coded Decimal status flag */ public static final int D = 3; /** Bit place of Interrupt status flag */ public static final int I = 2; /** Bit place of Zero status flag */ public static final int Z = 1; /** Bit place ofCarry status flag */ public static final int C = 0; private static final String[] flagNames = new String[] {"Carry", "Zero", "IRQ Disable", "Decimal Mode", "BRK Command", "<UNUSED>", "Overflow", "Negative"}; private final RoxByte[] register; public Registers(){ register = new RoxByte[8]; for (int i=0; i<8; i++) register[i] = RoxByte.ZERO; register[Register.STACK_POINTER_LOW.index] = RoxByte.fromLiteral(0b11111111); register[Register.STATUS_FLAGS.index] = RoxByte.fromLiteral(0b00000000); } /** * @param reg of the register to set * @param val to set the register to */ public void setRegister(Register reg, int val){ LOG.debug("'R:" + reg.getDescription() + "' := " + val); register[reg.index] = RoxByte.fromLiteral(val); } /** * @param reg for which to get the value * @return the value of the desired register */ public int getRegister(Register reg){ return register[reg.index].getRawValue(); } /** * Set the given register to the given value and set the flags register based on that value * * @param reg of the register to set * @param value to set the register to */ public void setRegisterAndFlags(Register reg, int value){ int valueByte = value & 0xFF; setRegister(reg, valueByte); setFlagsBasedOn(valueByte); } /** * @param newPCWord to set the Program Counter to */ public void setPC(int newPCWord){ setRegister(Register.PROGRAM_COUNTER_HI, newPCWord >> 8); setRegister(Register.PROGRAM_COUNTER_LOW, newPCWord & 0xFF); LOG.debug("'R+:Program Counter' := " + newPCWord + " [ " + getRegister(Register.PROGRAM_COUNTER_HI) + " | " + getRegister(Register.PROGRAM_COUNTER_LOW) + " ]"); } /** * @return the two byte value of the Program Counter */ public int getPC(){ return (getRegister(Register.PROGRAM_COUNTER_HI) << 8) | getRegister(Register.PROGRAM_COUNTER_LOW); } /** * Increment the Program Counter then return it's value * * @return the new value of the Program Counter */ public int getNextProgramCounter(){ setPC(getPC()+1); return getPC(); } /** * @param flagNumber for which to get the name * @return the {@link String} name of the given flag */ public static String getFlagName(int flagNumber){ if (flagNumber < 0 || flagNumber > 7) throw new IllegalArgumentException("Unknown 6502 Flag ID:" + flagNumber); return flagNames[flagNumber]; } /** * @param flagBitNumber flag to test * @return <code>true</code> if the specified flag is set, <code>false</code> otherwise */ public boolean getFlag(int flagBitNumber) { return register[Register.STATUS_FLAGS.index].isBitSet(flagBitNumber); } /** * @param flagBitNumber for which to set the state * @param state to set the flag to */ public void setFlagTo(int flagBitNumber, boolean state) { if (state) setFlag(flagBitNumber); else clearFlag(flagBitNumber); } /** * @param flagBitNumber for which to set to true */ public void setFlag(int flagBitNumber) { LOG.debug("'F:" + getFlagName(flagBitNumber) +"' -> SET"); register[Register.STATUS_FLAGS.index] = register[Register.STATUS_FLAGS.index].withBit(flagBitNumber); } /** * Bitwise clear flag by OR-ing the int carrying flags to be cleared * then AND-ing with status flag register. * * Clear bit 1 (place value 2) * 0000 0010 * NOT > 1111 1101 * AND(R) > .... ..0. * * @param flagBitNumber int with bits to clear, turned on */ public void clearFlag(int flagBitNumber){ LOG.debug("'F:" + getFlagName(flagBitNumber) + "' -> CLEARED"); register[Register.STATUS_FLAGS.index] = register[Register.STATUS_FLAGS.index].withoutBit(flagBitNumber); } /** * @param value to set the register flags based on */ public void setFlagsBasedOn(int value){ int valueByte = value & 0xFF; setZeroFlagFor(valueByte); setNegativeFlagFor(valueByte); } /** * Set zero flag if given argument is 0 */ public void setZeroFlagFor(int value){ if (value == 0) setFlag(Z); else clearFlag(Z); } /** * Set negative flag if given argument is 0 */ public void setNegativeFlagFor(int value){ if (isNegative(value)) setFlag(N); else clearFlag(N); } private boolean isNegative(int fakeByte){ return RoxByte.fromLiteral(fakeByte).isNegative(); // return (fakeByte & STATUS_FLAG_NEGATIVE) == STATUS_FLAG_NEGATIVE; ///What was this about? } }
package com.suse.salt.netapi.calls.modules; import com.google.gson.reflect.TypeToken; import com.suse.salt.netapi.calls.LocalCall; import java.util.Map; import java.util.LinkedHashMap; import java.util.List; import java.util.Arrays; import java.util.Collections; import java.util.Optional; /** * Basic operations on files and directories on minions */ public class File { /** * File module result object */ public static class Result { private boolean result; private String comment; public boolean getResult() { return result; } public String getComment() { return comment; } } private File() { } /** * Chown a file * * @param path Path to the file or directory * @param user User owner * @param group Group owner * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> chown(String path, String user, String group) { Map<String, String> args = new LinkedHashMap<>(); args.put("path", path); args.put("user", user); args.put("group", group); return new LocalCall<>("file.chown", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); } /** * Set the mode of a file * * @param path File or directory of which to set the mode * @param mode Mode to set the path to * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> chmod(String path, String mode) { return new LocalCall<>("file.set_mode", Optional.of(Arrays.asList(path, mode)), Optional.empty(), new TypeToken<String>(){}); } /** * Copy a file or directory from src to dst * * @param src File or directory to copy * @param dst Destination path * @param recurse Recurse flag * @param removeExisting If true, all files in the target directory are removed, * and then the files are copied from the source * @return The {@link LocalCall} object to make the call */ public static LocalCall<Boolean> copy(String src, String dst, boolean recurse, boolean removeExisting) { Map<String, Object> args = new LinkedHashMap<>(); args.put("src", src); args.put("dst", dst); args.put("recurse", recurse); args.put("remove_existing", removeExisting); return new LocalCall<>("file.copy", Optional.empty(), Optional.of(args), new TypeToken<Boolean>(){}); } /** * Move a file or directory from src to dst * * @param src File or directory to copy * @param dst Destination path * @return The {@link LocalCall} object to make the call */ public static LocalCall<Result> move(String src, String dst) { Map<String, Object> args = new LinkedHashMap<>(); args.put("src", src); args.put("dst", dst); return new LocalCall<>("file.move", Optional.empty(), Optional.of(args), new TypeToken<Result>(){}); } /** * Remove a file * * @param path File path to remove * @return The {@link LocalCall} object to make the call */ public static LocalCall<Boolean> remove(String path) { return new LocalCall<>("file.remove", Optional.of(Collections.singletonList(path)), Optional.empty(), new TypeToken<Boolean>(){}); } /** * Get the hash sum of a file * <p> * SHA256 algorithm is used by default * * @param path Path to the file or directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> getHash(String path) { return getHash(path, Optional.empty(), Optional.empty()); } /** * Get the hash sum of a file * * @param path Path to the file or directory * @param form Desired sum format * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> getHash(String path, HashType form) { return getHash(path, Optional.of(form), Optional.empty()); } /** * Get the hash sum of a file * * @param path Path to the file or directory * @param form Desired sum format * @param chunkSize Amount to sum at once * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> getHash(String path, HashType form, long chunkSize) { return getHash(path, Optional.of(form), Optional.of(chunkSize)); } private static LocalCall<String> getHash(String path, Optional<HashType> form, Optional<Long> chunkSize) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); if (form.isPresent()) { args.put("form", form.get().getHashType()); } if (chunkSize.isPresent()) { args.put("chunk_size", chunkSize.get()); } return new LocalCall<>("file.get_hash", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); } /** * Tests to see if path is a valid directory * * @param path Path to directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<Boolean> directoryExists(String path) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); return new LocalCall<>("file.directory_exists", Optional.empty(), Optional.of(args), new TypeToken<Boolean>(){}); } /** * Tests to see if path is a valid file * * @param path Path to file * @return The {@link LocalCall} object to make the call */ public static LocalCall<Boolean> fileExists(String path) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); return new LocalCall<>("file.file_exists", Optional.empty(), Optional.of(args), new TypeToken<Boolean>(){}); } /** * Return the mode of a file * * @param path File or directory of which to get the mode * @param followSymlinks Indicated if symlinks should be followed * @return The {@link LocalCall} * object to make the call */ public static LocalCall<String> getMode(String path, boolean followSymlinks) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); args.put("follow_symlinks", followSymlinks); return new LocalCall<>("file.get_mode", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); } /** * Ensures that a directory is available * * @param path Path to directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> mkdir(String path) { return mkdir(path, Optional.empty(), Optional.empty(), Optional.empty()); } /** * Ensures that a directory is available * * @param path Path to directory * @param mode Mode for the newly created directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> mkdir(String path, String mode) { return mkdir(path, Optional.empty(), Optional.empty(), Optional.of(mode)); } /** * Ensures that a directory is available * * @param path Path to directory * @param user Owner user * @param group Owner group * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> mkdir(String path, String user, String group) { return mkdir(path, Optional.of(user), Optional.of(group), Optional.empty()); } /** * Ensures that a directory is available * * @param path Path to directory * @param user Owner user * @param group Owner group * @param mode Mode for the newly created directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<String> mkdir(String path, String user, String group, String mode) { return mkdir(path, Optional.of(user), Optional.of(group), Optional.of(mode)); } private static LocalCall<String> mkdir(String path, Optional<String> user, Optional<String> group, Optional<String> mode) { Map<String, Object> args = new LinkedHashMap<>(); args.put("dir_path", path); if (user.isPresent()) { args.put("user", user.get()); } if (group.isPresent()) { args.put("group", group.get()); } if (mode.isPresent()) { args.put("mode", mode.get()); } return new LocalCall<>("file.mkdir", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); } /** * Returns a list containing the contents of a directory * * @param path Path to directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<List<String>> readdir(String path) { return new LocalCall<>("file.readdir", Optional.of(Collections.singletonList(path)), Optional.empty(), new TypeToken<List<String>>(){}); } /** * Removes the specified directory * <p> * Fails if the directory is not empty * * @param path Path to directory * @return The {@link LocalCall} object to make the call */ public static LocalCall<Boolean> rmdir(String path) { return new LocalCall<>("file.rmdir", Optional.of(Collections.singletonList(path)), Optional.empty(), new TypeToken<Boolean>(){}); } }
package com.techcavern.wavetact.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.techcavern.wavetact.commandline.perms.PermLevelC; import com.techcavern.wavetact.commandline.utils.AddServer; import com.techcavern.wavetact.commandline.utils.BasicCommands; import com.techcavern.wavetact.commandline.utils.Start; import com.techcavern.wavetact.commands.chanhalfop.*; import com.techcavern.wavetact.commands.chanop.*; import com.techcavern.wavetact.commands.chanowner.AutoOp; import com.techcavern.wavetact.commands.chanowner.CPermLevel; import com.techcavern.wavetact.commands.chanowner.Owner; import com.techcavern.wavetact.commands.chanowner.Protect; import com.techcavern.wavetact.commands.controller.*; import com.techcavern.wavetact.commands.fun.Attack; import com.techcavern.wavetact.commands.fun.SomethingAwesome; import com.techcavern.wavetact.commands.fun.UrbanDictonary; import com.techcavern.wavetact.commands.trusted.*; import com.techcavern.wavetact.commands.utils.*; import com.techcavern.wavetact.commands.utils.Help; import com.techcavern.wavetact.utils.events.DisconnectListener; import com.techcavern.wavetact.utils.events.KickListener; import com.techcavern.wavetact.utils.events.MessageListener; import com.techcavern.wavetact.utils.objects.*; import com.techcavern.wavetact.utils.thread.CheckTime; import org.pircbotx.Configuration; import org.pircbotx.Configuration.Builder; import org.pircbotx.PircBotX; import java.io.File; import java.nio.charset.Charset; import java.util.*; //import com.techcavern.wavetact.Commands.Commands.TestCommand; public class LoadUtils { public static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); public static PircBotX createbot(String nickservPassword, String name, List<String> channels, String nick, String server) { System.out.println("Configuring " + name); Builder<PircBotX> Net = new Configuration.Builder<PircBotX>(); Net.setName(nick); Net.setLogin("WaveTact"); Net.setEncoding(Charset.isSupported("UTF-8") ? Charset.forName("UTF-8") : Charset.defaultCharset()); // TODO: @logangorence Add support for port changes. Also, does PircBotX support SSL? I think so Net.setServer(server, 6667); channels.forEach(Net::addAutoJoinChannel); Net.setRealName(nick); Net.getListenerManager().addListener(new MessageListener()); Net.getListenerManager().addListener(new DisconnectListener()); // TODO: @logangorence Add support for saving configuration to allow for configuration per-network on "modules"... Should we also modularize? Anyways, each network will be able to enable/disable modules and if they are enabled, it will be added to the server file(maybe later on, server folders, which would have a server.info, modules.info, and possibly logs and other stuff). // Hm... the only module I can currently think of is "HighFive" // Net.getListenerManager().addListener(new HighFive()); Net.getListenerManager().addListener(new KickListener()); if (nickservPassword != null) { Net.setNickservPassword(nickservPassword); } return new PircBotX(Net.buildConfiguration()); } public static void registerNetworks() { File serversFolder = new File("servers/"); serversFolder.mkdir(); File[] files = serversFolder.listFiles(); String name; com.techcavern.wavetact.utils.fileUtils.Configuration config; for (File f : files) { if (!f.isDirectory()) { name = f.getName(); name = name.substring(0, f.getName().lastIndexOf('.')); config = new com.techcavern.wavetact.utils.fileUtils.Configuration(f); GeneralRegistry.configs.put(name, config); } } PircBotX bot; LinkedList<String> chans = new LinkedList<String>(); String nsPass; for (com.techcavern.wavetact.utils.fileUtils.Configuration c : GeneralRegistry.configs.values()) { chans.clear(); Collections.addAll(chans, c.getString("channels").split(", ")); if (c.getString("nickserv").equalsIgnoreCase("False")) { nsPass = null; } else { nsPass = c.getString("nickserv"); } bot = LoadUtils.createbot(nsPass, c.getString("name"), chans, c.getString("nick"), c.getString("server")); GeneralRegistry.WaveTact.addBot(bot); new CommandChar(c.getString("prefix"), bot); } } public static void registerDevServer() { List<String> Chans = Arrays.asList("#techcavern"); PircBotX Dev = LoadUtils.createbot(null, "EsperNet", Chans, "WaveTactDev", "irc.esper.net"); GeneralRegistry.WaveTact.addBot(Dev); new CommandChar("@", Dev); } public static void startThreads() { (new Thread(new CheckTime())).start(); } public static void registerCommands() { /** try{ GeneralRegistry.COMMANDS.addAll(GeneralRegistry.TASKS.submit(new CommandCollection("com.techcavern.wavetact.commands")).get()); } catch(Exception ex){ ex.printStackTrace(System.err); } **/ GeneralRegistry.Commands.add(new Ban()); GeneralRegistry.Commands.add(new HalfOp()); GeneralRegistry.Commands.add(new Kick()); GeneralRegistry.Commands.add(new Mode()); GeneralRegistry.Commands.add(new Owner()); GeneralRegistry.Commands.add(new Protect()); GeneralRegistry.Commands.add(new Quiet()); GeneralRegistry.Commands.add(new Voice()); GeneralRegistry.Commands.add(new Op()); GeneralRegistry.Commands.add(new IRCRaw()); GeneralRegistry.Commands.add(new Join()); GeneralRegistry.Commands.add(new Lock()); GeneralRegistry.Commands.add(new Shutdown()); GeneralRegistry.Commands.add(new SomethingAwesome()); GeneralRegistry.Commands.add(new UrbanDictonary()); GeneralRegistry.Commands.add(new Act()); GeneralRegistry.Commands.add(new CustomCMD()); GeneralRegistry.Commands.add(new Part()); GeneralRegistry.Commands.add(new Say()); GeneralRegistry.Commands.add(new WolframAlpha()); GeneralRegistry.Commands.add(new CheckUserLevel()); GeneralRegistry.Commands.add(new Commands()); GeneralRegistry.Commands.add(new Define()); GeneralRegistry.Commands.add(new FindIP()); GeneralRegistry.Commands.add(new Help()); GeneralRegistry.Commands.add(new Hostmask()); GeneralRegistry.Commands.add(new MathC()); GeneralRegistry.Commands.add(new PingTime()); GeneralRegistry.Commands.add(new Question()); GeneralRegistry.Commands.add(new Weather()); GeneralRegistry.Commands.add(new Topic()); GeneralRegistry.Commands.add(new Attack()); GeneralRegistry.Commands.add(new DefCon()); GeneralRegistry.Commands.add(new CPermLevel()); GeneralRegistry.Commands.add(new AutoOp()); } public static void initializeCommandlines() { //TODO Fix this to work with @CMDLine once @CMD is fixed GeneralRegistry.CommandLines.add(new AddServer()); GeneralRegistry.CommandLines.add(new com.techcavern.wavetact.commandline.Help()); GeneralRegistry.CommandLines.add(new BasicCommands()); GeneralRegistry.CommandLines.add(new Start()); GeneralRegistry.CommandLines.add(new PermLevelC()); } public static void parseCommandLineArguments(String[] args) { boolean exit = false; boolean invalid = true; if (args.length < 1) { com.techcavern.wavetact.commandline.Help c = new com.techcavern.wavetact.commandline.Help(); c.doAction(args); } for (CommandLine c : GeneralRegistry.CommandLineArguments) { for (String b : c.getArgument()) { for (String s : args) { if (s.equalsIgnoreCase("-" + b)) { c.doAction(args); invalid = false; } } } } for (CommandLine c : GeneralRegistry.CommandLines) { for (String b : c.getArgument()) { if (args[0].equalsIgnoreCase("-" + b)) { c.doAction(args); invalid = false; } } } if (invalid) System.exit(0); } }
package com.telekom.m2m.cot.restsdk.util; import com.telekom.m2m.cot.restsdk.devicecontrol.OperationStatus; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; /** * Filter to build as criteria for collection queries. * * @author Patrick Steinert * @since 0.2.0 */ public class Filter { private Filter() { } /** * Use to create a FilterBuilder. * * @return FilterBuilder. */ @Nonnull public static FilterBuilder build() { return new FilterBuilder(); } /** * Filter Builder for build collection queries. * <p><b>Usage:</b></p> * <pre> * {@code * measurementApi.getMeasurements( * Filter.build() * .byFragmentType("com_telekom_example_SampleTemperatureSensor") * .bySource("1122334455") * ); * } * </pre> */ public static class FilterBuilder { @Nonnull private final HashMap<FilterBy, String> filters = new HashMap<>(); /** * Creates a parameter string. * * @return a string in pattern <code>arg1=val1&amp;arg2=val2</code> */ @Nonnull public String buildFilter() { return filters.entrySet().stream() .map(filter -> filter.getKey().getFilterKey() + "=" + filter.getValue()) .collect(Collectors.joining("&")); } /** * Adds a build for source id. * * @param id ID of the source ({@link com.telekom.m2m.cot.restsdk.inventory.ManagedObject}) to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder bySource(String id) { filters.put(FilterBy.BYSOURCE, id); return this; } /** * Adds a build for type. * * @param type type to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byType(String type) { filters.put(FilterBy.BYTYPE, type); return this; } /** * Adds a build for a time range. * * @param from start of the date range (more in the history). * @param to end of the date range (more in the future). * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byDate(Date from, Date to) { filters.put(FilterBy.BYDATEFROM, CotUtils.convertDateToTimestring(from)); filters.put(FilterBy.BYDATETO, CotUtils.convertDateToTimestring(to)); return this; } /** * Adds a build for a fragment. * * @param fragmentType to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byFragmentType(String fragmentType) { filters.put(FilterBy.BYFRAGMENTTYPE, fragmentType); return this; } /** * Adds a build for a deviceId. * * @param deviceId to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byDeviceId(String deviceId) { filters.put(FilterBy.BYDEVICEID, deviceId); return this; } /** * Adds a build for a status. * * @param operationStatus to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byStatus(OperationStatus operationStatus) { filters.put(FilterBy.BYSTATUS, operationStatus.toString()); return this; } /** * Adds a build for a text. * * @param text to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byText(String text) { filters.put(FilterBy.BYTEXT, text); return this; } /** * Adds a build for a list of comma separated Ids. * * @param listOfIds to build for (comma separated). * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byListOfIds(String listOfIds) { filters.put(FilterBy.BYLISTOFIDs, listOfIds); return this; } /** * Adds a build for a Alarm status. * * @param status to build for. * @return an appropriate build Object. * @since 0.3.0 */ @Deprecated @Nonnull public FilterBuilder byStatus(String status) { filters.put(FilterBy.BYSTATUS, status); return this; } /** * Adds a build for an agentId. * * @param agentId to build for. * @return an appropriate build Object. * @since 0.3.1 */ @Deprecated @Nonnull public FilterBuilder byAgentId(String agentId) { filters.put(FilterBy.BYAGENTID, agentId); return this; } /** * Adds a build for a user. * * @param user to build for. * @return an appropriate build Object. * @since 0.6.0 */ @Deprecated @Nonnull public FilterBuilder byUser(String user) { filters.put(FilterBy.BYUSER, user); return this; } /** * Adds a build for an application. * * @param application to build for. * @return an appropriate build Object. * @since 0.6.0 */ @Deprecated @Nonnull public FilterBuilder byApplication(String application) { filters.put(FilterBy.BYAPPLICATION, application); return this; } /** * adds a build for a filter * * @param filterBy enum value, which filter should to be added * @param value value for filter, which should be added * @return an appropriate build Object */ @Nonnull public FilterBuilder setFilter(@Nonnull final FilterBy filterBy, @Nonnull final String value) { filters.put(filterBy, value); return this; } /** * adds a build for a map of filters * * @param filtersToAdd contains enum values and values for filter builds * @return an appropriate build Object */ @Nonnull public FilterBuilder setFilters(@Nonnull final Map<FilterBy, String> filtersToAdd){ filters.putAll(filtersToAdd); return this; } /** * validate all set filters allowed by the api * * @param acceptedFilters list of filters, which are allowed. Pass null if all filters are allowed. * @throws CotSdkException If a filter that is not allowed is detected. */ public void validateSupportedFilters(@Nullable final List<FilterBy> acceptedFilters) { // Do nothing, when all filters are accepted. if (acceptedFilters != null) { for (final Map.Entry<FilterBy, String> definedFilter : filters.entrySet()) { if (!acceptedFilters.contains(definedFilter.getKey())) { throw new CotSdkException(String.format("This filter is not available in used api [%s]", definedFilter.getKey())); } } } } } }
package com.totalchange.bunman.jd7; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.totalchange.bunman.Catalogue; import com.totalchange.bunman.CatalogueSongListener; import com.totalchange.bunman.cddb.CddbQuerier; import com.totalchange.bunman.cddb.CddbResult; final class Jd7Catalogue implements Catalogue { private static final String CDDB_DATA_CATEGORY = "data"; private static final String SPLITTER_CDDB = "/"; private static final String SPLITTER_DIRNAME = " "; private static final Logger logger = LoggerFactory .getLogger(Jd7Catalogue.class); private IdnFileAlbumCache cache; private CddbQuerier querier; private File root; public Jd7Catalogue(IdnFileAlbumCache cache, CddbQuerier querier, File root) { this.cache = cache; this.querier = querier; this.root = root; } private void processAlbumData(CatalogueSongListener listener, Album album, boolean ignoreTrackNum, File dir, File... ignored) { FileFinder fileFinder = new FileFinder(dir.listFiles(), ignored); for (int num = 0; num < album.getTracks().size(); num++) { String track = album.getTracks().get(num); File file = fileFinder.findTrackFile(track); if (file != null) { int trackNum = -1; if (!ignoreTrackNum) { trackNum = num + 1; } listener.yetAnotherSong(new Jd7Song(album, trackNum, track, file)); } else { // TODO: Internationalise listener.warn("Couldn't find a file for " + "track '" + track + "' from album '" + album.getAlbum() + "' by artist '" + album.getArtist() + "' in directory " + dir.getAbsolutePath()); } } } private void processIdDir(File dir, File idFile, CatalogueSongListener listener) { try { IdFileAlbum idf = new IdFileAlbum(idFile); processAlbumData(listener, idf, false, dir, idFile); } catch (IOException ioEx) { listener.warn("Couldn''t read ID file " + idFile + ": " + ioEx.getLocalizedMessage()); } } private String readIdValue(File file) throws IOException { logger.trace("Reading id string from file {}", file); BufferedReader in = new BufferedReader(new FileReader(file)); try { String id = in.readLine(); logger.trace("Raw id value is {}", id); if (id != null) { id = id.trim(); } if (id != null && id.length() <= 0) { id = null; } logger.trace("Parsed id value is {}", id); return id; } finally { in.close(); } } private void addItemToQueueAndCacheIt(CatalogueSongListener listener, File file, String id, IdnFileAlbum idnf) { cache.putFileIntoCache(id, file.getParentFile().getName(), idnf); processAlbumData(listener, idnf, false, file.getParentFile(), file); } private boolean equalsIgnoreCase(String[] arr1, String[] arr2) { if (arr1.length != arr2.length) { return false; } for (int num = 0; num < arr1.length; num++) { if (!arr1[num].equalsIgnoreCase(arr2[num])) { return false; } } return true; } private void processQueryResults(CatalogueSongListener listener, File file, String id, List<CddbResult> results) { if (logger.isTraceEnabled()) { logger.trace("Got CDDB results for file " + file + ", id " + id + ": " + results); } if (results.size() <= 0) { logger.trace("No results - need to report as a problem"); // TODO: Internationalise listener.warn("Failed to find any CDDB info for id " + id + " in directory " + file.getParent()); return; } if (results.size() == 1) { logger.trace("Only one result, adding it to the queue"); addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file, results.get(0))); return; } // Got more than 1 result - remove any that don't match on artist and // title (and skip any in the "data" category). String[] dirSplit = Jd7Utils.splitArtistAlbumBits(file.getParentFile() .getName(), SPLITTER_DIRNAME); List<CddbResult> matches = new ArrayList<CddbResult>(); for (CddbResult cddb : results) { String[] resSplit = Jd7Utils.splitArtistAlbumBits(cddb.getTitle(), SPLITTER_CDDB); if (!cddb.getCategory().equalsIgnoreCase(CDDB_DATA_CATEGORY) && equalsIgnoreCase(dirSplit, resSplit)) { matches.add(cddb); } } if (matches.size() >= 1) { logger.trace("Found a match for {}: {}", (Object[]) dirSplit, matches); addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file, matches.get(0))); return; } // Bums // TODO: sort out a way of flagging multiple possibilities to the user // TODO: Internationalise listener.warn("Couldn't find any suitable CDDB info " + "for id " + id + " in directory " + file.getParent() + " out of possible matches " + results + ". Fallen back to file names."); processAlbumData(listener, new NoFileAlbum(file.getParentFile()), true, file.getParentFile(), file); } private void processIdnFile(final File file, final CatalogueSongListener listener) { logger.trace("Processing idn file {}", file); final String id; try { id = readIdValue(file); } catch (IOException ioEx) { // TODO: Internationalise listener.warn("Failed to read an ID value from " + file + " with error " + ioEx.getMessage()); return; } if (id == null) { // TODO: Internationalise listener.warn(file + " does not contain an ID value"); return; } logger.trace("Looking up from cache based on id {}", id); IdnFileAlbum idnf = cache.getFileFromCache(id, file.getParentFile() .getName()); if (idnf != null) { logger.trace("Got result {} from cache", idnf); idnf.setIdnFile(file); processAlbumData(listener, idnf, false, file.getParentFile(), file); } logger.trace("Querying for CDDB results for id {}", id); querier.query(id, new CddbQuerier.Listener() { public void response(List<CddbResult> results) { processQueryResults(listener, file, id, results); } public void error(IOException exception) { listener.warn(exception.getMessage()); } }); } private void recurseForIdFiles(File dir, CatalogueSongListener listener) { File idFile = new File(dir, "id"); if (idFile.exists()) { processIdDir(dir, idFile, listener); } else { File idnFile = new File(dir, "idn"); if (idnFile.exists()) { processIdnFile(idnFile, listener); } } for (File subDir : dir.listFiles()) { if (subDir.isDirectory()) { recurseForIdFiles(subDir, listener); } } } public void listAllSongs(CatalogueSongListener listener) { recurseForIdFiles(root, listener); // Wait for IDN factory to finish any background processing - shouldn't // really throw an error... try { querier.close(); } catch (IOException ioEx) { listener.warn(ioEx.getMessage()); logger.warn("A problem occurred waiting for the CDDB querier to " + "close", ioEx); } } }
package com.whirvis.jraknet.server; import static com.whirvis.jraknet.protocol.MessageIdentifier.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.whirvis.jraknet.Packet; import com.whirvis.jraknet.RakNet; import com.whirvis.jraknet.RakNetException; import com.whirvis.jraknet.RakNetPacket; import com.whirvis.jraknet.client.RakNetClient; import com.whirvis.jraknet.identifier.Identifier; import com.whirvis.jraknet.protocol.MessageIdentifier; import com.whirvis.jraknet.protocol.Reliability; import com.whirvis.jraknet.protocol.login.ConnectionBanned; import com.whirvis.jraknet.protocol.login.IncompatibleProtocol; import com.whirvis.jraknet.protocol.login.OpenConnectionRequestOne; import com.whirvis.jraknet.protocol.login.OpenConnectionRequestTwo; import com.whirvis.jraknet.protocol.login.OpenConnectionResponseOne; import com.whirvis.jraknet.protocol.login.OpenConnectionResponseTwo; import com.whirvis.jraknet.protocol.message.CustomPacket; import com.whirvis.jraknet.protocol.message.EncapsulatedPacket; import com.whirvis.jraknet.protocol.message.acknowledge.Acknowledge; import com.whirvis.jraknet.protocol.status.UnconnectedPing; import com.whirvis.jraknet.protocol.status.UnconnectedPong; import com.whirvis.jraknet.session.GeminusRakNetPeer; import com.whirvis.jraknet.session.RakNetClientSession; import com.whirvis.jraknet.session.RakNetState; import com.whirvis.jraknet.util.RakNetUtils; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; /** * Used to easily create servers using the RakNet protocol. * * @author Trent Summerlin */ public class RakNetServer implements GeminusRakNetPeer, RakNetServerListener { private static final Logger log = LoggerFactory.getLogger(RakNetServer.class); // Server data private final long guid; private final long pongId; private final long timestamp; private final int port; private final int maxConnections; private final int maximumTransferUnit; private boolean broadcastingEnabled; private Identifier identifier; private final ConcurrentLinkedQueue<RakNetServerListener> listeners; private Thread serverThread; // Networking data private final Bootstrap bootstrap; private final EventLoopGroup group; private final RakNetServerHandler handler; // Session data private Channel channel; private volatile boolean running; private final ConcurrentHashMap<InetSocketAddress, RakNetClientSession> sessions; /** * Constructs a <code>RakNetServer</code> with the specified port, maximum * amount connections, maximum transfer unit, and <code>Identifier</code>. * * @param port * the server port. * @param maxConnections * the maximum amount of connections. * @param maximumTransferUnit * the maximum transfer unit. * @param identifier * the <code>Identifier</code>. */ public RakNetServer(int port, int maxConnections, int maximumTransferUnit, Identifier identifier) { // Set server data UUID uuid = UUID.randomUUID(); this.guid = uuid.getMostSignificantBits(); this.pongId = uuid.getLeastSignificantBits(); this.timestamp = System.currentTimeMillis(); this.port = port; this.maxConnections = maxConnections; this.maximumTransferUnit = maximumTransferUnit; this.broadcastingEnabled = true; this.identifier = identifier; this.listeners = new ConcurrentLinkedQueue<RakNetServerListener>(); // Initiate bootstrap data this.bootstrap = new Bootstrap(); this.group = new NioEventLoopGroup(); this.handler = new RakNetServerHandler(this); // Create session map this.sessions = new ConcurrentHashMap<InetSocketAddress, RakNetClientSession>(); // Check maximum transfer unit if (this.maximumTransferUnit < RakNet.MINIMUM_MTU_SIZE) { throw new IllegalArgumentException( "Maximum transfer unit can be no smaller than " + RakNet.MINIMUM_MTU_SIZE); } } /** * Constructs a <code>RakNetServer</code> with the specified port, maximum * amount connections, and maximum transfer unit. * * @param port * the server port. * @param maxConnections * the maximum amount of connections. * @param maximumTransferUnit * the maximum transfer unit. */ public RakNetServer(int port, int maxConnections, int maximumTransferUnit) { this(port, maxConnections, maximumTransferUnit, null); } /** * Constructs a <code>RakNetServer</code> with the specified port and * maximum amount of connections. * * @param port * the server port. * @param maxConnections * the maximum amount of connections. */ public RakNetServer(int port, int maxConnections) { this(port, maxConnections, RakNetUtils.getMaximumTransferUnit()); } /** * Constructs a <code>RakNetServer</code> with the specified port, maximum * amount connections, and <code>Identifier</code>. * * @param port * the server port. * @param maxConnections * the maximum amount of connections. * @param identifier * the <code>Identifier</code>. */ public RakNetServer(int port, int maxConnections, Identifier identifier) { this(port, maxConnections); this.identifier = identifier; } /** * @return the server's networking protocol version. */ public final int getProtocolVersion() { return RakNet.SERVER_NETWORK_PROTOCOL; } /** * @return the server's globally unique ID. */ public final long getGloballyUniqueId() { return this.guid; } /** * @return the server's timestamp. */ public final long getTimestamp() { return (System.currentTimeMillis() - this.timestamp); } /** * @return the port the server is bound to. */ public final int getPort() { return this.port; } /** * @return the maximum amount of connections the server can handle at once. */ public final int getMaxConnections() { return this.maxConnections; } /** * @return the maximum transfer unit. */ public final int getMaximumTransferUnit() { return this.maximumTransferUnit; } /** * Enables/disables server broadcasting. * * @param enabled * whether or not the server will broadcast. */ public final void setBroadcastingEnabled(boolean enabled) { this.broadcastingEnabled = enabled; log.info((enabled ? "Enabled" : "Disabled") + " broadcasting"); } /** * @return <code>true</code> if broadcasting is enabled. */ public final boolean isBroadcastingEnabled() { return this.broadcastingEnabled; } /** * @return the identifier the server uses for discovery. */ public final Identifier getIdentifier() { return this.identifier; } /** * Sets the server's identifier used for discovery. * * @param identifier * the new identifier. */ public final void setIdentifier(Identifier identifier) { this.identifier = identifier; log.info("Set identifier to \"" + identifier.build() + "\""); } /** * @return the thread the server is running on if it was started using * <code>startThreaded()</code>. */ public final Thread getThread() { return this.serverThread; } /** * @return the server's listeners. */ public final RakNetServerListener[] getListeners() { return listeners.toArray(new RakNetServerListener[listeners.size()]); } /** * Adds a listener to the server. * * @param listener * the listener to add. * @return the server. */ public final RakNetServer addListener(RakNetServerListener listener) { // Validate listener if (listener == null) { throw new NullPointerException("Listener must not be null"); } if (listeners.contains(listener)) { throw new IllegalArgumentException("A listener cannot be added twice"); } if (listener instanceof RakNetClient && !listener.equals(this)) { throw new IllegalArgumentException("A server cannot be used as a listener except for itself"); } // Add listener listeners.add(listener); log.info("Added listener " + listener.getClass().getName()); return this; } /** * Adds the server to its own set of listeners, used when extending the * <code>RakNetServer</code> directly. * * @return the server. */ public final RakNetServer addSelfListener() { this.addListener(this); return this; } /** * Removes a listener from the server. * * @param listener * the listener to remove. * @return the server. */ public final RakNetServer removeListener(RakNetServerListener listener) { boolean hadListener = listeners.remove(listener); if (hadListener == true) { log.info("Removed listener " + listener.getClass().getName()); } else { log.warn("Attempted to removed unregistered listener " + listener.getClass().getName()); } return this; } /** * Removes the server from its own set of listeners, used when extending the * <code>RakNetServer</code> directly. * * @return the server. */ public final RakNetServer removeSelfListener() { this.removeListener(this); return this; } /** * @return the sessions connected to the server. */ public final RakNetClientSession[] getSessions() { return sessions.values().toArray(new RakNetClientSession[sessions.size()]); } /** * @return the amount of sessions connected to the server. */ public final int getSessionCount() { return sessions.size(); } /** * @param address * the address to check. * @return true server has a session with the specified address. */ public final boolean hasSession(InetSocketAddress address) { return sessions.containsKey(address); } /** * @param guid * the globally unique ID to check. * @return <code>true</code> if the server has a session with the specified * globally unique ID. */ public final boolean hasSession(long guid) { for (RakNetClientSession session : sessions.values()) { if (session.getGloballyUniqueId() == guid) { return true; } } return false; } /** * @param address * the address of the session. * @return a session connected to the server by their address. */ public final RakNetClientSession getSession(InetSocketAddress address) { return sessions.get(address); } /** * @param guid * the globally unique ID of the session. * @return a session connected to the server by their address. */ public final RakNetClientSession getSession(long guid) { for (RakNetClientSession session : sessions.values()) { if (session.getGloballyUniqueId() == guid) { return session; } } return null; } @Override public final EncapsulatedPacket sendMessage(long guid, Reliability reliability, int channel, Packet packet) { if (this.hasSession(guid)) { return this.getSession(guid).sendMessage(reliability, channel, packet); } else { throw new IllegalArgumentException("No such session with GUID"); } } /** * Removes a session from the server with the specified reason. * * @param address * the address of the session. * @param reason * the reason the session was removed. */ public final void removeSession(InetSocketAddress address, String reason) { if (sessions.containsKey(address)) { // Notify client of disconnection RakNetClientSession session = sessions.remove(address); session.sendMessage(Reliability.UNRELIABLE, ID_DISCONNECTION_NOTIFICATION); // Notify API log.debug("Removed session with address " + address); if (session.getState() == RakNetState.CONNECTED) { for (RakNetServerListener listener : listeners) { listener.onClientDisconnect(session, reason); } } else { for (RakNetServerListener listener : listeners) { listener.onClientPreDisconnect(address, reason); } } } else { log.warn("Attempted to remove session that had not been added to the server"); } } /** * Removes a session from the server. * * @param address * the address of the session. */ public final void removeSession(InetSocketAddress address) { this.removeSession(address, "Disconnected from server"); } /** * Removes a session from the server with the specified reason. * * @param session * the session to remove. * @param reason * the reason the session was removed. */ public final void removeSession(RakNetClientSession session, String reason) { this.removeSession(session.getAddress(), reason); } /** * Removes a session from the server. * * @param session * the session to remove. */ public final void removeSession(RakNetClientSession session) { this.removeSession(session, "Disconnected from server"); } /** * Blocks the address and disconnects all the clients on the address with * the specified reason for the specified amount of time. * * @param address * the address to block. * @param reason * the reason the address was blocked. * @param time * how long the address will blocked in milliseconds. */ public final void blockAddress(InetAddress address, String reason, long time) { for (InetSocketAddress clientAddress : sessions.keySet()) { if (clientAddress.getAddress().equals(address)) { this.removeSession(clientAddress, reason); } } handler.blockAddress(address, reason, time); } /** * Blocks the address and disconnects all the clients on the address for the * specified amount of time. * * @param address * the address to block. * @param time * how long the address will blocked in milliseconds. */ public final void blockAddress(InetAddress address, long time) { this.blockAddress(address, "Blocked", time); } /** * Unblocks the specified address. * * @param address * the address to unblock. */ public final void unblockAddress(InetAddress address) { handler.unblockAddress(address); } /** * @param address * the address to check. * @return <code>true</code> if the specified address is blocked. */ public final boolean addressBlocked(InetAddress address) { return handler.addressBlocked(address); } /** * Called whenever the handler catches an exception in Netty. * * @param address * the address that caused the exception. * @param cause * the exception caught by the handler. */ protected final void handleHandlerException(InetSocketAddress address, Throwable cause) { // Remove session that caused the error if (this.hasSession(address)) { this.removeSession(address, cause.getClass().getName()); } // Notify API log.warn("Handled exception " + cause.getClass().getName() + " caused by address " + address); for (RakNetServerListener listener : listeners) { listener.onHandlerException(address, cause); } } /** * Handles a packet received by the handler. * * @param packet * the packet to handle. * @param sender * the address of the sender. */ protected final void handleMessage(RakNetPacket packet, InetSocketAddress sender) { short packetId = packet.getId(); if (packetId == ID_UNCONNECTED_PING || packetId == ID_UNCONNECTED_PING_OPEN_CONNECTIONS) { UnconnectedPing ping = new UnconnectedPing(packet); ping.decode(); if (ping.failed()) { return; // Bad packet, ignore } // Make sure parameters match and that broadcasting is enabled if ((packetId == ID_UNCONNECTED_PING || (sessions.size() < this.maxConnections || this.maxConnections < 0)) && this.broadcastingEnabled == true) { ServerPing pingEvent = new ServerPing(sender, identifier, ping.connectionType); for (RakNetServerListener listener : listeners) { listener.handlePing(pingEvent); } if (ping.magic == true && pingEvent.getIdentifier() != null) { UnconnectedPong pong = new UnconnectedPong(); pong.timestamp = ping.timestamp; pong.pongId = this.pongId; pong.identifier = pingEvent.getIdentifier(); pong.encode(); if (!pong.failed()) { this.sendNettyMessage(pong, sender); } else { log.error(UnconnectedPong.class.getSimpleName() + " packet failed to encode"); } } } } else if (packetId == ID_OPEN_CONNECTION_REQUEST_1) { OpenConnectionRequestOne connectionRequestOne = new OpenConnectionRequestOne(packet); connectionRequestOne.decode(); if (sessions.containsKey(sender)) { if (sessions.get(sender).getState().equals(RakNetState.CONNECTED)) { this.removeSession(sender, "Client re-instantiated connection"); } } if (connectionRequestOne.magic == true) { // Are there any problems? RakNetPacket errorPacket = this.validateSender(sender); if (errorPacket == null) { if (connectionRequestOne.protocolVersion != this.getProtocolVersion()) { // Incompatible protocol IncompatibleProtocol incompatibleProtocol = new IncompatibleProtocol(); incompatibleProtocol.networkProtocol = this.getProtocolVersion(); incompatibleProtocol.serverGuid = this.guid; incompatibleProtocol.encode(); this.sendNettyMessage(incompatibleProtocol, sender); } else { // Everything passed, one last check... if (connectionRequestOne.maximumTransferUnit <= this.maximumTransferUnit) { OpenConnectionResponseOne connectionResponseOne = new OpenConnectionResponseOne(); connectionResponseOne.serverGuid = this.guid; connectionResponseOne.maximumTransferUnit = connectionRequestOne.maximumTransferUnit; connectionResponseOne.encode(); this.sendNettyMessage(connectionResponseOne, sender); } } } else { this.sendNettyMessage(errorPacket, sender); } } } else if (packetId == ID_OPEN_CONNECTION_REQUEST_2) { OpenConnectionRequestTwo connectionRequestTwo = new OpenConnectionRequestTwo(packet); connectionRequestTwo.decode(); if (!connectionRequestTwo.failed() && connectionRequestTwo.magic == true) { // Are there any problems? RakNetPacket errorPacket = this.validateSender(sender); if (errorPacket == null) { if (this.hasSession(connectionRequestTwo.clientGuid)) { // This client is already connected this.sendNettyMessage(ID_ALREADY_CONNECTED, sender); } else { // Everything passed, one last check... if (connectionRequestTwo.maximumTransferUnit <= this.maximumTransferUnit) { // Create response OpenConnectionResponseTwo connectionResponseTwo = new OpenConnectionResponseTwo(); connectionResponseTwo.serverGuid = this.guid; connectionResponseTwo.clientAddress = sender; connectionResponseTwo.maximumTransferUnit = connectionRequestTwo.maximumTransferUnit; connectionResponseTwo.encryptionEnabled = false; connectionResponseTwo.encode(); if (!connectionResponseTwo.failed()) { // Call event for (RakNetServerListener listener : listeners) { listener.onClientPreConnect(sender); } // Create session RakNetClientSession clientSession = new RakNetClientSession(this, System.currentTimeMillis(), connectionRequestTwo.connectionType, connectionRequestTwo.clientGuid, connectionRequestTwo.maximumTransferUnit, channel, sender); sessions.put(sender, clientSession); // Send response, we are ready for login this.sendNettyMessage(connectionResponseTwo, sender); } } } } else { this.sendNettyMessage(errorPacket, sender); } } } else if (packetId >= ID_CUSTOM_0 && packetId <= ID_CUSTOM_F) { if (sessions.containsKey(sender)) { CustomPacket custom = new CustomPacket(packet); custom.decode(); RakNetClientSession session = sessions.get(sender); session.handleCustom(custom); } } else if (packetId == Acknowledge.ACKNOWLEDGED || packetId == Acknowledge.NOT_ACKNOWLEDGED) { if (sessions.containsKey(sender)) { Acknowledge acknowledge = new Acknowledge(packet); acknowledge.decode(); RakNetClientSession session = sessions.get(sender); session.handleAcknowledge(acknowledge); } } if (MessageIdentifier.hasPacket(packet.getId())) { log.debug("Handled internal packet with ID " + MessageIdentifier.getName(packet.getId()) + " (" + packet.getId() + ")"); } else { log.debug("Sent packet with ID " + packet.getId() + " to session handler"); } } /** * Validates the sender during login to make sure there are no problems. * * @param sender * the address of the packet sender. * @return the packet to respond with if there was an error. */ private final RakNetPacket validateSender(InetSocketAddress sender) { // Checked throughout all login if (this.hasSession(sender)) { return new RakNetPacket(ID_ALREADY_CONNECTED); } else if (this.getSessionCount() >= this.maxConnections && this.maxConnections >= 0) { // We have no free connections return new RakNetPacket(ID_NO_FREE_INCOMING_CONNECTIONS); } else if (this.addressBlocked(sender.getAddress())) { // Address is blocked ConnectionBanned connectionBanned = new ConnectionBanned(); connectionBanned.serverGuid = this.guid; connectionBanned.encode(); return connectionBanned; } // There were no errors return null; } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, com.whirvis.jraknet.Packet) * sendMessage} method. * * @param buf * the buffer to send. * @param address * the address to send the buffer to. */ public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) { channel.writeAndFlush(new DatagramPacket(buf, address)); log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8) + ") to " + address); } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, com.whirvis.jraknet.Packet) * sendMessage} method. * * @param packet * the buffer to send. * @param address * the address to send the buffer to. */ public final void sendNettyMessage(Packet packet, InetSocketAddress address) { this.sendNettyMessage(packet.buffer(), address); } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, int) * sendMessage} method. * * @param packetId * the ID of the packet to send. * @param address * the address to send the packet to. */ public final void sendNettyMessage(int packetId, InetSocketAddress address) { this.sendNettyMessage(new RakNetPacket(packetId), address); } /** * Starts the server. * * @throws RakNetException * if an error occurs during startup. */ public final void start() throws RakNetException { // Make sure we have a listener if (listeners.size() <= 0) { log.warn("Server has no listeners"); } // Create bootstrap and bind the channel try { bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler); bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false); this.channel = bootstrap.bind(port).sync().channel(); this.running = true; log.debug("Created and bound bootstrap"); // Notify API log.info("Started server"); for (RakNetServerListener listener : listeners) { listener.onServerStart(); } // Update system while (this.running == true) { /* * The order here is important, as the sleep could fail to * execute (thus increasing the CPU usage dramatically) if we * sleep before we execute the code in the for loop. */ try { Thread.sleep(0, 1); // Lower CPU usage } catch (InterruptedException e) { // Ignore this, it does not matter } for (RakNetClientSession session : sessions.values()) { try { // Update session and make sure it isn't DOSing us session.update(); if (session.getPacketsReceivedThisSecond() >= RakNet.getMaxPacketsPerSecond()) { this.blockAddress(session.getInetAddress(), "Too many packets", RakNet.MAX_PACKETS_PER_SECOND_BLOCK); } } catch (Throwable throwable) { // An error related to the session occurred for (RakNetServerListener listener : listeners) { listener.onSessionException(session, throwable); } this.removeSession(session, throwable.getMessage()); } } } // Shutdown netty group.shutdownGracefully().sync(); } catch (InterruptedException e) { this.running = false; throw new RakNetException(e); } } /** * Starts the server on its own <code>Thread</code>. * * @return the <code>Thread</code> the server is running on. */ public final Thread startThreaded() { // Give the thread a reference RakNetServer server = this; // Create thread and start it Thread thread = new Thread() { @Override public void run() { try { server.start(); } catch (Throwable throwable) { if (server.getListeners().length > 0) { for (RakNetServerListener listener : server.getListeners()) { listener.onThreadException(throwable); } } else { throwable.printStackTrace(); } } } }; thread.setName("JRAKNET_SERVER_" + Long.toHexString(server.getGloballyUniqueId()).toUpperCase()); thread.start(); this.serverThread = thread; log.info("Started on thread with name " + thread.getName()); // Return the thread so it can be modified return thread; } /** * Stops the server. * * @param reason * the reason the server shutdown. */ public final void shutdown(String reason) { // Tell the server to stop running this.running = false; // Disconnect sessions for (RakNetClientSession session : sessions.values()) { this.removeSession(session, reason); } sessions.clear(); // Interrupt its thread if it owns one if (this.serverThread != null) { serverThread.interrupt(); } // Notify API log.info("Shutdown server"); for (RakNetServerListener listener : listeners) { listener.onServerShutdown(); } } /** * Stops the server. */ public final void shutdown() { this.shutdown("Server shutdown"); } }
package com.zhokhov.interview.sorting; import static com.zhokhov.interview.util.Console.*; /** * @author <a href='mailto:alexey@zhokhov.com'>Alexey Zhokhov</a> */ public class MergeSort { public void sort(int[] array) { mergeSort(array, 0, array.length - 1); } /* * The mergeSort algorithm implementation */ private void mergeSort(int[] array, int left, int right) { __grey("\nmergeSort, left: " + left + ", right: " + right + " ==> "); ____purple("" + (left < right)); if (left < right) { // split the array into 2 int center = (left + right) / 2; ____grey("center: " + center); // sort the left and right array mergeSort(array, left, center); mergeSort(array, center + 1, right); ____grey("Merging, center: " + center); // merge the result merge(array, left, center + 1, right); } } /* * The merge method used by the mergeSort algorithm implementation. */ private void merge(int[] array, int leftArrayBegin, int rightArrayBegin, int rightArrayEnd) { int leftArrayEnd = rightArrayBegin - 1; int numElements = rightArrayEnd - leftArrayBegin + 1; int[] resultArray = new int[numElements]; int resultArrayBegin = 0; ____grey(" leftArrayBegin: " + leftArrayBegin); ____grey(" leftArrayEnd: " + leftArrayEnd); ____grey(" rightArrayBegin: " + rightArrayBegin); ____grey(" rightArrayEnd: " + rightArrayEnd); // Find the smallest element in both these array and add it to the result // array i.e you may have a array of the form [1,5] [2,4] // We need to sort the above as [1,2,4,5] while (leftArrayBegin <= leftArrayEnd && rightArrayBegin <= rightArrayEnd) { if (array[leftArrayBegin] <= array[rightArrayBegin]) { resultArray[resultArrayBegin++] = array[leftArrayBegin++]; ____blue(" new leftArrayBegin: " + leftArrayBegin); } else { resultArray[resultArrayBegin++] = array[rightArrayBegin++]; ____blue(" new rightArrayBegin: " + rightArrayBegin); } } // After the main loop completed we may have few more elements in // left array copy them first while (leftArrayBegin <= leftArrayEnd) { resultArray[resultArrayBegin++] = array[leftArrayBegin++]; ____blue(" [post] new leftArrayBegin: " + leftArrayBegin); } // After the main loop completed we may have few more elements in // right array copy them while (rightArrayBegin <= rightArrayEnd) { resultArray[resultArrayBegin++] = array[rightArrayBegin++]; ____blue(" [post] new rightArrayBegin: " + rightArrayBegin); } // Copy resultArray back to the main array for (int i = numElements - 1; i >= 0; i--, rightArrayEnd--) { array[rightArrayEnd] = resultArray[i]; } } /* * A sample merge method to help understand the merge routine. * This below function is not used by the merge sort * * This is here only for explanation purpose */ public int[] sampleMerge(int[] leftArray, int[] rightArray) { int leftArrayEnd = leftArray.length - 1; int rightArrayEnd = rightArray.length - 1; int leftArrayBegin = 0; int rightArrayBegin = 0; int numElements = leftArray.length + rightArray.length; int[] resultArray = new int[numElements]; int resultArrayBegin = 0; ____grey(" leftArrayBegin: " + leftArrayBegin); ____grey(" leftArrayEnd: " + leftArrayEnd); ____grey(" rightArrayBegin: " + rightArrayBegin); ____grey(" rightArrayEnd: " + rightArrayEnd); // Find the smallest element in both these array and add it to the temp // array i.e you may have a array of the form [1,5] [2,4] // We need to sort the above as [1,2,4,5] while (leftArrayBegin <= leftArrayEnd && rightArrayBegin <= rightArrayEnd) { if (leftArray[leftArrayBegin] <= rightArray[rightArrayBegin]) { resultArray[resultArrayBegin++] = leftArray[leftArrayBegin++]; ____blue(" new leftArrayBegin: " + leftArrayBegin); } else { resultArray[resultArrayBegin++] = rightArray[rightArrayBegin++]; ____blue(" new rightArrayBegin: " + rightArrayBegin); } } // After the main loop completed we may have few more elements in // left array copy them first while (leftArrayBegin <= leftArrayEnd) { resultArray[resultArrayBegin++] = leftArray[leftArrayBegin++]; ____blue(" [post] new leftArrayBegin: " + leftArrayBegin); } // After the main loop completed we may have few more elements in // right array copy them while (rightArrayBegin <= rightArrayEnd) { resultArray[resultArrayBegin++] = rightArray[rightArrayBegin++]; ____blue(" [post] new rightArrayBegin: " + rightArrayBegin); } return resultArray; } public static void main(String args[]) { int array[] = {7, 1, 8, 2, 0, 12, 10, 7, 5, 3}; __yellow("\nNew array: "); __dump(array); System.out.println("\nSorting"); MergeSort mergeSort = new MergeSort(); mergeSort.sort(array); __green("\nResult: "); __dump(array); System.out.print("\n"); System.out.println("***********************\n"); System.out.println("Now demo a simple merge routine."); int leftArray[] = {1, 3, 5, 7}; int rightArray[] = {2, 4, 6, 8, 10}; __yellow("\nLeft array: "); __dump(leftArray); __yellow("Right array: "); __dump(rightArray); System.out.println("\nMerging"); int[] mergedArray = mergeSort.sampleMerge(leftArray, rightArray); __green("\nResult: "); __dump(mergedArray); } }
package de.binarytree.plugins.qualitygates; import hudson.DescriptorExtensionList; import hudson.ExtensionPoint; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.Describable; import hudson.model.AbstractBuild; import hudson.model.Hudson; import de.binarytree.plugins.qualitygates.result.GateReport; public abstract class Gate implements Describable<Gate>, ExtensionPoint { private String name; public Gate(String name) { this.name = name; } public GateReport evaluate(AbstractBuild build, Launcher launcher, BuildListener listener) { GateReport gateReport = new GateReport(this); this.doEvaluation(build, launcher, listener, gateReport); return gateReport; } public GateReport document() { return new GateReport(this); } /** * Performs the actual evaluation of this gate. * * The type of evaluation is fully up to the implementer. Whether the * evaluation has been successful has to be denoted in the given gateReport * object. * * - SUCCESS means, that the result of the gate was positive and the * following gates shall be evaluated afterwards. - UNSTABLE means, that the * gate has generated warnings, but the following gates shall be evaluated * nevertheless. - FAILURE means, that the result of the gate was negative, * therefore the following gates shall NOT be evaluated. - NOT_BUILT means, * that the gate was not evaluated, therefore the following gates shall NOT * be evaluated. Reevaluation can be triggered by a GET-Request to the * {@link BuildResultAction}. * * @param gateReport * the report where the gate has to document, whether its * evaluation has been successfull */ abstract void doEvaluation(AbstractBuild build, Launcher launcher, BuildListener listener, GateReport gateReport); public QualityGateDescriptor getDescriptor() { return (QualityGateDescriptor) Hudson.getInstance().getDescriptor( getClass()); } public String getName() { return this.name; } public static DescriptorExtensionList<Gate, QualityGateDescriptor> all() { return Hudson.getInstance() .<Gate, QualityGateDescriptor> getDescriptorList(Gate.class); } }
package de.dhbw.humbuch.view; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.eventbus.EventBus; import com.google.inject.Inject; import com.vaadin.data.Container.Filter; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.fieldgroup.FieldGroup.CommitException; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.filter.Or; import com.vaadin.data.util.filter.SimpleStringFilter; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.event.ShortcutListener; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.AbstractTextField.TextChangeEventMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Table; import com.vaadin.ui.Table.ColumnGenerator; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import de.davherrmann.mvvm.BasicState; import de.davherrmann.mvvm.State; import de.davherrmann.mvvm.StateChangeListener; import de.davherrmann.mvvm.ViewModelComposer; import de.davherrmann.mvvm.annotations.BindState; import de.dhbw.humbuch.event.ConfirmEvent; import de.dhbw.humbuch.event.MessageEvent; import de.dhbw.humbuch.model.entity.Category; import de.dhbw.humbuch.model.entity.Profile; import de.dhbw.humbuch.model.entity.SchoolYear.Term; import de.dhbw.humbuch.model.entity.Subject; import de.dhbw.humbuch.model.entity.TeachingMaterial; import de.dhbw.humbuch.viewmodel.BookManagementViewModel; import de.dhbw.humbuch.viewmodel.BookManagementViewModel.Categories; import de.dhbw.humbuch.viewmodel.BookManagementViewModel.TeachingMaterials; /** * * @author Martin Wentzel * */ public class BookManagementView extends VerticalLayout implements View, ViewInformation { private static final long serialVersionUID = -5063268947544706757L; private static final String TITLE = "Lehrmittelverwaltung"; private static final String TABLE_CATEGORY = "category"; private static final String TABLE_NAME = "name"; private static final String TABLE_PROFILE = "profile"; private static final String TABLE_FROMGRADE = "fromGrade"; private static final String TABLE_FROMTERM = "fromTerm"; private static final String TABLE_TOGRADE = "toGrade"; private static final String TABLE_TOTERM = "toTerm"; private static final String TABLE_PRODUCER = "producer"; private static final String TABLE_IDENTNR = "identifyingNumber"; private static final String TABLE_COMMENT = "comment"; private static final String TABLE_VALIDFROM = "validFrom"; private static final String TABLE_VALIDUNTIL = "validUntil"; private EventBus eventBus; private BookManagementViewModel bookManagementViewModel; /** * Layout components */ private HorizontalLayout head; private TextField filter; private Button btnEdit; private Button btnNew; private Button btnDelete; private Table materialsTable; private BeanItemContainer<TeachingMaterial> tableData; private BeanFieldGroup<TeachingMaterial> binder = new BeanFieldGroup<TeachingMaterial>( TeachingMaterial.class); @BindState(TeachingMaterials.class) public final State<Collection<TeachingMaterial>> teachingMaterials = new BasicState<>( Collection.class); @BindState(Categories.class) public final State<Collection<Category>> categories = new BasicState<>( Collection.class); /** * All popup-window components and the corresponding binded states. The * popup-window for adding a new teaching material and editing a teaching * material is the same. Only the caption will be set differently */ private Window windowEditTeachingMaterial; private FormLayout windowContent; private HorizontalLayout windowButtons; private TextField txtTmName = new TextField("Titel"); private TextField txtIdentNr = new TextField("Nummer/ISBN"); private TextField txtProducer = new TextField("Hersteller/Verlag"); private TextField txtFromGrade = new TextField(); private TextField txtToGrade = new TextField(); private ComboBox cbProfiles = new ComboBox("Profil"); private ComboBox cbFromTerm = new ComboBox(); private ComboBox cbToTerm = new ComboBox(); private ComboBox cbCategory = new ComboBox("Kategorie"); private DateField dfValidFrom = new DateField("Gültig von"); private DateField dfValidUntil = new DateField("Gültig bis"); private TextArea textAreaComment = new TextArea("Kommentar"); private Button btnWindowSave = new Button("Speichern"); private Button btnWindowCancel = new Button("Abbrechen"); @Inject public BookManagementView(ViewModelComposer viewModelComposer, BookManagementViewModel bookManagementViewModel, EventBus eventBus) { this.bookManagementViewModel = bookManagementViewModel; this.eventBus = eventBus; init(); buildLayout(); bindViewModel(viewModelComposer, bookManagementViewModel); } /** * Initializes the components and sets attributes. * */ @SuppressWarnings("serial") private void init() { head = new HorizontalLayout(); head.setWidth("100%"); head.setSpacing(true); // Filter filter = new TextField(); filter.setImmediate(true); filter.setInputPrompt("Lehrmittel suchen..."); filter.setWidth("50%"); filter.setTextChangeEventMode(TextChangeEventMode.EAGER); head.addComponent(filter); head.setExpandRatio(filter, 1); head.setComponentAlignment(filter, Alignment.MIDDLE_LEFT); // Buttons HorizontalLayout buttons = new HorizontalLayout(); buttons.setSpacing(true); // Add btnNew = new Button("Hinzufügen"); buttons.addComponent(btnNew); // Delete btnDelete = new Button("Löschen"); btnDelete.setEnabled(false); buttons.addComponent(btnDelete); // Edit btnEdit = new Button("Bearbeiten"); btnEdit.setEnabled(false); btnEdit.addStyleName("default"); btnEdit.setClickShortcut(KeyCode.ENTER); buttons.addComponent(btnEdit); head.addComponent(buttons); head.setComponentAlignment(buttons, Alignment.MIDDLE_RIGHT); // Instantiate table materialsTable = new Table(); materialsTable.setSelectable(true); materialsTable.setImmediate(true); materialsTable.setSizeFull(); materialsTable.setColumnCollapsingAllowed(true); tableData = new BeanItemContainer<TeachingMaterial>( TeachingMaterial.class); materialsTable.setContainerDataSource(tableData); materialsTable.setVisibleColumns(new Object[] { TABLE_NAME, TABLE_PRODUCER, TABLE_PROFILE, TABLE_FROMGRADE, TABLE_TOGRADE, TABLE_CATEGORY, TABLE_IDENTNR }); materialsTable.setColumnHeader(TABLE_CATEGORY, "Kategorie"); materialsTable.setColumnHeader(TABLE_NAME, "Titel"); materialsTable.setColumnHeader(TABLE_PROFILE, "Profil"); materialsTable.setColumnHeader(TABLE_FROMGRADE, "Von Klasse"); materialsTable.setColumnHeader(TABLE_TOGRADE, "Bis Klasse"); materialsTable.setColumnHeader(TABLE_PRODUCER, "Hersteller/Verlag"); materialsTable.setColumnHeader(TABLE_IDENTNR, "Nummer/ISBN"); materialsTable.setColumnHeader(TABLE_COMMENT, "Kommentar"); materialsTable.setColumnHeader(TABLE_VALIDFROM, "Gültig von"); materialsTable.setColumnHeader(TABLE_VALIDUNTIL, "Gültig bis"); materialsTable.addGeneratedColumn(TABLE_PROFILE, new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { TeachingMaterial item = (TeachingMaterial) itemId; String profile = ""; for (Entry<String, Set<Subject>> entry : Profile .getProfileMap().entrySet()) { if (item.getProfile().equals(entry.getValue())) { profile = entry.getKey().toString(); break; } } return profile; } }); binder.setBuffered(true); this.createEditWindow(); this.addListener(); } /** * Creates the window for editing and creating teaching materials * * @return The created Window */ @SuppressWarnings("serial") public void createEditWindow() { // Create Window and set parameters windowEditTeachingMaterial = new Window(); windowEditTeachingMaterial.center(); windowEditTeachingMaterial.setModal(true); windowEditTeachingMaterial.setResizable(false); windowContent = new FormLayout(); windowContent.setMargin(true); windowButtons = new HorizontalLayout(); windowButtons.setSpacing(true); btnWindowSave.addStyleName("default"); // Fill Comboboxes cbFromTerm.addItem(Term.FIRST); cbFromTerm.addItem(Term.SECOND); cbToTerm.addItem(Term.FIRST); cbToTerm.addItem(Term.SECOND); Map<String, Set<Subject>> profiles = Profile.getProfileMap(); for (Map.Entry<String, Set<Subject>> profile : profiles.entrySet()) { cbProfiles.addItem(profile.getValue()); cbProfiles.setItemCaption(profile.getValue(), profile.getKey()); } // Set Form options cbCategory.setNullSelectionAllowed(false); cbProfiles.setNullSelectionAllowed(false); cbFromTerm.setNullSelectionAllowed(false); cbToTerm.setNullSelectionAllowed(false); txtIdentNr.setRequired(true); txtTmName.setRequired(true); cbCategory.setRequired(true); cbProfiles.setRequired(true); dfValidFrom.setRequired(true); dfValidUntil.setDescription("Leer für unbestimmtes Gültigkeitsdatum"); // Input prompts txtIdentNr.setInputPrompt("ISBN"); txtTmName.setInputPrompt("Titel oder Name"); txtProducer.setInputPrompt("z.B. Klett"); txtFromGrade.setInputPrompt("z.B. 5"); txtToGrade.setInputPrompt("z.B. 7"); textAreaComment.setInputPrompt("Zusätzliche Informationen"); // NullRepresentation txtIdentNr.setNullRepresentation(""); txtTmName.setNullRepresentation(""); txtProducer.setNullRepresentation(""); txtFromGrade.setNullRepresentation(""); txtToGrade.setNullRepresentation(""); textAreaComment.setNullRepresentation(""); // Bind to FieldGroup binder.bind(txtTmName, TABLE_NAME); binder.bind(txtIdentNr, TABLE_IDENTNR); binder.bind(cbCategory, TABLE_CATEGORY); binder.bind(txtProducer, TABLE_PRODUCER); binder.bind(cbProfiles, TABLE_PROFILE); binder.bind(txtFromGrade, TABLE_FROMGRADE); binder.bind(cbFromTerm, TABLE_FROMTERM); binder.bind(txtToGrade, TABLE_TOGRADE); binder.bind(cbToTerm, TABLE_TOTERM); binder.bind(dfValidFrom, TABLE_VALIDFROM); binder.bind(dfValidUntil, TABLE_VALIDUNTIL); binder.bind(textAreaComment, TABLE_COMMENT); // Add all components windowContent.addComponent(txtTmName); windowContent.addComponent(txtIdentNr); windowContent.addComponent(cbCategory); windowContent.addComponent(txtProducer); windowContent.addComponent(cbProfiles); windowContent.addComponent(new HorizontalLayout() { { setSpacing(true); setCaption("Von Klassenstufe"); txtFromGrade.setWidth("50px"); cbFromTerm.setWidth(null); addComponent(txtFromGrade); addComponent(cbFromTerm); } }); windowContent.addComponent(new HorizontalLayout() { { setSpacing(true); setCaption("Bis Klassenstufe"); txtToGrade.setWidth("50px"); addComponent(txtToGrade); addComponent(cbToTerm); } }); windowContent.addComponent(dfValidFrom); windowContent.addComponent(dfValidUntil); windowContent.addComponent(textAreaComment); windowButtons.addComponent(btnWindowCancel); windowButtons.addComponent(btnWindowSave); windowContent.addComponent(windowButtons); windowEditTeachingMaterial.setContent(windowContent); windowEditTeachingMaterial.setCaption("Lehrmittel bearbeiten"); windowEditTeachingMaterial.setCloseShortcut(KeyCode.ESCAPE, null); } /** * Adds all listener to their corresponding components. * */ @SuppressWarnings("serial") private void addListener() { /** * Listens for changes in the Collection teachingMaterials and adds them * to the container */ teachingMaterials.addStateChangeListener(new StateChangeListener() { @Override public void stateChange(Object value) { tableData.removeAllItems(); for (TeachingMaterial material : teachingMaterials.get()) { tableData.addItem(material); } } }); /** * Enables/disables the edit and delete buttons */ materialsTable.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); btnEdit.setEnabled(item != null); btnDelete.setEnabled(item != null); } }); /** * Opens the popup-window for editing a book and inserts the data from * the teachingMaterialInfo-State. */ btnEdit.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); binder.setItemDataSource(item); UI.getCurrent().addWindow(windowEditTeachingMaterial); txtTmName.focus(); } }); /** * Opens a new popup-window with an empty new teaching material */ btnNew.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { TeachingMaterial item = new TeachingMaterial.Builder(null, null, null, new Date()).build(); binder.setItemDataSource(item); UI.getCurrent().addWindow(windowEditTeachingMaterial); txtTmName.focus(); } }); /** * Closes the popup window * */ btnWindowCancel.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { windowEditTeachingMaterial.close(); clearWindowFields(); } }); /** * Saves the teachingMaterial and closes the popup-window * */ btnWindowSave.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if (FormFieldsValid()) { try { binder.commit(); bookManagementViewModel.doUpdateTeachingMaterial(binder .getItemDataSource().getBean()); windowEditTeachingMaterial.close(); eventBus.post(new MessageEvent( "Lehrmittel gespeichert.")); } catch (CommitException e) { eventBus.post(new MessageEvent(e.getLocalizedMessage())); } } } }); /** * Show a confirm popup and delete the teaching material on confirmation */ btnDelete.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { final TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); if (item != null) { Runnable runnable = new Runnable() { @Override public void run() { bookManagementViewModel .doDeleteTeachingMaterial(item); materialsTable.select(null); } }; eventBus.post(new ConfirmEvent.Builder( "Wollen Sie das Lehrmittel wirklich löschen?") .caption("Löschen").confirmRunnable(runnable) .build()); } } }); /** * Provides the live search of the teaching material table by adding a * filter after every keypress in the search field. Currently the * publisher and title search are supported. */ filter.addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = -1684545652234105334L; @Override public void textChange(TextChangeEvent event) { String text = event.getText(); Filter filter = new Or(new SimpleStringFilter(TABLE_NAME, text, true, false), new SimpleStringFilter(TABLE_PRODUCER, text, true, false), new SimpleStringFilter(TABLE_CATEGORY,text,true,false), new SimpleStringFilter(TABLE_FROMGRADE,text,true,false), new SimpleStringFilter(TABLE_TOGRADE,text,true,false), new SimpleStringFilter(TABLE_IDENTNR,text,true,false)); tableData.removeAllContainerFilters(); tableData.addContainerFilter(filter); } }); /** * Allows to dismiss the filter by hitting ESCAPE */ filter.addShortcutListener(new ShortcutListener("Clear", KeyCode.ESCAPE, null) { @Override public void handleAction(Object sender, Object target) { filter.setValue(""); tableData.removeAllContainerFilters(); } }); /** * Fills the category combobox */ categories.addStateChangeListener(new StateChangeListener() { @Override public void stateChange(Object arg0) { for (Category cat : categories.get()) { cbCategory.addItem(cat); cbCategory.setItemCaption(cat, cat.getName()); } } }); } /** * Validates the fields in the edit teaching materials window. * * @return Whether or not the fields in the editor are valid */ private boolean FormFieldsValid() { // Validate if a field is empty if (txtTmName.getValue() == null || txtIdentNr.getValue() == null || cbCategory.getValue() == null || dfValidFrom.getValue() == null || cbProfiles.getValue() == null) { eventBus.post(new MessageEvent( "Bitte füllen Sie alle Pflicht-Felder aus.")); return false; } else { // No field is empty, validate now for right values and lengths if (txtTmName.getValue().length() < 2) { eventBus.post(new MessageEvent( "Der Titel muss mindestens 2 Zeichen enthalten.")); return false; } try { if (txtToGrade.getValue() != null) Integer.parseInt(txtToGrade.getValue()); if (txtFromGrade.getValue() != null) Integer.parseInt(txtFromGrade.getValue()); } catch (NumberFormatException e) { eventBus.post(new MessageEvent( "Die Klassenstufen dürfen nur Zahlen enthalten")); return false; } try { dfValidFrom.validate(); dfValidUntil.validate(); } catch (InvalidValueException e) { eventBus.post(new MessageEvent( "Mindestens ein Datumsfeld ist nicht korrekt.")); return false; } return true; } } /** * Builds the layout by adding all components in their specific order. */ private void buildLayout() { setMargin(true); setSpacing(true); setSizeFull(); addComponent(head); addComponent(materialsTable); setExpandRatio(materialsTable, 1); } /** * Empties the fields of the popup-window to prevent that TextFields already * have content form previous edits. */ private void clearWindowFields() { txtTmName.setValue(""); txtIdentNr.setValue(""); txtProducer.setValue(""); txtFromGrade.setValue(""); txtToGrade.setValue(""); textAreaComment.setValue(""); txtProducer.setValue(""); cbFromTerm.setValue(Term.FIRST); cbToTerm.setValue(Term.SECOND); } @Override public void enter(ViewChangeEvent event) { // TODO Q&D: have to be changed after "data has changed"-system is // implemented bookManagementViewModel.updateCategories(); } private void bindViewModel(ViewModelComposer viewModelComposer, Object... viewModels) { try { viewModelComposer.bind(this, viewModels); } catch (IllegalAccessException | NoSuchElementException | UnsupportedOperationException e) { e.printStackTrace(); } } @Override public String getTitle() { return TITLE; } }
package de.j4velin.wifiAutoOff; import android.content.Context; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.preference.Preference; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; public class StatusPreference extends Preference { private ImageView image; private TextView title; private TextView sub1; private TextView sub2; public StatusPreference(final Context context, final AttributeSet attrs) { super(context, attrs); } @Override protected View onCreateView(final ViewGroup parent) { super.onCreateView(parent); LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = li.inflate(R.layout.statepreference, parent, false); image = v.findViewById(R.id.icon); title = v.findViewById(R.id.title); sub1 = v.findViewById(R.id.sub1); sub2 = v.findViewById(R.id.sub2); update(); return v; } /** * Called to update the status preference */ void update() { WifiManager wm = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); boolean connected = ((ConnectivityManager) getContext().getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE)) .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected(); if (title == null) return; if (wm.isWifiEnabled()) { if (!connected) { title.setText(R.string.no_connected); image.setColorFilter(Color.DKGRAY); sub1.setText(R.string.click_to_select_network); sub2.setVisibility(View.GONE); } else { WifiInfo wi = wm.getConnectionInfo(); String ssid = wi.getSSID(); if (ssid.contains("unknown ssid")) { ssid = getContext().getString(R.string.event_connected); } title.setText(ssid); image.setColorFilter(getContext().getResources().getColor(R.color.colorAccent)); updateSignal(); int ip = wi.getIpAddress(); sub2.setText(String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff))); sub2.setVisibility(View.VISIBLE); } } else { title.setText(R.string.wifi_not_enabled); image.setColorFilter(Color.LTGRAY); sub1.setText(R.string.click_to_turn_on); sub2.setVisibility(View.GONE); } } /** * Called to update the WiFi signal text * * @return true, if connected to a WiFi network */ boolean updateSignal() { WifiManager wm = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); boolean connected = ((ConnectivityManager) getContext().getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE)) .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); if (sub1 == null) return wm.isWifiEnabled() && connected; if (wm.isWifiEnabled() && connected) { WifiInfo wi = wm.getConnectionInfo(); try { sub1.setText(WifiManager.calculateSignalLevel(wi.getRssi(), 100) + "% - " + wi.getLinkSpeed() + " Mbps"); } catch (ArithmeticException e) { sub1.setText(wi.getLinkSpeed() + " Mbps"); } return true; } else { return false; } } }
package de.jformchecker.themes; import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.GenericFormBuilder; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; import de.jformchecker.criteria.ValidationResult; public class BasicFormBuilder extends GenericFormBuilder { String divSuccessClass = "has-success"; String divErrorClass = "has-error"; protected String getHelpTag(String helpText, FormCheckerElement elem) { return "<span id=\"" + this.getHelpBlockId(elem) + "\" class=\"help-block\">" + helpText + "</span>"; } public TagAttributes getLabelAttributes(FormCheckerElement elem) { TagAttributes attributes = new TagAttributes(); attributes.put("class", "control-label"); return attributes; } public Wrapper getWrapperForInput(FormCheckerElement elem) { return new Wrapper("<div>", "</div>"); } public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } public void addAttributesToInputFields(Map<String, String> attribs, FormCheckerElement elem) { attribs.put("class", "form-control"); } public Wrapper getWrapperForElem(FormCheckerElement elem, boolean firstRun) { String state = ""; if (!firstRun) { if (!elem.isValid()) { state = " " + divErrorClass; } else { state = " " + divSuccessClass; } } return new Wrapper("<div class=\"form-group" + state + "\">", "</div>"); } final public void setDivSuccessClass(String divSuccessClass) { this.divSuccessClass = divSuccessClass; } final public void setDivErrorClass(String divErrorClass) { this.divErrorClass = divErrorClass; } @Override public ValidationResult getErrors(FormCheckerElement e, boolean firstRun) { if (!firstRun && !e.isValid()) { return (e.getValidationResult()); } return ValidationResult.ok(); } @Override public String formatError(String error) { if (error != null && !"".equals(error)) { return ("Problem: " + error + "!!<br>"); } else { return ""; } } @Override public Wrapper getWrapperForAllFormElements() { return Wrapper.of("<fieldset>", "</fieldset>"); } }
package dmillerw.lore.command; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.IChatComponent; import net.minecraft.world.World; /** * @author dmillerw */ public class LoreCommandSender implements ICommandSender { public EntityPlayer player; public LoreCommandSender(EntityPlayer player) { this.player = player; } @Override public String getCommandSenderName() { return player.getCommandSenderName(); } @Override public IChatComponent func_145748_c_() { return player.func_145748_c_(); } @Override public void addChatMessage(IChatComponent var1) { } @Override public boolean canCommandSenderUseCommand(int var1, String var2) { return true; } @Override public ChunkCoordinates getPlayerCoordinates() { return player.getPlayerCoordinates(); } @Override public World getEntityWorld() { return player.getEntityWorld(); } }
package edu.neumont.java.playlistpug; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class PugServlet */ /** * @see HttpServlet#HttpServlet() */ public PugServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String destination = request.getPathInfo(); String[] path = null; if(request.getPathInfo() == null || request.getPathInfo().equals("")){ destination = "/WEB-INF/index.jsp"; }else{ path = request.getPathInfo().substring(1).split("/"); Boolean b = destination.equals("/"); if(destination.equals("/") || path[0].equals("index") || path[0].equals("main") || path[0].equals("home")){ destination = "/WEB-INF/index.jsp"; }else if(path[0].equals("upload")){ destination = "/WEB-INF/upload.jsp"; }else if(path[0].equals("song")){ //set attributes name as the name of the song and //song as whatever is needed to play the song request.setAttribute("name", "song name"); request.setAttribute("song", "song data"); destination = "/WEB-INF/song.jsp"; }else if(path[0].equals("search")){ //depends on how we decide to do the searching //may set attribute to search terms or list of search results request.setAttribute("search_terms_or_results", ""); destination = "/WEB-INF/search.jsp"; } } RequestDispatcher rd = request.getRequestDispatcher(destination); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
package edu.oregonstate.carto.mapcomposer; import com.jhlabs.composite.MultiplyComposite; import com.jhlabs.image.BicubicScaleFilter; import com.jhlabs.image.BoxBlurFilter; import com.jhlabs.image.ImageUtils; import com.jhlabs.image.LightFilter; import com.jhlabs.image.ShadowFilter; import com.jhlabs.image.TileImageFilter; import edu.oregonstate.carto.importer.AdobeCurveReader; import edu.oregonstate.carto.mapcomposer.gui.ErrorDialog; import edu.oregonstate.carto.mapcomposer.imageFilters.CurvesFilter; import edu.oregonstate.carto.mapcomposer.imageFilters.CurvesFilter.Curve; import edu.oregonstate.carto.mapcomposer.utils.TintFilter; import edu.oregonstate.carto.tilemanager.ImageTileMerger; import edu.oregonstate.carto.tilemanager.Tile; import edu.oregonstate.carto.tilemanager.TileSet; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.xml.bind.annotation.XmlElement; /** * A map layer. * * @author Nicholas Hallahan nick@theoutpost.io * @author Bernhard Jenny, Cartography and Geovisualization Group, Oregon State * University */ public class Layer { public enum BlendType { NORMAL, MULTIPLY } private static BufferedImage whiteMegaTile; private TileSet imageTileSet; private TileSet maskTileSet; @XmlElement(name = "visible") private boolean visible = true; @XmlElement(name = "name") private String name; @XmlElement(name = "textureTileFilePath") private String textureTileFilePath; @XmlElement(name = "blending") private BlendType blending = BlendType.NORMAL; @XmlElement(name = "opacity") private float opacity = 1; @XmlElement(name = "curveURL") private String curveURL; private CurvesFilter.Curve[] curves = null; @XmlElement(name = "tint") private Tint tint = null; @XmlElement(name = "textureScale") private float textureScale = 1f; @XmlElement(name = "invertMask") private boolean invertMask = false; @XmlElement(name = "maskBlur") private float maskBlur = 0; @XmlElement(name = "shadow") private Shadow shadow = null; @XmlElement(name = "emboss") private Emboss emboss = null; public Layer() { } public Layer(String layerName) { this.name = layerName; } public void renderToTile(Graphics2D g2d, int z, int x, int y) { if (isBlendingNormal()) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getOpacity())); } else { g2d.setComposite(new MultiplyComposite(getOpacity())); } BufferedImage image = null; if (textureTileFilePath != null) { try { BufferedImage textureTile = ImageIO.read(new File(textureTileFilePath)); textureTile = ImageUtils.convertImageToARGB(textureTile); // scale texture patch if needed if (textureScale != 1f) { int textureW = (int) (textureTile.getWidth() * this.textureScale); int textureH = (int) (textureTile.getHeight() * this.textureScale); BicubicScaleFilter scaleFilter = new BicubicScaleFilter(textureW, textureH); textureTile = scaleFilter.filter(textureTile, null); } TileImageFilter tiler = new TileImageFilter(); tiler.setHeight(Tile.TILE_SIZE * 3); tiler.setWidth(Tile.TILE_SIZE * 3); BufferedImage dst = new BufferedImage(Tile.TILE_SIZE * 3, Tile.TILE_SIZE * 3, BufferedImage.TYPE_INT_ARGB); image = tiler.filter(textureTile, dst); } catch (IOException ex) { image = null; // FIXME System.err.println("could not load texture image"); } } // load tile image if (imageTileSet != null) { Tile tile = imageTileSet.getTile(z, x, y); try { image = ImageTileMerger.createMegaTile(tile); // convert to ARGB. All following manipulations are optimized for // this modus. image = ImageUtils.convertImageToARGB(image); } catch (IOException exc) { image = null; } } // tinting if (this.tint != null) { // use the pre-existing image for modulating brightness if the image // exists (i.e. a texture image has been created or an image has // been loaded). if (image != null) { TintFilter tintFilter = new TintFilter(); tintFilter.setTint(tint.getTintColor()); System.out.println(tint.getTintColor().toString()); image = tintFilter.filter(image, null); } else { // no pre-existing image, create a solid color image image = solidColorImage(Tile.TILE_SIZE * 3, Tile.TILE_SIZE * 3, this.tint.getTintColor()); } } // create solid white background image if no image has been loaded if (image == null) { image = createWhiteMegaTile(); } // gradation curve if (this.curveURL != null && this.curveURL.length() > 0) { image = curve(image); } // masking BufferedImage maskImage = null; if (maskTileSet != null) { Tile tile = maskTileSet.getTile(z, x, y); try { maskImage = ImageTileMerger.createMegaTile(tile); // convert to ARGB. All following manipulations are optimized for // this modus. maskImage = ImageUtils.convertImageToARGB(maskImage); } catch (IOException exc) { maskImage = createWhiteMegaTile(); } if (this.maskBlur > 0) { BoxBlurFilter blurFilter = new BoxBlurFilter(); blurFilter.setHRadius(this.maskBlur); blurFilter.setVRadius(this.maskBlur); blurFilter.setPremultiplyAlpha(false); blurFilter.setIterations(1); maskImage = blurFilter.filter(maskImage, null); } image = alphaChannelFromGrayImage(image, maskImage, this.invertMask); } // embossing if (this.emboss != null) { // this solution works fine, but is slow LightFilter lightFilter = new LightFilter(); lightFilter.setBumpSource(LightFilter.BUMPS_FROM_IMAGE_ALPHA); lightFilter.setBumpHeight(this.emboss.getEmbossHeight()); lightFilter.setBumpSoftness(this.emboss.getEmbossSoftness()); LightFilter.Light forestLight = (LightFilter.Light) (lightFilter.getLights().get(0)); forestLight.setAzimuth((float) Math.toRadians(this.emboss.getEmbossAzimuth() - 90)); forestLight.setElevation((float) Math.toRadians(this.emboss.getEmbossElevation())); forestLight.setDistance(0); forestLight.setIntensity(1f); //lightFilter.getMaterial().highlight = 10f; lightFilter.getMaterial().highlight = 10f; image = lightFilter.filter(image, null); } // drop shadow: draw it onto the destination image if (this.shadow != null) { BufferedImage shadowImage = ImageUtils.cloneImage(image); //x negative : left - x positive : right //y negative : down - y positive : up //TODO : distinguish x and y offset OR use a mouving offset !! ShadowFilter shadowFilter = new ShadowFilter(this.shadow.getShadowFuziness(), this.shadow.getShadowOffset(), -this.shadow.getShadowOffset(), 1f); shadowFilter.setShadowColor(this.shadow.getShadowColor().getRGB()); shadowImage = shadowFilter.filter(shadowImage, null); shadowImage = shadowImage.getSubimage(Tile.TILE_SIZE, Tile.TILE_SIZE, Tile.TILE_SIZE, Tile.TILE_SIZE); g2d.drawImage(shadowImage, null, null); } // draw this layer into the destination image BufferedImage tileImage = image.getSubimage(Tile.TILE_SIZE, Tile.TILE_SIZE, Tile.TILE_SIZE, Tile.TILE_SIZE); g2d.drawImage(tileImage, null, null); } /** * Applies curve to image. * @param image * @return */ private BufferedImage curve(BufferedImage image) { // load curve from file if it has not been loaded yet try { if (curves == null && curveURL != null) { URI uri = new URI(curveURL); if (!new File(uri).exists()) { ErrorDialog.showErrorDialog("Curves file does not exist."); return null; } AdobeCurveReader acr = new AdobeCurveReader(); acr.readACV(new URL(curveURL)); curves = acr.getCurves(); for (CurvesFilter.Curve c : curves) { c.normalize(); } } } catch (IOException | URISyntaxException ex) { Logger.getLogger(Layer.class.getName()).log(Level.SEVERE, null, ex); } // apply curve to image if (curves != null) { CurvesFilter curvesFilter = new CurvesFilter(); curvesFilter.setCurves(curves); return curvesFilter.filter(image, null); } else { return null; } } /** * Use a grayscale image as alpha channel for another image. */ private static BufferedImage alphaChannelFromGrayImage(BufferedImage image, BufferedImage mask, boolean invertMask) { image = ImageUtils.convertImageToARGB(image); // convert mask to grayscale image if necessary if (mask.getType() != BufferedImage.TYPE_BYTE_GRAY) { System.out.println("!!!! Alpha Mask not in Grayscale Modus !!!!"); BufferedImage tmpMask = new BufferedImage(mask.getWidth(), mask.getHeight(), BufferedImage.TYPE_BYTE_GRAY); ColorConvertOp toGray = new ColorConvertOp(null); mask = toGray.filter(mask, tmpMask); } // for TYPE_INT_ARGB with a TYPE_BYTE_GRAY mask if (mask.getType() == BufferedImage.TYPE_BYTE_GRAY) { byte ad[] = ((DataBufferByte) mask.getRaster().getDataBuffer()).getData(); int d[] = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); int size = image.getWidth() * image.getHeight(); if (!invertMask) { for (int i = 0; i < size; i++) { d[i] = (d[i] & 0xFFFFFF) | ((((int) ad[i]) << 24) ^ 0xff000000); } } else { for (int i = 0; i < size; i++) { d[i] = (d[i] & 0xFFFFFF) | (((int) ad[i]) << 24); } } } return image; } private static BufferedImage solidColorImage(int width, int height, Color color) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setColor(color); g2d.fillRect(0, 0, width, height); g2d.dispose(); return image; } private static BufferedImage createWhiteMegaTile() { if (whiteMegaTile != null) { return whiteMegaTile; } whiteMegaTile = new BufferedImage(Tile.TILE_SIZE * 3, Tile.TILE_SIZE * 3, BufferedImage.TYPE_INT_ARGB); Graphics2D g = whiteMegaTile.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, Tile.TILE_SIZE * 3, Tile.TILE_SIZE * 3); g.dispose(); return whiteMegaTile; } /** * @return the visible */ public boolean isVisible() { return visible; } /** * @param visible the visible to set */ public void setVisible(boolean visible) { this.visible = visible; } /** * @return the name */ public String getName() { return name; } /** * @param name the layerName to set */ public void setName(String name) { this.name = name; } /** * @return the imageTileSet */ public TileSet getImageTileSet() { return imageTileSet; } /** * @param imageTileSet the imageTileSet to set */ public void setImageTileSet(TileSet imageTileSet) { this.imageTileSet = imageTileSet; } /** * @return the textureTileFilePath */ public String getTextureTileFilePath() { return textureTileFilePath; } /** * @param textureTileFilePath File path for a single tile that is used to * texture the layer. */ public void setTextureTileFilePath(String textureTileFilePath) { this.textureTileFilePath = textureTileFilePath; } /** * @return the maskTileSet */ public TileSet getMaskTileSet() { return maskTileSet; } /** * @param maskTileSet the maskTileSet to set */ public void setMaskTileSet(TileSet maskTileSet) { this.maskTileSet = maskTileSet; } /** * * @return true if the blend type is normal */ public boolean isBlendingNormal() { return blending == BlendType.NORMAL; } /** * Setting the blending type. * * @param blending type */ public void setBlending(BlendType blending) { this.blending = blending; } /** * @return the opacity */ public float getOpacity() { return opacity; } /** * @param opacity the opacity to set */ public void setOpacity(float opacity) { this.opacity = opacity; } /** * @return the curveURL */ public String getCurveURL() { return curveURL; } /** * @param curveURL the curveURL to set */ public void setCurveURL(String curveURL) { curves = null; this.curveURL = curveURL; } /** * @return the textureScale */ public float getTextureScale() { return textureScale; } /** * @param textureScale the textureScale to set */ public void setTextureScale(float textureScale) { this.textureScale = textureScale; } /** * @return the invertMask */ public boolean isInvertMask() { return invertMask; } /** * @param invertMask the invertMask to set */ public void setInvertMask(boolean invertMask) { this.invertMask = invertMask; } /** * @return the maskBlur */ public float getMaskBlur() { return maskBlur; } /** * @param maskBlur the maskBlur to set */ public void setMaskBlur(float maskBlur) { this.maskBlur = maskBlur; } /** * @return the blending */ public BlendType getBlending() { return blending; } /** * @return the tint */ public Tint getTint() { return tint; } /** * @param tint the tint to set */ public void setTint(Tint tint) { this.tint = tint; } /** * @return the shadow */ public Shadow getShadow() { return shadow; } /** * @param shadow the shadow to set */ public void setShadow(Shadow shadow) { this.shadow = shadow; } /** * @return the emboss */ public Emboss getEmboss() { return emboss; } /** * @param emboss the emboss to set */ public void setEmboss(Emboss emboss) { this.emboss = emboss; } @Override public String toString() { return getName(); } }
package es.ucm.fdi.iw.controller; import java.security.Principal; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import es.ucm.fdi.iw.model.API; import es.ucm.fdi.iw.model.Usuario; @Controller public class RootController { //Se usa para registrar lo que hagamos private static Logger log = Logger.getLogger(RootController.class); @Autowired private PasswordEncoder passwordEncoder; @Autowired private EntityManager entityManager; @ModelAttribute public void addAttributes(Model m) { m.addAttribute("prefix", "static/"); } @GetMapping({ "/", "/index" }) @Transactional public String index(Model model) { List<String> listaJS = new ArrayList<String>(); listaJS.add("jquery-3.1.1.min.js"); listaJS.add("index.js"); model.addAttribute("pageExtraScripts", listaJS); API.cardsDataBaseMin(entityManager,2,100); return "index"; } @GetMapping({ "/info" }) public String info(Model model) { List<String> listaCSS = new ArrayList<String>(); listaCSS.add("infoStyle.css"); model.addAttribute("pageExtraCSS", listaCSS); List<String> listaJS = new ArrayList<String>(); listaJS.add("jquery-3.1.1.min.js"); listaJS.add("index.js"); model.addAttribute("pageExtraScripts", listaJS); return "info"; } private void setDefaultJS(Model m, String ... others) { List<String> listaJS = new ArrayList<String>(); listaJS.add("jquery-3.1.1.min.js"); listaJS.add("jquery-ui-1.12.1/jquery-ui.min.js"); listaJS.add("bootstrap.min.js"); listaJS.add("star-rating.min.js"); for (String o : others) { listaJS.add(o + ".js"); } m.addAttribute("pageExtraScripts", listaJS); } @GetMapping({ "/intercambio" }) public String intercambio(Model model, HttpSession session) { List<String> listaCSS = new ArrayList<String>(); listaCSS.add("intercambioStyles.css"); List<String> listaJS = new ArrayList<String>(); listaJS.add("jquery-3.1.1.min.js"); listaJS.add("bootstrap.min.js"); listaJS.add("intercambio.js"); model.addAttribute("pageExtraCSS", listaCSS); model.addAttribute("pageExtraScripts", listaJS); return "intercambio"; } @RequestMapping(value="/register", method = RequestMethod.POST) @Transactional public String register(@RequestParam("nombre") String formName, @RequestParam("apellidos") String formSurname, @RequestParam("email") String formEmail, @RequestParam("usuario") String formUser, @RequestParam("contrasena") String formPassword, @RequestParam("provincia") String formProvincia, HttpSession session) { Usuario u = Usuario.crearUsuario(formName,formSurname,formEmail,formUser, passwordEncoder.encode(formPassword), formProvincia); log.info("Creating user " + u); entityManager.persist(u); entityManager.flush(); return "redirect:home"; } /** * Logout (also returns to home view). */ @GetMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:index"; } @GetMapping({ "/historial" }) public String historial(Model model, HttpSession session) { List<String> listaCSS = new ArrayList<String>(); listaCSS.add("styleHistorial.css"); List<String> listaJS = new ArrayList<String>(); listaJS.add("jquery-3.1.1.min.js"); listaJS.add("bootstrap.min.js"); model.addAttribute("pageExtraCSS", listaCSS); model.addAttribute("pageExtraScripts", listaJS); return "historial"; } }
package foodtruck.alexa; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.amazon.speech.slu.Intent; import com.amazon.speech.slu.Slot; import com.amazon.speech.speechlet.Session; import com.amazon.speech.speechlet.SpeechletResponse; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Inject; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.LocationDAO; import foodtruck.geolocation.GeoLocator; import foodtruck.geolocation.GeolocationGranularity; import foodtruck.model.Location; import foodtruck.model.TruckStop; import foodtruck.schedule.ScheduleCacher; import foodtruck.server.resources.json.DailyScheduleWriter; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; import foodtruck.util.TimeOnlyFormatter; import static foodtruck.util.MoreStrings.capitalize; /** * @author aviolette * @since 8/25/16 */ class LocationIntentProcessor implements IntentProcessor { static final String SLOT_LOCATION = "Location"; static final String SLOT_WHEN = "When"; private static final Logger log = Logger.getLogger(LocationIntentProcessor.class.getName()); private final GeoLocator locator; private final FoodTruckStopService service; private final Clock clock; private final ScheduleCacher scheduleCacher; private final LocationDAO locationDAO; private final DailyScheduleWriter dailyScheduleWriter; private final Location defaultCenter; private final DateTimeFormatter formatter; @Inject public LocationIntentProcessor(GeoLocator locator, FoodTruckStopService service, Clock clock, LocationDAO locationDAO, ScheduleCacher cacher, DailyScheduleWriter dailyScheduleWriter, @DefaultCenter Location center, @TimeOnlyFormatter DateTimeFormatter formatter) { this.locator = locator; this.service = service; this.clock = clock; this.locationDAO = locationDAO; scheduleCacher = cacher; this.dailyScheduleWriter = dailyScheduleWriter; this.defaultCenter = center; this.formatter = formatter; } @Override public Set<String> getSlotNames() { return ImmutableSet.of(SLOT_LOCATION, SLOT_WHEN); } @Override public SpeechletResponse process(Intent intent, Session session) { Slot locationSlot = intent.getSlot(SLOT_LOCATION); String locationName = locationSlot.getValue(); if (Strings.isNullOrEmpty(locationName)) { return provideHelp(); } else if (locationName.endsWith(" for")) { locationName = locationName.substring(0, locationName.length() - 4); } Location location = locator.locate(locationName, GeolocationGranularity.NARROW); boolean tomorrow = "tomorrow".equals(intent.getSlot(SLOT_WHEN) .getValue()); LocalDate currentDay = clock.currentDay(); LocalDate requestDate = tomorrow ? currentDay.plusDays(1) : currentDay; if (location == null || !location.isResolved()) { return locationNotFound(locationName, tomorrow, requestDate); } boolean inFuture = requestDate.isAfter(currentDay); String dateRepresentation = toDate(requestDate); SpeechletResponseBuilder builder = SpeechletResponseBuilder.builder(); @SuppressWarnings("unchecked") List<TruckStop> trucks = FluentIterable.from( service.findStopsNearALocation(location, requestDate)) .toList(); List<String> truckNames = Lists.transform(trucks, TruckStop.TO_TRUCK_NAME); List<String> truckTimes = Lists.transform(trucks, new Function<TruckStop, String>() { public String apply(TruckStop input) { return formatter.print(input.getStartTime()) + " to " + formatter.print(input.getEndTime()); } }); boolean allSame = Sets.newHashSet(truckTimes) .size() == 1; String futurePhrase = inFuture ? "scheduled to be " : ""; int count = truckNames.size(); switch (count) { case 0: String nearby = AlexaUtils.toAlexaList(findAlternateLocations(tomorrow, location, requestDate), true, Conjunction.or); String noTrucks; if (Strings.isNullOrEmpty(nearby)) { noTrucks = String.format( "There are no trucks %sat %s %s and there don't appear to be any nearby that location.", futurePhrase, location.getShortenedName(), dateRepresentation); builder.speechSSML(noTrucks); } else if ("downtown".equalsIgnoreCase(locationName)) { builder.speechSSML( String.format("These trucks are %sat be downtown %s: %s", futurePhrase, dateRepresentation, nearby)); } else { builder.speechSSML( String.format("There are no trucks %sat %s %s. These nearby locations have food trucks: %s.", futurePhrase, location.getShortenedName(), dateRepresentation, nearby)); } break; case 1: builder.speechSSML( String.format("%s is %sat %s %s from %s", truckNames.get(0), futurePhrase, location.getShortenedName(), dateRepresentation, truckTimes.get(0))); break; case 2: { String schedulePart = allSame ? " from " + truckTimes.get(0) : buildSchedulePart(truckNames, truckTimes); builder.speechSSML( String.format("%s and %s are %sat %s %s%s", truckNames.get(0), truckNames.get(1), futurePhrase, location.getShortenedName(), dateRepresentation, schedulePart)); } break; default: { String schedulePart = allSame ? " from " + truckTimes.get(0) : buildSchedulePart(truckNames, truckTimes); builder.speechSSML( String.format("There are %s trucks %sat %s %s: %s%s", count, futurePhrase, locationSlot.getValue(), dateRepresentation, AlexaUtils.toAlexaList(truckNames, true), schedulePart)); } } String prefix = "downtown".equalsIgnoreCase(locationName) ? "" : "at "; String cardTitle = String.format("Food Trucks %s%s %s", prefix, location.getShortenedName(), capitalize(toDate(requestDate))); if (location.getImageUrl() == null) { builder.simpleCard(cardTitle); } else { builder.imageCard(cardTitle, location.getImageUrl() .secure(), location.getImageUrl() .secure()); } return builder.tell(); } private String buildSchedulePart(List<String> truckNames, List<String> truckTimes) { List<String> combined = Lists.newLinkedList(); for (int i = 0; i < truckNames.size(); i++) { combined.add(truckNames.get(i) + " from " + truckTimes.get(i)); } return ". " + AlexaUtils.toAlexaList(combined, true); } private SpeechletResponse provideHelp() { List<String> locations = findAlternateLocations(false, null, clock.currentDay()); if (locations.isEmpty()) { locations = ImmutableList.of("Clark and Monroe"); } return SpeechletResponseBuilder.builder() .speechSSML(String.format( "You can ask me about a specific location in Chicago. For example, you can say: What food trucks are at %s today?", locations.get(0))) .useSpeechTextForReprompt() .ask(); } private SpeechletResponse locationNotFound(String locationName, boolean tomorrow, LocalDate requestDate) { List<String> locations = findAlternateLocations(tomorrow, null, requestDate); log.log(Level.SEVERE, "Could not find location {0} that is specified in alexa", locationName); SpeechletResponseBuilder builder = SpeechletResponseBuilder.builder(); if (locations.isEmpty()) { return builder.speechSSML("What location was that?") .useSpeechTextForReprompt() .tell(); } else { return builder.speechSSML("What location was that?") .repromptSSML(String.format( "I did not recognize the location you mentioned. Some locations that have trucks %s are %s. Which location are you interested in?", toDate(requestDate), AlexaUtils.toAlexaList(locations, true, Conjunction.or))) .ask(); } } private List<String> findAlternateLocations(boolean tomorrow, Location currentLocation, LocalDate theDate) { try { String schedule = tomorrow ? scheduleCacher.findTomorrowsSchedule() : scheduleCacher.findSchedule(); if (tomorrow && Strings.isNullOrEmpty(schedule)) { schedule = dailyScheduleWriter.asJSON(service.findStopsForDay(theDate)) .toString(); scheduleCacher.saveTomorrowsSchedule(schedule); } List<Location> locations = extractLocations(schedule); Predicate<Location> filterPredicate = Predicates.alwaysTrue(); Location searchLocation = MoreObjects.firstNonNull(currentLocation, defaultCenter); if (searchLocation != null) { Collections.sort(locations, searchLocation.distanceFromComparator()); if (currentLocation != null) { filterPredicate = currentLocation.rangedPredicate(5); } } return FluentIterable.from(locations) .filter(filterPredicate) .transform(Location.TO_SPOKEN_NAME) .limit(3) .toList(); } catch (Exception e) { log.log(Level.WARNING, "Could not parse daily schedule {0} {1}", new Object[]{tomorrow, e.getMessage()}); return ImmutableList.of("Clark and Monroe"); } } private List<Location> extractLocations(String schedule) throws JSONException { JSONObject jsonObject = new JSONObject(schedule); log.log(Level.FINE, "Schedule {0}", jsonObject); JSONArray locationArr = jsonObject.getJSONArray("locations"); List<Location> locations = Lists.newLinkedList(); for (int i = 0; i < locationArr.length(); i++) { Long key = locationArr.getJSONObject(i) .getLong("key"); Location loc = locationDAO.findById(key); if (loc == null) { continue; } locations.add(loc); } return locations; } private String toDate(LocalDate date) { if (date.equals(clock.currentDay())) { return "today"; } else if (date.minusDays(1) .equals(clock.currentDay())) { return "tomorrow"; } else { return "on that date"; } } }
package fr.liglab.lcm.internals; import java.util.Arrays; import java.util.Calendar; import fr.liglab.lcm.internals.FrequentsIterator; import fr.liglab.lcm.internals.Dataset.TransactionsIterable; import fr.liglab.lcm.internals.Selector.WrongFirstParentException; import fr.liglab.lcm.io.FileReader; import fr.liglab.lcm.util.ItemsetsFactory; import gnu.trove.map.hash.TIntIntHashMap; /** * Represents an LCM recursion step. Its also acts as a Dataset factory. */ public final class ExplorationStep implements Cloneable { public static boolean verbose = false; public static boolean ultraVerbose = false; public final static String KEY_VIEW_SUPPORT_THRESHOLD = "lcm.threshold.view"; public final static String KEY_LONG_TRANSACTIONS_THRESHOLD = "lcm.threshold.long"; public final static String KEY_DENSITY_THRESHOLD = "lcm.threshold.density"; /** * @see longTransactionsMode */ static int LONG_TRANSACTION_MODE_THRESHOLD = Integer.parseInt( System.getProperty(KEY_LONG_TRANSACTIONS_THRESHOLD, "2000")); /** * When projecting on a item having a support count above * VIEW_SUPPORT_THRESHOLD%, projection will be a DatasetView */ static double VIEW_SUPPORT_THRESHOLD = Double.parseDouble( System.getProperty(KEY_VIEW_SUPPORT_THRESHOLD, "0.15")); /** * When set to true we stick to a complete LCMv2 implementation, with predictive * prefix-preservation tests and compressions at all steps. * Setting this to false is better when mining top-k-per-item patterns. */ public static boolean LCM_STYLE = true; /** * closure of parent's pattern UNION extension */ public final int[] pattern; /** * Extension item that led to this recursion step. Already included in * "pattern". */ public final int core_item; public final Dataset dataset; public final Counters counters; /** * Selectors chain - may be null when empty */ protected Selector selectChain; protected final FrequentsIterator candidates; /** * When an extension fails first-parent test, it ends up in this map. Keys * are non-first-parent items associated to their actual first parent. */ private final TIntIntHashMap failedFPTests; private final boolean predictiveFPTestMode; /** * Start exploration on a dataset contained in a file. * * @param minimumSupport * @param path * to an input file in ASCII format. Each line should be a * transaction containing space-separated item IDs. */ public ExplorationStep(int minimumSupport, String path) { this.core_item = Integer.MAX_VALUE; this.selectChain = null; this.predictiveFPTestMode = false; FileReader reader = new FileReader(path); this.counters = new Counters(minimumSupport, reader); reader.close(this.counters.renaming); this.pattern = this.counters.closure; this.dataset = new Dataset(this.counters, reader); this.candidates = this.counters.getExtensionsIterator(); this.failedFPTests = new TIntIntHashMap(); } private ExplorationStep(int[] pattern, int core_item, Dataset dataset, Counters counters, Selector selectChain, FrequentsIterator candidates, TIntIntHashMap failedFPTests, boolean predictiveFPTestMode) { super(); this.pattern = pattern; this.core_item = core_item; this.dataset = dataset; this.counters = counters; this.selectChain = selectChain; this.candidates = candidates; this.failedFPTests = failedFPTests; this.predictiveFPTestMode = predictiveFPTestMode; } /** * Finds an extension for current pattern in current dataset and returns the * corresponding ExplorationStep (extensions are enumerated by ascending * item IDs - in internal rebasing) Returns null when all valid extensions * have been generated */ public ExplorationStep next() { if (this.candidates == null) { return null; } while (true) { int candidate = this.candidates.next(); if (candidate < 0) { return null; } try { if (this.selectChain == null || this.selectChain.select(candidate, this)) { TransactionsIterable support = this.dataset.getSupport(candidate); // System.out.println("extending "+Arrays.toString(this.pattern)+ // " with "+ // candidate+" ("+this.counters.getReverseRenaming()[candidate]+")"); Counters candidateCounts = new Counters(this.counters.minSupport, support.iterator(), candidate, this.dataset.getIgnoredItems(), this.counters.maxFrequent); int greatest = Integer.MIN_VALUE; for (int i = 0; i < candidateCounts.closure.length; i++) { if (candidateCounts.closure[i] > greatest) { greatest = candidateCounts.closure[i]; } } if (greatest > candidate) { throw new WrongFirstParentException(candidate, greatest); } // instanciateDataset may choose to compress renaming - if // not, at least it's set for now. candidateCounts.reuseRenaming(this.counters.reverseRenaming); return new ExplorationStep(this, candidate, candidateCounts, support); } } catch (WrongFirstParentException e) { addFailedFPTest(e.extension, e.firstParent); } } } /** * Instantiate state for a valid extension. * * @param parent * @param extension * a first-parent extension from parent step * @param candidateCounts * extension's counters from parent step * @param support * previously-computed extension's support */ protected ExplorationStep(ExplorationStep parent, int extension, Counters candidateCounts, TransactionsIterable support) { this.core_item = extension; this.counters = candidateCounts; int[] reverseRenaming = parent.counters.reverseRenaming; if (verbose) { if (parent.pattern.length == 0 || ultraVerbose) { System.err.format("%1$tY/%1$tm/%1$td %1$tk:%1$tM:%1$tS - thread %2$d projecting %3$s with %4$s\n", Calendar.getInstance(), Thread.currentThread().getId(), Arrays.toString(parent.pattern), reverseRenaming[extension]); } } this.pattern = ItemsetsFactory .extendRename(candidateCounts.closure, extension, parent.pattern, reverseRenaming); if (this.counters.nbFrequents == 0 || this.counters.distinctTransactionsCount == 0) { this.candidates = null; this.failedFPTests = null; this.selectChain = null; this.dataset = null; this.predictiveFPTestMode = false; } else { this.failedFPTests = new TIntIntHashMap(); if (parent.selectChain == null) { this.selectChain = null; } else { this.selectChain = parent.selectChain.copy(); } // ! \\ From here, order is important if (parent.predictiveFPTestMode) { this.predictiveFPTestMode = true; } else { final int averageLen = candidateCounts.distinctTransactionLengthSum / candidateCounts.distinctTransactionsCount; this.predictiveFPTestMode = LCM_STYLE || averageLen > LONG_TRANSACTION_MODE_THRESHOLD; if (this.predictiveFPTestMode) { this.selectChain = new FirstParentTest(this.selectChain); } } // indeed, instantiateDataset is influenced by longTransactionsMode this.dataset = instanciateDataset(parent, support); // and intanciateDataset may choose to trigger some renaming in // counters this.candidates = this.counters.getExtensionsIterator(); } } private Dataset instanciateDataset(ExplorationStep parent, TransactionsIterable support) { double supportRate = this.counters.distinctTransactionsCount / (double) parent.dataset.getStoredTransactionsCount(); if (!this.predictiveFPTestMode && (supportRate) > VIEW_SUPPORT_THRESHOLD) { return new DatasetView(parent.dataset, this.counters, support, this.core_item); } else { int[] renaming = this.counters.compressRenaming(parent.counters.getReverseRenaming()); TransactionsRenamingDecorator filtered = new TransactionsRenamingDecorator(support.iterator(), renaming); Dataset dataset = new Dataset(this.counters, filtered); if (LCM_STYLE) { dataset.compress(this.core_item); } return dataset; } } public int getFailedFPTest(final int item) { synchronized (this.failedFPTests) { return this.failedFPTests.get(item); } } private void addFailedFPTest(final int item, final int firstParent) { synchronized (this.failedFPTests) { this.failedFPTests.put(item, firstParent); } } public void appendSelector(Selector s) { if (this.selectChain == null) { this.selectChain = s; } else { this.selectChain = this.selectChain.append(s); } } public int getCatchedWrongFirstParentCount() { if (this.failedFPTests == null) { return 0; } else { return this.failedFPTests.size(); } } public ExplorationStep copy() { return new ExplorationStep(pattern, core_item, dataset.clone(), counters.clone(), selectChain, candidates, failedFPTests, predictiveFPTestMode); } public Progress getProgression() { return new Progress(); } public final class Progress { public final int current; public final int last; protected Progress() { this.current = candidates.peek(); this.last = candidates.last(); } } }
package io.github.bonigarcia.wdm; import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * Generic manager. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public abstract class BrowserManager { protected static final Logger log = LoggerFactory .getLogger(BrowserManager.class); private static final String SEPARATOR = "/"; private static final Architecture DEFAULT_ARCH = Architecture .valueOf("x" + System.getProperty("sun.arch.data.model")); private static final String MY_OS_NAME = getOsName(); private static final String VERSION_PROPERTY = "wdm.driverVersion"; public abstract List<URL> getDrivers() throws Exception; protected abstract String getExportParameter(); protected abstract String getDriverVersion(); protected abstract String getDriverName(); protected abstract URL getDriverUrl() throws MalformedURLException; protected String versionToDownload; public void setup() { setup(DEFAULT_ARCH, DriverVersion.NOT_SPECIFIED.name()); } public void setup(String version) { setup(DEFAULT_ARCH, version); } public void setup(Architecture arch) { setup(arch, DriverVersion.NOT_SPECIFIED.name()); } public void setup(Architecture arch, String version) { try { // Honor property if available (even when version is present) String driverVersion = getDriverVersion(); if (!driverVersion.equalsIgnoreCase(DriverVersion.LATEST.name()) || version.equals(DriverVersion.NOT_SPECIFIED.name())) { version = driverVersion; } this.getClass().newInstance().manage(arch, version); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } public void manage(Architecture arch, DriverVersion version) { manage(arch, version.name()); } public String existsDriverInCache(String repository, String driverVersion, Architecture arch) { String driverName = getDriverName(); log.trace("Checking if {} {} ({} bits) exists in cache {}", driverName, driverVersion, arch, repository); Iterator<File> iterateFiles = FileUtils .iterateFiles(new File(repository), null, true); String driverInCache = null; while (iterateFiles.hasNext()) { driverInCache = iterateFiles.next().toString(); // Exception for phantomjs boolean architecture = driverName.equals("phantomjs") || driverInCache.contains(arch.toString()); log.trace("Checking {}", driverInCache); if (driverInCache.contains(driverVersion) && driverInCache.contains(driverName) && architecture) { log.debug("Found {} {} ({} bits) in cache: {} ", driverVersion, driverName, arch, driverInCache); break; } else { driverInCache = null; } } if (driverInCache == null) { log.trace("{} {} ({} bits) do not exist in cache {}", driverVersion, driverName, arch, repository); } return driverInCache; } public void manage(Architecture arch, String version) { try { boolean getLatest = version == null || version.isEmpty() || version.equalsIgnoreCase(DriverVersion.LATEST.name()) || version.equalsIgnoreCase( DriverVersion.NOT_SPECIFIED.name()); String driverInCache = null; if (!getLatest) { versionToDownload = version; driverInCache = existsDriverInCache(Downloader.getTargetPath(), version, arch); } if (driverInCache != null) { System.setProperty(VERSION_PROPERTY, version); exportDriver(getExportParameter(), driverInCache); } else { // Get the complete list of URLs List<URL> urls = getDrivers(); if (!urls.isEmpty()) { List<URL> candidateUrls; boolean continueSearchingVersion; do { // Get the latest or concrete version if (getLatest) { candidateUrls = getLatest(urls, getDriverName()); } else { candidateUrls = getVersion(urls, getDriverName(), version); } if (versionToDownload == null) { break; } log.trace("All URLS: {}", urls); log.trace("Candidate URLS: {}", candidateUrls); if (this.getClass().equals(EdgeDriverManager.class)) { // Microsoft Edge binaries are different continueSearchingVersion = false; } else { // Filter by architecture and OS candidateUrls = filter(candidateUrls, arch); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.debug("No valid binary found for {} {}", getDriverName(), versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } } while (continueSearchingVersion); if (candidateUrls.isEmpty()) { String versionStr = getLatest ? "(latest version)" : version; String errMessage = getDriverName() + " " + versionStr + " for " + MY_OS_NAME + arch.toString() + " not found in " + getDriverUrl(); log.error(errMessage); throw new RuntimeException(errMessage); } for (URL url : candidateUrls) { String export = candidateUrls.contains(url) ? getExportParameter() : null; System.setProperty(VERSION_PROPERTY, versionToDownload); Downloader.download(url, versionToDownload, export, getDriverName()); } } } } catch (Exception e) { throw new RuntimeException(e); } } public List<URL> filter(List<URL> list, Architecture arch) { log.trace("{} {} - URLs before filtering: {}", getDriverName(), versionToDownload, list); List<URL> out = new ArrayList<URL>(); // Round #1 : Filter by OS for (URL url : list) { for (OperativeSystem os : OperativeSystem.values()) { if (((MY_OS_NAME.contains(os.name()) && url.getFile().toLowerCase().contains(os.name())) || getDriverName().equals("IEDriverServer") || (IS_OS_MAC && url.getFile().toLowerCase().contains("osx"))) && !out.contains(url)) { out.add(url); } } } log.trace("{} {} - URLs after filtering by OS ({}): {}", getDriverName(), versionToDownload, MY_OS_NAME, out); // Round #2 : Filter by architecture (32/64 bits) if (out.size() > 1 && arch != null) { for (URL url : list) { // Exception: 32 bits (sometimes referred as x86) if (arch == Architecture.x32 && url.getFile().contains("x86")) { continue; } if (!url.getFile().contains(arch.toString())) { out.remove(url); } } } log.trace("{} {} - URLs after filtering by architecture ({}): {}", getDriverName(), versionToDownload, arch, out); return out; } public List<URL> removeFromList(List<URL> list, String version) { List<URL> out = new ArrayList<URL>(list); for (URL url : list) { if (url.getFile().contains(version)) { out.remove(url); } } return out; } public List<URL> getVersion(List<URL> list, String match, String version) { List<URL> out = new ArrayList<URL>(); Collections.reverse(list); for (URL url : list) { if (url.getFile().contains(match) && url.getFile().contains(version) && !url.getFile().contains("-symbols")) { out.add(url); } } versionToDownload = version; log.debug("Using {} {}", match, version); return out; } public List<URL> getLatest(List<URL> list, String match) { log.trace("Checking the lastest version of {}", match); log.trace("Input URL list {}", list); List<URL> out = new ArrayList<URL>(); Collections.reverse(list); for (URL url : list) { if (url.getFile().contains(match)) { log.trace("URL {} match with {}", url, match); String currentVersion; if (getDriverName().equals("phantomjs")) { String file = url.getFile(); file = url.getFile().substring(file.lastIndexOf(SEPARATOR), file.length()); final int matchIndex = file.indexOf(match); currentVersion = file.substring( matchIndex + match.length() + 1, file.length()); final int dashIndex = currentVersion.indexOf('-'); currentVersion = currentVersion.substring(0, dashIndex); } else if (getDriverName().equals("wires")) { currentVersion = url.getFile().substring( url.getFile().indexOf("-") + 1, url.getFile().lastIndexOf("-")); } else if (getDriverName().equals("operadriver")) { currentVersion = url.getFile().substring( url.getFile().indexOf(SEPARATOR + "v") + 2, url.getFile().lastIndexOf(SEPARATOR)); } else { currentVersion = url.getFile().substring( url.getFile().indexOf(SEPARATOR) + 1, url.getFile().lastIndexOf(SEPARATOR)); } if (getDriverName().equals("MicrosoftWebDriver")) { currentVersion = currentVersion.substring( currentVersion.lastIndexOf(SEPARATOR) + 1); } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } } log.info("Latest version of {} is {}", match, versionToDownload); return out; } public Integer versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int i = 0; while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { i++; } if (i < vals1.length && i < vals2.length) { int diff = Integer.valueOf(vals1[i]) .compareTo(Integer.valueOf(vals2[i])); return Integer.signum(diff); } else { return Integer.signum(vals1.length - vals2.length); } } public List<URL> getDriversFromXml(URL driverUrl, String driverBinary) throws Exception { log.info("Reading {} to seek {}", driverUrl, getDriverName()); List<URL> urls = new ArrayList<URL>(); int retries = 1; int maxRetries = WdmConfig.getInt("wdm.seekErrorRetries"); do { try { BufferedReader reader = new BufferedReader( new InputStreamReader(driverUrl.openStream())); Document xml = loadXML(reader); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key", xml.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { Element e = (Element) nodes.item(i); String version = e.getChildNodes().item(0).getNodeValue(); urls.add(new URL(driverUrl + version)); } reader.close(); break; } catch (Throwable e) { log.warn("[{}/{}] Exception reading {} to seek {}: {} {}", retries, maxRetries, driverUrl, getDriverName(), e.getClass().getName(), e.getMessage(), e); retries++; if (retries > maxRetries) { throw e; } } } while (true); return urls; } public Document loadXML(Reader reader) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(reader); return builder.parse(is); } public String getDownloadedVersion() { return System.getProperty(VERSION_PROPERTY); } private static String getOsName() { String os = System.getProperty("os.name").toLowerCase(); if (SystemUtils.IS_OS_WINDOWS) { os = "win"; } else if (SystemUtils.IS_OS_LINUX) { os = "linux"; } else if (SystemUtils.IS_OS_MAC) { os = "mac"; } return os; } protected static void exportDriver(String variableName, String variableValue) { log.info("Exporting {} as {}", variableName, variableValue); System.setProperty(variableName, variableValue); } }
package dk.netarkivet.harvester.scheduler; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.CommonSettings; import dk.netarkivet.common.utils.CleanupIF; import dk.netarkivet.common.utils.ExceptionUtils; import dk.netarkivet.common.utils.NotificationsFactory; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.harvester.HarvesterSettings; import dk.netarkivet.harvester.datamodel.DBSpecifics; import dk.netarkivet.harvester.datamodel.HarvestDefinitionDAO; import dk.netarkivet.harvester.datamodel.Job; import dk.netarkivet.harvester.datamodel.JobDAO; import dk.netarkivet.harvester.datamodel.JobStatus; import dk.netarkivet.harvester.harvesting.distribute.HarvestControllerClient; import dk.netarkivet.harvester.harvesting.distribute.MetadataEntry; /** * This class handles scheduling of heritrix jobs. * The scheduler loads all active harvest definitions and * extracts the scheduling information for each definition. * When a harvest definition is scheduled to start the scheduler * creates the corresponding heritrix jobs and submits these * to the active HarvestServers. It also handles backup and makes * sure backup is not performed while jobs are being scheduled. * This class is not Threadsafe. */ public class HarvestScheduler implements CleanupIF { /** The logger to use. */ protected static final Log log = LogFactory.getLog( HarvestScheduler.class.getName()); /** The Client to use for communicating with the known servers. */ private HarvestControllerClient hcc; /** The timer used to control how frequently, jobs are scheduled. */ private Timer timer; /** The unique instance of this class. */ private static HarvestScheduler instance; /** The period between checking if new jobs should be generated. * This is one minute because that's the finest we can define in a harvest * definition. */ private static final int GENERATE_JOBS_PERIOD = 60*1000; /** Lock guaranteeing that only one timertask is running at a time, and * that allows the next timer tasks to drop out if one is still running. */ private boolean running; /** * Listener after responses from submitted Harvest jobs. */ private static HarvestSchedulerMonitorServer hsmon; /** * Backup-related fields. */ private Date lastBackupDate = null; private int backupInitHour; /** * Create new instance of the HarvestScheduler. */ private HarvestScheduler() { log.info("Creating HarvestScheduler"); hcc = HarvestControllerClient.getInstance(); hsmon = HarvestSchedulerMonitorServer.getInstance(); backupInitHour = Settings.getInt(CommonSettings.DB_BACKUP_INIT_HOUR); if (backupInitHour < 0 || backupInitHour > 23) { log.warn("Illegal value for backupHour " + "(Settting = DB_BACKUP_INIT_HOUR) found: " + backupInitHour); log.info("BackupHour set to 0"); backupInitHour = 0; } else { log.info("Backup hour is " + backupInitHour); } } /** * Get the unique instance of the harvest scheduler. If the instance is * new it is started up to begin scheduling harvests. * @return The instance */ public static synchronized HarvestScheduler getInstance() { if (instance == null) { instance = new HarvestScheduler(); //automatically calls the run-method.. instance.run(); } return instance; } /** * Start scheduling of harvest definitions. * The location of the harvestdefinition data is retrieved from: * settings.xml */ public void run() { try { log.debug("Rescheduling any leftover jobs"); rescheduleJobs(); log.debug("Starting scheduling of harvestdefinitions"); log.info("Scheduler running every " + (GENERATE_JOBS_PERIOD/1000) + " seconds"); TimerTask task = new TimerTask() { public void run() { try { synchronized (timer) { scheduleJobs(); } } catch (Throwable e) { log.warn("Exception while scheduling new jobs", e); } } }; final GregorianCalendar cal = new GregorianCalendar(); // Schedule running every GENERATE_JOBS_PERIOD milliseconds // presently one minut. scheduleJobs(); // stop STARTED jobs which have been on for more than // settings.harvester.scheduler.jobtimeouttime time stopTimeoutJobs(); timer = new Timer(true); timer.scheduleAtFixedRate(task, cal.getTime(), GENERATE_JOBS_PERIOD); } catch (Throwable t) { log.warn("Scheduling terminated due to exception", t); t.printStackTrace(); } } /** * Reschedule all jobs with JobStatus SUBMITTED. */ private void rescheduleJobs() { final JobDAO dao = JobDAO.getInstance(); final Iterator<Long> jobs = dao.getAllJobIds(JobStatus.SUBMITTED); int resubmitcount = 0; while (jobs.hasNext()) { long oldID = jobs.next(); long newID = dao.rescheduleJob(oldID); log.info("Resubmitting old job " + oldID + " as " + newID); resubmitcount++; } log.info(resubmitcount + " has been resubmitted."); } /** * Stop any job that has been in status STARTED a very long time defined * by the HarvesterSettings.JOB_TIMEOUT_TIME setting * */ private void stopTimeoutJobs() { final JobDAO dao = JobDAO.getInstance(); final Iterator<Long> jobs = dao.getAllJobIds(JobStatus.STARTED); int stoppedJobs = 0; while (jobs.hasNext()) { long id = jobs.next(); Job job = dao.read(id); long timeDiff = Settings.getLong(HarvesterSettings.JOB_TIMEOUT_TIME); Date endTime = new Date(); endTime.setTime(job.getActualStart().getTime() + timeDiff); if (new Date().after(endTime)) { final String msg = " Job " + id + " has exceeded its timeout of " + Settings.getLong(HarvesterSettings.JOB_TIMEOUT_TIME) + " minutes. Its status has now been changed to " + "FAILED."; log.warn(msg); job.setStatus(JobStatus.FAILED); dao.update(job); stoppedJobs++; job.appendHarvestErrors(msg); } } log.warn("Changed " + stoppedJobs + " jobs from STARTED to FAILED"); } /** * Schedule all jobs ready for execution and perform backup if required. */ private void scheduleJobs() { synchronized (this) { if (running) { log.debug("Previous scheduleJobs not finished, " + "skipping new one."); return; } running = true; } if (backupNow()) { // Check if we want to backup the database now? File backupDir = new File("DB-Backup-" + System.currentTimeMillis()); try { DBSpecifics.getInstance().backupDatabase(backupDir); lastBackupDate = new Date(); } catch (SQLException e) { String errMsg = "Unable to backup database to dir: " + backupDir + "\n"+ ExceptionUtils.getSQLExceptionCause(e); log.warn(errMsg, e); NotificationsFactory.getInstance().errorEvent( errMsg, e); } } try { final HarvestDefinitionDAO hddao = HarvestDefinitionDAO.getInstance(); hddao.generateJobs(new Date()); submitNewJobs(); } finally { synchronized (this) { running = false; } } } /** * Is it now time to backup the database? * Check that no jobs are being generated, that we backup as soon as * possible if backup is behind schedule, that we don't backup several * times in an hour, and that the first backup is done at the right time. * @return true, if it is now time to backup the database */ private boolean backupNow() { // Never backup while making jobs if (HarvestDefinitionDAO.getInstance().isGeneratingJobs()) { return false; } Calendar cal = Calendar.getInstance(); boolean isBackupHour = (cal.get(Calendar.HOUR_OF_DAY) == backupInitHour); if (lastBackupDate != null) { int hoursPassed = getHoursPassedSince(lastBackupDate); if (hoursPassed < 1) { return false; // Never backup if it's been done within an hour } else if (hoursPassed > 25) { return true; // Backup at any time if we're behind schedule } } return isBackupHour; } /** * Find the number of hours passed since argument theDate. * returns -1, if number of hours passed since theDate is negative. * @param theDate the date compared to current time. * @return the number of hours passed since argument theDate */ private int getHoursPassedSince(Date theDate){ Calendar currentCal = Calendar.getInstance(); Calendar theDateCal = Calendar.getInstance(); theDateCal.setTime(theDate); long millisecondsPassed = currentCal.getTimeInMillis() - theDateCal.getTimeInMillis(); if (millisecondsPassed < 0) { return -1; } int secondsPassed = (int) (millisecondsPassed / 1000L); return (secondsPassed / 3600); } /** Submit those jobs that are ready for submission. */ private synchronized void submitNewJobs() { final JobDAO dao = JobDAO.getInstance(); Iterator<Long> jobsToSubmit = dao.getAllJobIds(JobStatus.NEW); if (!jobsToSubmit.hasNext()) { log.trace("No jobs to be run at this time"); } else { log.trace("Submitting new jobs."); } int i = 0; while (jobsToSubmit.hasNext()) { final long jobID = jobsToSubmit.next(); Job jobToSubmit = null; try { jobToSubmit = dao.read(jobID); jobToSubmit.setStatus(JobStatus.SUBMITTED); jobToSubmit.setSubmittedDate(new Date()); dao.update(jobToSubmit); //Add alias metadata List<MetadataEntry> metadata = new ArrayList<MetadataEntry>(); MetadataEntry aliasMetadataEntry = MetadataEntry.makeAliasMetadataEntry( jobToSubmit.getJobAliasInfo(), jobToSubmit.getOrigHarvestDefinitionID(), jobToSubmit.getHarvestNum(), jobToSubmit.getJobID()); if (aliasMetadataEntry != null) { metadata.add(aliasMetadataEntry); } //Add jobid metadata MetadataEntry duplicateReductionMetadataEntry = MetadataEntry.makeDuplicateReductionMetadataEntry( dao.getJobIDsForDuplicateReduction(jobID), jobToSubmit.getOrigHarvestDefinitionID(), jobToSubmit.getHarvestNum(), jobToSubmit.getJobID() ); if (duplicateReductionMetadataEntry != null) { metadata.add(duplicateReductionMetadataEntry); } hcc.doOneCrawl(jobToSubmit, metadata); log.trace("Job " + jobToSubmit + " sent to harvest queue."); } catch (Throwable e) { String message = "Error while scheduling job " + jobID; log.warn(message, e); if (jobToSubmit != null) { jobToSubmit.setStatus(JobStatus.FAILED); jobToSubmit.appendHarvestErrors(message); jobToSubmit.appendHarvestErrorDetails( ExceptionUtils.getStackTrace(e)); dao.update(jobToSubmit); } } } if (i > 0) { log.info("Submitted " + i + " jobs for harvesting"); } } /** * Release allocated resources (JMS connections), stop scheduling harvests, * and nullify the singleton. */ public void close() { log.debug("HarvestScheduler closing down."); cleanup(); log.trace("HarvestScheduler now closed"); } /** * Release allocated resources (JMS connections), stop scheduling harvests, * and nullify the singleton, all without logging. * @see CleanupIF#cleanup() */ public void cleanup() { if (timer != null) { synchronized (timer) { timer.cancel(); } } timer = null; if (hcc != null) { hcc.close(); hcc = null; } if (hsmon != null) { hsmon.cleanup(); } hsmon = null; instance = null; } }
package jp.fujiu.TweetNicoMovieForQuerychan; import java.io.IOException; import java.util.Random; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.StringEscapeUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; public class App { private static final String TWITTER4J_DEBUG = "Twitter4jDebug"; private static final String TWITTER_API_KEY = "TwitterApiKey"; private static final String TWITTER_SECRET_KEY = "TwitterSecretKey"; private static final String TWITTER_ACCESS_TOKEN = "TwitterAccessToken"; private static final String TWITTER_ACCESS_SECRET = "TwitterAccessSecret"; public static void main(String[] args) { System.out.println("start : " + App.class.getName()); final String envEnabled = "ApplicationEnabled"; String[] requiredEnvVariables = { envEnabled, TWITTER_API_KEY, TWITTER_SECRET_KEY, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET, }; for (String value : requiredEnvVariables) { if (System.getenv(value) == null) { System.out.printf("Environment variable %1$s is nothing\n", value); return; } } // (Bluemixjar). boolean doTweet = System.getenv(envEnabled).equalsIgnoreCase("true"); if (doTweet == false) { System.out.printf("ENV '%1$s' is not 'true', so main tweet will not be posted.\n", envEnabled); } try { TweetQuerychanMovie(doTweet); } catch (TwitterException e) { e.printStackTrace(); return; } } private static void TweetQuerychanMovie(boolean doTweet) throws TwitterException { final String TWITTER_SCREEN_NAME = "@mtk_f"; final String TWEET_TAG = " final String URL = "http://api.search.nicovideo.jp/api/"; final String QUERY = "mmd "; final String postContent = String.format( "{\"query\":\"%1$s\",\"service\":[\"video\"],\"search\":[\"title\",\"description\",\"tags\"],\"join\":[\"cmsid\",\"title\",\"description\",\"thumbnail_url\",\"start_time\",\"view_counter\",\"comment_counter\",\"mylist_counter\",\"channel_id\",\"main_community_id\",\"length_seconds\",\"last_res_body\"],\"filters\":[],\"sort_by\":\"start_time\",\"order\":\"desc\",\"from\":0,\"size\":25,\"timeout\":10000,\"issuer\":\"pc\",\"reason\":\"user\"}", QUERY); // API. ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled("true".equalsIgnoreCase(System.getenv(TWITTER4J_DEBUG))) .setOAuthConsumerKey(System.getenv(TWITTER_API_KEY)) .setOAuthConsumerSecret(System.getenv(TWITTER_SECRET_KEY)) .setOAuthAccessToken(System.getenv(TWITTER_ACCESS_TOKEN)) .setOAuthAccessTokenSecret(System.getenv(TWITTER_ACCESS_SECRET)); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); // nicovideo.jpJSON. String rawJson; Client client = Client.create(); WebResource webResource = client.resource(URL); rawJson = webResource.type(MediaType.APPLICATION_JSON_TYPE).post(String.class, postContent); client.getExecutorService().shutdown(); // 2JSON. int cr2ndPosition = -1; for (int i = 0; i < 2; i++) { cr2ndPosition = rawJson.indexOf("\n", cr2ndPosition) + 1; if (cr2ndPosition == 0) { System.out.println(rawJson); String msg = String.format("%1$s %2$s %3$s", TWITTER_SCREEN_NAME, "JSON \\n error", TWEET_TAG); twitter.updateStatus(msg); return; } } int cr3drPosition = rawJson.indexOf("\n", cr2ndPosition); if (cr3drPosition == -1) { System.out.println(rawJson); String msg = String.format("%1$s %2$s %3$s", TWITTER_SCREEN_NAME, "JSON \\n error", TWEET_TAG); twitter.updateStatus(msg); return; } String json2ndLine = rawJson.substring(cr2ndPosition, cr3drPosition); // JSON. ObjectMapper mapper = new ObjectMapper(); try { JsonDefinition response = mapper.readValue(json2ndLine, JsonDefinition.class); if (response.values != null) { Random random = new Random(); int index = random.nextInt(response.values.length); JsonDefinitionValue value = response.values[index]; final int maxLength = 50; String title = value.title.length() < maxLength ? value.title : value.title.substring(0, maxLength) + "..."; String msg = String.format( " %1$s \n" + "%2$s\n" + "http: + "%4$s", QUERY, StringEscapeUtils.unescapeHtml4(title), value.cmsid, TWEET_TAG); System.out.println(msg); if (doTweet) { twitter.updateStatus(msg); } } else { String msg = String.format("%1$s %2$s %3$s", TWITTER_SCREEN_NAME, "response.values was null", TWEET_TAG); twitter.updateStatus(msg); return; } } catch (IOException e) { e.printStackTrace(); String msg = String.format("%1$s %2$s %3$s", TWITTER_SCREEN_NAME, e.getMessage(), TWEET_TAG); twitter.updateStatus(msg); return; } } }
package leetcode191_200; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class BinaryTreeRightSideView { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //Core idea: 1.Each depth of the tree only select one node. 2.View depth is current size of result list. public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); rightView(root, result, 0); return result; } public void rightView(TreeNode curr, List<Integer> result, int currDepth){ if(curr == null) return; if(currDepth == result.size()) result.add(curr.val); rightView(curr.right, result, currDepth + 1); rightView(curr.left, result, currDepth + 1); } public List<Integer> rightSideView1(TreeNode root) { ArrayList<Integer> result = new ArrayList<>(); if(root == null) return result; LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(root); while(queue.size()>0){ int size = queue.size(); //get size here for(int i=0; i<size; i++){ TreeNode top = queue.remove(); if(i==0) result.add(top.val); //the first element in the queue (right-most of the tree) if(top.right!=null) queue.add(top.right); if(top.left!=null) queue.add(top.left); } } return result; } public List<Integer> rightSideView2(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root==null) return result; Queue<TreeNode> q = new LinkedList<>(); Queue<TreeNode> qNext = new LinkedList<>(); q.offer(root); while (!q.isEmpty()){ TreeNode n = q.poll(); if (n.left!=null) qNext.offer(n.left); if (n.right!=null) qNext.offer(n.right); if (q.isEmpty()){ result.add(n.val); if (!qNext.isEmpty()){ q = new LinkedList<>(qNext); qNext = new LinkedList<>(); } } } return result; } }
package mho.wheels.iterables; import mho.wheels.math.Combinatorics; import mho.wheels.math.MathUtils; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.ordering.Ordering; import mho.wheels.structures.*; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * An {@code ExhaustiveProvider} produces {@code Iterable}s that generate some set of values in a specified order. * There is only a single instance of this class. */ @SuppressWarnings("ConstantConditions") public final class ExhaustiveProvider extends IterableProvider { /** * The single instance of this class. */ public static final ExhaustiveProvider INSTANCE = new ExhaustiveProvider(); /** * The transition between algorithms for generating lists of values. If the number of values is less than or equal * to this value, we use lexicographic ordering; otherwise, Z-curve ordering. */ private static final int MAX_SIZE_FOR_SHORT_LIST_ALG = 5; /** * Disallow instantiation */ private ExhaustiveProvider() {} /** * A {@link List} that contains both {@link boolean}s. * * Length is 2 */ @Override public @NotNull List<Boolean> booleans() { return Arrays.asList(false, true); } /** * A {@code List} that contains all {@link Ordering}s in increasing order. * * Length is 3 * * @return the {@code List} described above. */ public @NotNull List<Ordering> orderingsIncreasing() { return Arrays.asList(LT, EQ, GT); } /** * A {@code List} that contains all {@code Ordering}s. * * Length is 3 */ @Override public @NotNull List<Ordering> orderings() { return Arrays.asList(EQ, LT, GT); } /** * A {@code List} that contains all {@link RoundingMode}s. * * Length is 8 */ @Override public @NotNull List<RoundingMode> roundingModes() { return Arrays.asList( RoundingMode.UNNECESSARY, RoundingMode.UP, RoundingMode.DOWN, RoundingMode.CEILING, RoundingMode.FLOOR, RoundingMode.HALF_UP, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN ); } @Override public @NotNull Iterable<Byte> rangeUp(byte a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return mux(Arrays.asList(IterableUtils.rangeUp((byte) 0), IterableUtils.rangeBy((byte) -1, (byte) -1, a))); } } @Override public @NotNull Iterable<Short> rangeUp(short a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return mux( Arrays.asList(IterableUtils.rangeUp((short) 0), IterableUtils.rangeBy((short) -1, (short) -1, a)) ); } } @Override public @NotNull Iterable<Integer> rangeUp(int a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return mux(Arrays.asList(IterableUtils.rangeUp(0), IterableUtils.rangeBy(-1, -1, a))); } } @Override public @NotNull Iterable<Long> rangeUp(long a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return mux(Arrays.asList(IterableUtils.rangeUp(0L), IterableUtils.rangeBy(-1L, -1L, a))); } } /** * An {@code Iterable} that generates all {@code BigIntegers}s greater than or equal to {@code a}. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigInteger}s.</li> * </ul> * * Length is infinite * * @param a the inclusive lower bound of the generated elements * @return {@code BigInteger}s greater than or equal to {@code a} */ @Override public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) { if (a.signum() != -1) { return IterableUtils.rangeUp(a); } else { return mux( Arrays.asList( IterableUtils.rangeUp(BigInteger.ZERO), IterableUtils.rangeBy(BigInteger.valueOf(-1), BigInteger.valueOf(-1), a) ) ); } } @Override public @NotNull Iterable<Character> rangeUp(char a) { return IterableUtils.rangeUp(a); } @Override public @NotNull Iterable<Byte> rangeDown(byte a) { if (a <= 0) { return IterableUtils.rangeBy(a, (byte) -1); } else { return mux(Arrays.asList(IterableUtils.range((byte) 0, a), IterableUtils.rangeBy((byte) -1, (byte) -1))); } } @Override public @NotNull Iterable<Short> rangeDown(short a) { if (a <= 0) { return IterableUtils.rangeBy(a, (short) -1); } else { return mux( Arrays.asList(IterableUtils.range((short) 0, a), IterableUtils.rangeBy((short) -1, (short) -1)) ); } } @Override public @NotNull Iterable<Integer> rangeDown(int a) { if (a <= 0) { return IterableUtils.rangeBy(a, -1); } else { return mux(Arrays.asList(IterableUtils.range(0, a), IterableUtils.rangeBy(-1, -1))); } } @Override public @NotNull Iterable<Long> rangeDown(long a) { if (a <= 0) { return IterableUtils.rangeBy(a, -1L); } else { return mux(Arrays.asList(IterableUtils.range(0L, a), IterableUtils.rangeBy(-1L, -1L))); } } @Override public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) { if (a.signum() != 1) { return IterableUtils.rangeBy(a, BigInteger.valueOf(-1)); } else { return mux(Arrays.asList(IterableUtils.range(BigInteger.ZERO, a), IterableUtils.rangeBy(BigInteger.valueOf(-1), BigInteger.valueOf(-1)))); } } @Override public @NotNull Iterable<Character> rangeDown(char a) { return IterableUtils.range('\0', a); } @Override public @NotNull Iterable<Byte> range(byte a, byte b) { if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (byte) -1, a); } else { return mux( Arrays.asList(IterableUtils.range((byte) 0, b), IterableUtils.rangeBy((byte) -1, (byte) -1, a)) ); } } @Override public @NotNull Iterable<Short> range(short a, short b) { if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (short) -1, a); } else { return mux( Arrays.asList(IterableUtils.range((short) 0, b), IterableUtils.rangeBy((short) -1, (short) -1, a)) ); } } @Override public @NotNull Iterable<Integer> range(int a, int b) { if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, -1, a); } else { return mux(Arrays.asList(IterableUtils.range(0, b), IterableUtils.rangeBy(-1, -1, a))); } } public @NotNull Iterable<Long> range(long a, long b) { if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (byte) -1, a); } else { return mux(Arrays.asList(IterableUtils.range(0L, b), IterableUtils.rangeBy(-1L, -1L, a))); } } @Override public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) { if (a.signum() != -1 && b.signum() != -1) { return IterableUtils.range(a, b); } else if (a.signum() == -1 && b.signum() == -1) { return IterableUtils.rangeBy(b, BigInteger.valueOf(-1), a); } else { return mux( Arrays.asList( IterableUtils.range(BigInteger.ZERO, b), IterableUtils.rangeBy(BigInteger.valueOf(-1), BigInteger.valueOf(-1), a) ) ); } } @Override public @NotNull Iterable<Character> range(char a, char b) { return IterableUtils.range(a, b); } @Override public @NotNull <T> List<T> uniformSample(@NotNull List<T> xs) { return xs; } @Override public @NotNull Iterable<Character> uniformSample(@NotNull String s) { return fromString(s); } /** * An {@code Iterable} that contains all {@link Byte}s in increasing order. Does not support removal. * * Length is 2<sup>8</sup> = 256 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Byte> bytesIncreasing() { return IterableUtils.rangeUp(Byte.MIN_VALUE); } /** * An {@code Iterable} that contains all {@link Short}s in increasing order. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Short> shortsIncreasing() { return IterableUtils.rangeUp(Short.MIN_VALUE); } /** * An {@code Iterable} that contains all {@link Integer}s in increasing order. Does not support removal. * * Length is 2<sup>32</sup> = 4,294,967,296 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Integer> integersIncreasing() { return IterableUtils.rangeUp(Integer.MIN_VALUE); } /** * An {@code Iterable} that contains all {@link Long}s in increasing order. Does not support removal. * * Length is 2<sup>64</sup> = 18,446,744,073,709,551,616 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Long> longsIncreasing() { return IterableUtils.rangeUp(Long.MIN_VALUE); } @Override public @NotNull Iterable<Byte> positiveBytes() { return IterableUtils.rangeUp((byte) 1); } @Override public @NotNull Iterable<Short> positiveShorts() { return IterableUtils.rangeUp((short) 1); } @Override public @NotNull Iterable<Integer> positiveIntegers() { return IterableUtils.rangeUp(1); } @Override public @NotNull Iterable<Long> positiveLongs() { return IterableUtils.rangeUp(1L); } /** * An {@code Iterable} that contains all positive {@link BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> positiveBigIntegers() { return IterableUtils.rangeUp(BigInteger.ONE); } /** * An {@code Iterable} that contains all negative {@code Byte}s. Does not support removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Byte> negativeBytes() { return IterableUtils.rangeBy((byte) -1, (byte) -1); } /** * An {@code Iterable} that contains all negative {@code Short}s. Does not support removal. * * Length is 2<sup>15</sup> = 32,768 */ @Override public @NotNull Iterable<Short> negativeShorts() { return IterableUtils.rangeBy((short) -1, (short) -1); } /** * An {@code Iterable} that contains all negative {@code Integer}s. Does not support removal. * * Length is 2<sup>31</sup> = 2,147,483,648 */ @Override public @NotNull Iterable<Integer> negativeIntegers() { return IterableUtils.rangeBy(-1, -1); } /** * An {@code Iterable} that contains all negative {@code Long}s. Does not support removal. * * Length is 2<sup>63</sup> = 9,223,372,036,854,775,808 */ @Override public @NotNull Iterable<Long> negativeLongs() { return IterableUtils.rangeBy(-1L, -1L); } /** * An {@code Iterable} that contains all negative {@code BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> negativeBigIntegers() { return IterableUtils.rangeBy(BigInteger.valueOf(-1), BigInteger.valueOf(-1)); } /** * An {@code Iterable} that contains all natural {@code Byte}s. Does not support removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Byte> naturalBytes() { return IterableUtils.rangeUp((byte) 0); } /** * An {@code Iterable} that contains all natural {@code Short}s (including 0). Does not support removal. * * Length is 2<sup>15</sup> = 32,768 */ @Override public @NotNull Iterable<Short> naturalShorts() { return IterableUtils.rangeUp((short) 0); } /** * An {@code Iterable} that contains all natural {@code Integer}s (including 0). Does not support removal. * * Length is 2<sup>31</sup> = 2,147,483,648 */ @Override public @NotNull Iterable<Integer> naturalIntegers() { return IterableUtils.rangeUp(0); } /** * An {@code Iterable} that contains all natural {@code Long}s (including 0). Does not support removal. * * Length is 2<sup>63</sup> = 9,223,372,036,854,775,808 */ @Override public @NotNull Iterable<Long> naturalLongs() { return IterableUtils.rangeUp(0L); } /** * An {@code Iterable} that contains all natural {@code BigInteger}s (including 0). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> naturalBigIntegers() { return rangeUp(BigInteger.ZERO); } /** * An {@code Iterable} that contains all {@code Byte}s. Does not support removal. * * Length is 2<sup>8</sup> = 128 */ @Override public @NotNull Iterable<Byte> bytes() { return cons((byte) 0, mux(Arrays.asList(positiveBytes(), negativeBytes()))); } /** * An {@code Iterable} that contains all {@code Short}s. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Short> shorts() { return cons((short) 0, mux(Arrays.asList(positiveShorts(), negativeShorts()))); } /** * An {@code Iterable} that contains all {@code Integer}s. Does not support removal. * * Length is 2<sup>32</sup> = 4,294,967,296 */ @Override public @NotNull Iterable<Integer> integers() { return cons(0, mux(Arrays.asList(positiveIntegers(), negativeIntegers()))); } /** * An {@code Iterable} that contains all {@code Long}s. Does not support removal. * * Length is 2<sup>64</sup> = 18,446,744,073,709,551,616 */ @Override public @NotNull Iterable<Long> longs() { return cons(0L, mux(Arrays.asList(positiveLongs(), negativeLongs()))); } /** * An {@code Iterable} that contains all {@code BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> bigIntegers() { return cons(BigInteger.ZERO, mux(Arrays.asList(positiveBigIntegers(), negativeBigIntegers()))); } /** * An {@code Iterable} that contains all ASCII {@link Character}s in increasing order. Does not support * removal. * * Length is 2<sup>7</sup> = 128 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Character> asciiCharactersIncreasing() { return range((char) 0, (char) 127); } /** * An {@code Iterable} that contains all ASCII {@code Character}s in an order which places "friendly" characters * first. Does not support removal. * * Length is 2<sup>7</sup> = 128 * * @return the {@code Iterable} described above. */ @Override public @NotNull Iterable<Character> asciiCharacters() { return concat(Arrays.asList( range('a', 'z'), range('A', 'Z'), range('0', '9'), range('!', '/'), // printable non-alphanumeric ASCII... range(':', '@'), range('[', '`'), range('{', '~'), range((char) 0, (char) 32), // non-printable and whitespace ASCII Arrays.asList((char) 127) // DEL )); } /** * An {@code Iterable} that contains all {@code Character}s in increasing order. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 * * @return the {@code Iterable} described above. */ public @NotNull Iterable<Character> charactersIncreasing() { return range(Character.MIN_VALUE, Character.MAX_VALUE); } /** * An {@code Iterable} that contains all {@code Character}s in an order which places "friendly" characters * first. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Character> characters() { return concat(Arrays.asList( range('a', 'z'), range('A', 'Z'), range('0', '9'), range('!', '/'), // printable non-alphanumeric ASCII... range(':', '@'), range('[', '`'), range('{', '~'), range((char) 0, (char) 32), // non-printable and whitespace ASCII rangeUp((char) 127) // DEL and non-ASCII )); } public @NotNull Iterable<Float> positiveOrdinaryFloatsIncreasing() { return stopAt(f -> f == Float.MAX_VALUE, iterate(FloatingPointUtils::successor, Float.MIN_VALUE)); } public @NotNull Iterable<Float> negativeOrdinaryFloatsIncreasing() { return stopAt(f -> f == -Float.MIN_VALUE, iterate(FloatingPointUtils::successor, -Float.MAX_VALUE)); } public @NotNull Iterable<Float> ordinaryFloatsIncreasing() { //noinspection RedundantCast return concat((Iterable<Iterable<Float>>) Arrays.asList( stopAt(f -> f == -Float.MIN_VALUE, iterate(FloatingPointUtils::successor, -Float.MAX_VALUE)), Arrays.asList(0.0f), stopAt(f -> f == Float.MAX_VALUE, iterate(FloatingPointUtils::successor, Float.MIN_VALUE)) )); } public @NotNull Iterable<Float> floatsIncreasing() { //noinspection RedundantCast return concat((Iterable<Iterable<Float>>) Arrays.asList( stopAt(f -> f == -Float.MIN_VALUE, iterate(FloatingPointUtils::successor, Float.NEGATIVE_INFINITY)), Arrays.asList(-0.0f, Float.NaN, 0.0f), stopAt(f -> f == Float.POSITIVE_INFINITY, iterate(FloatingPointUtils::successor, Float.MIN_VALUE)) )); } /** * An {@code Iterable} that contains all possible positive {@code float} mantissas. A {@code float}'s mantissa is * the unique odd integer that, when multiplied by a power of 2, equals the {@code float}. Does not support * removal. * * Length is 2<sup>23</sup> = 8,388,608 */ private static final @NotNull Iterable<Integer> FLOAT_MANTISSAS = IterableUtils.rangeBy(1, 2, 1 << 24); private static final @NotNull Iterable<Integer> FLOAT_EXPONENTS = cons( 0, mux(Arrays.asList(INSTANCE.range(1, 127), IterableUtils.rangeBy(-1, -1, -149))) ); @Override public @NotNull Iterable<Float> positiveOrdinaryFloats() { return map( Optional::get, filter( Optional::isPresent, map(p -> FloatingPointUtils.floatFromME(p.a, p.b), pairs(FLOAT_MANTISSAS, FLOAT_EXPONENTS)) ) ); } @Override public @NotNull Iterable<Float> negativeOrdinaryFloats() { return map(f -> -f, positiveOrdinaryFloats()); } @Override public @NotNull Iterable<Float> ordinaryFloats() { return cons(0.0f, mux(Arrays.asList(positiveOrdinaryFloats(), negativeOrdinaryFloats()))); } @Override public @NotNull Iterable<Float> floats() { return concat( Arrays.asList(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0f, -0.0f), tail(ordinaryFloats()) ); } public @NotNull Iterable<Double> positiveOrdinaryDoublesIncreasing() { return stopAt(d -> d == Double.MAX_VALUE, iterate(FloatingPointUtils::successor, Double.MIN_VALUE)); } public @NotNull Iterable<Double> negativeOrdinaryDoublesIncreasing() { return stopAt(d -> d == -Double.MIN_VALUE, iterate(FloatingPointUtils::successor, -Double.MAX_VALUE)); } public @NotNull Iterable<Double> ordinaryDoublesIncreasing() { //noinspection RedundantCast return concat((Iterable<Iterable<Double>>) Arrays.asList( stopAt(d -> d == -Double.MIN_VALUE, iterate(FloatingPointUtils::successor, -Double.MAX_VALUE)), Arrays.asList(0.0), stopAt(d -> d == Double.MAX_VALUE, iterate(FloatingPointUtils::successor, Double.MIN_VALUE)) )); } public @NotNull Iterable<Double> doublesIncreasing() { //noinspection RedundantCast return concat((Iterable<Iterable<Double>>) Arrays.asList( stopAt(d -> d == -Double.MIN_VALUE, iterate(FloatingPointUtils::successor, Double.NEGATIVE_INFINITY)), Arrays.asList(-0.0, Double.NaN, 0.0), stopAt(d -> d == Double.POSITIVE_INFINITY, iterate(FloatingPointUtils::successor, Double.MIN_VALUE)) )); } /** * An {@code Iterable} that contains all possible positive {@code double} mantissas. A {@code double}'s mantissa is * the unique odd integer that, when multiplied by a power of 2, equals the {@code double}. Does not support * removal. * * Length is 2<sup>52</sup> = 4,503,599,627,370,496 */ private static final @NotNull Iterable<Long> DOUBLE_MANTISSAS = IterableUtils.rangeBy(1L, 2, 1L << 53); private static final @NotNull Iterable<Integer> DOUBLE_EXPONENTS = cons( 0, mux(Arrays.asList(INSTANCE.range(1, 1023), IterableUtils.rangeBy(-1, -1, -1074))) ); @Override public @NotNull Iterable<Double> positiveOrdinaryDoubles() { return map( Optional::get, filter( Optional::isPresent, map(p -> FloatingPointUtils.doubleFromME(p.a, p.b), pairs(DOUBLE_MANTISSAS, DOUBLE_EXPONENTS)) ) ); } @Override public @NotNull Iterable<Double> negativeOrdinaryDoubles() { return map(d -> -d, positiveOrdinaryDoubles()); } @Override public @NotNull Iterable<Double> ordinaryDoubles() { return cons(0.0, mux(Arrays.asList(positiveOrdinaryDoubles(), negativeOrdinaryDoubles()))); } @Override public @NotNull Iterable<Double> doubles() { return concat( Arrays.asList(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0, -0.0), tail(ordinaryDoubles()) ); } /** * An {@code Iterable} that contains all positive {@link BigDecimal}s. Does not support removal. * * Length is infinite */ public @NotNull Iterable<BigDecimal> positiveBigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(positiveBigIntegers(), integers())); } /** * An {@code Iterable} that contains all negative {@code BigDecimal}s. Does not support removal. * * Length is infinite */ public @NotNull Iterable<BigDecimal> negativeBigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(negativeBigIntegers(), integers())); } /** * An {@code Iterable} that contains all {@code BigDecimal}s. Does not support removal. * * Length is infinite */ public @NotNull Iterable<BigDecimal> bigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(bigIntegers(), integers())); } @Override public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) { return cons(null, xs); } @Override public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) { return cons(Optional.<T>empty(), map(Optional::of, xs)); } @Override public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) { return cons(NullableOptional.<T>empty(), map(NullableOptional::of, xs)); } /** * See {@link mho.wheels.math.Combinatorics#pairsLogarithmicOrder(Iterable)} * * @param xs the {@code Iterable} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all pairs of elements from {@code xs} in logarithmic order */ @Override public @NotNull <T> Iterable<Pair<T, T>> pairsLogarithmicOrder(@NotNull Iterable<T> xs) { return Combinatorics.pairsLogarithmicOrder(xs); } /** * See {@link mho.wheels.math.Combinatorics#pairsLogarithmicOrder(Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the pairs are selected * @param bs the {@code Iterable} from which the second components of the pairs are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all pairs of elements from {@code as} and {@code bs} in logarithmic order */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairsLogarithmicOrder( @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { return Combinatorics.pairsLogarithmicOrder(as, bs); } /** * See {@link mho.wheels.math.Combinatorics#pairsSquareRootOrder(Iterable)} * * @param xs the {@code Iterable} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all pairs of elements from {@code xs} in square-root order */ @Override public @NotNull <T> Iterable<Pair<T, T>> pairsSquareRootOrder(@NotNull Iterable<T> xs) { return Combinatorics.pairsSquareRootOrder(xs); } /** * See {@link mho.wheels.math.Combinatorics#pairsSquareRootOrder(Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the pairs are selected * @param bs the {@code Iterable} from which the second components of the pairs are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all pairs of elements from {@code as} and {@code bs} in square-root order */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairsSquareRootOrder( @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { return Combinatorics.pairsSquareRootOrder(as, bs); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairs( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, f, (BigInteger i) -> { List<BigInteger> list = MathUtils.demux(2, i); return new Pair<>(list.get(0), list.get(1)); } ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsLogarithmic( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, f, MathUtils::logarithmicDemux ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsSquareRoot( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, f, MathUtils::squareRootDemux ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsExponential( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, f, i -> { Pair<BigInteger, BigInteger> p = MathUtils.logarithmicDemux(i); return new Pair<>(p.b, p.a); } ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsSquare( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, f, i -> { Pair<BigInteger, BigInteger> p = MathUtils.squareRootDemux(i); return new Pair<>(p.b, p.a); } ); } /** * See {@link mho.wheels.math.Combinatorics#pairs(Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the pairs are selected * @param bs the {@code Iterable} from which the second components of the pairs are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all pairs of elements from {@code as} and {@code bs} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) { return Combinatorics.pairs(as, bs); } /** * See {@link mho.wheels.math.Combinatorics#triples(Iterable, Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the triples are selected * @param bs the {@code Iterable} from which the second components of the triples are selected * @param cs the {@code Iterable} from which the third components of the triples are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @return all triples of elements from {@code as}, {@code bs}, and {@code cs} */ @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 Combinatorics.triples(as, bs, cs); } /** * See {@link mho.wheels.math.Combinatorics#quadruples(Iterable, Iterable, Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the quadruples are selected * @param bs the {@code Iterable} from which the second components of the quadruples are selected * @param cs the {@code Iterable} from which the third components of the quadruples are selected * @param ds the {@code Iterable} from which the fourth components of the quadruples are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @return all quadruples of elements from {@code as}, {@code bs}, {@code cs}, and {@code ds} */ @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 Combinatorics.quadruples(as, bs, cs, ds); } /** * See {@link mho.wheels.math.Combinatorics#quintuples(Iterable, Iterable, Iterable, Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the quintuples are selected * @param bs the {@code Iterable} from which the second components of the quintuples are selected * @param cs the {@code Iterable} from which the third components of the quintuples are selected * @param ds the {@code Iterable} from which the fourth components of the quintuples are selected * @param es the {@code Iterable} from which the fifth components of the quintuples are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @return all quintuples of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, and {@code es} */ @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 Combinatorics.quintuples(as, bs, cs, ds, es); } /** * See {@link mho.wheels.math.Combinatorics#sextuples(Iterable, Iterable, Iterable, Iterable, Iterable, * Iterable)} * * @param as the {@code Iterable} from which the first components of the sextuples are selected * @param bs the {@code Iterable} from which the second components of the sextuples are selected * @param cs the {@code Iterable} from which the third components of the sextuples are selected * @param ds the {@code Iterable} from which the fourth components of the sextuples are selected * @param es the {@code Iterable} from which the fifth components of the sextuples are selected * @param fs the {@code Iterable} from which the sixth components of the sextuples are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @return all sextuples of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, {@code es}, and * {@code fs} */ @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 Combinatorics.sextuples(as, bs, cs, ds, es, fs); } /** * See {@link mho.wheels.math.Combinatorics#septuples(Iterable, Iterable, Iterable, Iterable, Iterable, * Iterable, Iterable)} * * @param as the {@code Iterable} from which the first components of the septuples are selected * @param bs the {@code Iterable} from which the second components of the septuples are selected * @param cs the {@code Iterable} from which the third components of the septuples are selected * @param ds the {@code Iterable} from which the fourth components of the septuples are selected * @param es the {@code Iterable} from which the fifth components of the septuples are selected * @param fs the {@code Iterable} from which the sixth components of the septuples are selected * @param gs the {@code Iterable} from which the seventh components of the septuples are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @param <G> the type of the seventh {@code Iterable}'s elements * @return all septuples of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, {@code es}, * {@code fs}, and {@code gs} */ @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 Combinatorics.septuples(as, bs, cs, ds, es, fs, gs); } @Override public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) { return Combinatorics.pairs(xs); } @Override public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) { return Combinatorics.triples(xs); } @Override public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) { return Combinatorics.quadruples(xs); } @Override public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) { return Combinatorics.quintuples(xs); } @Override public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) { return Combinatorics.sextuples(xs); } @Override public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) { return Combinatorics.septuples(xs); } @Override public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) { if (length(take(MAX_SIZE_FOR_SHORT_LIST_ALG + 1, xs)) < MAX_SIZE_FOR_SHORT_LIST_ALG + 1) { return Combinatorics.listsIncreasing(size, xs); } else { return Combinatorics.lists(size, xs); } } @Override public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) { if (length(take(MAX_SIZE_FOR_SHORT_LIST_ALG + 1, xs)) < MAX_SIZE_FOR_SHORT_LIST_ALG + 1) { return Combinatorics.listsShortlexAtLeast(minSize, xs); } else { return Combinatorics.listsAtLeast(minSize, xs); } } @Override public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) { if (length(take(MAX_SIZE_FOR_SHORT_LIST_ALG + 1, xs)) < MAX_SIZE_FOR_SHORT_LIST_ALG + 1) { return Combinatorics.listsShortlex(xs); } else { return Combinatorics.lists(xs); } } @Override public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) { return Combinatorics.strings(size, cs); } @Override public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) { return Combinatorics.stringsAtLeast(minSize, cs); } @Override public @NotNull Iterable<String> strings(int size) { return Combinatorics.strings(size, characters()); } @Override public @NotNull Iterable<String> stringsAtLeast(int minSize) { return Combinatorics.stringsAtLeast(minSize, characters()); } @Override public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) { return Combinatorics.strings(cs); } @Override public @NotNull Iterable<String> strings() { return Combinatorics.strings(characters()); } /** * Determines whether {@code this} is equal to {@code that}. This implementation is the same as in * {@link java.lang.Object#equals}, but repeated here for clarity. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code ExhaustiveProvider} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { return this == that; } /** * Calculates the hash code of {@code this}. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>The result is 0.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { return 0; } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>The result is {@code "ExhaustiveProvider"}.</li> * </ul> * * @return a {@code String} representation of {@code this} */ @Override public String toString() { return "ExhaustiveProvider"; } }
package net.bootsfaces.component; import java.io.IOException; import java.util.Map; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import net.bootsfaces.C; import net.bootsfaces.render.A; import net.bootsfaces.render.H; import net.bootsfaces.render.Tooltip; /** * * @author thecoder4eu */ @ResourceDependencies({ @ResourceDependency(library = "bsf", name = "css/core.css"), @ResourceDependency(library = "bsf", name = "css/tooltip.css", target = "head") }) public class LinksContainer extends UIComponentBase { /** * <p>The standard component type for this component.</p> */ public static final String COMPONENT_TYPE =C.BSFCOMPONENT+C.DOT+"LinksContainer"; /** * <p>The component family for this component.</p> */ public static final String COMPONENT_FAMILY = C.BSFCOMPONENT; public LinksContainer() { setRendererType(null); // this component renders itself Tooltip.addResourceFile(); } @Override public void encodeBegin(FacesContext fc) throws IOException { if (!isRendered()) { return; } /* * <ul class="?"> * ... * </ul> */ ResponseWriter rw = fc.getResponseWriter(); Map<String, Object> attrs = getAttributes(); String pull = A.asString(attrs.get(A.PULL)); rw.startElement(H.UL, this); rw.writeAttribute("id",getClientId(fc),"id"); String style = (String) attrs.get("style"); if (null != style && style.length()>0) { rw.writeAttribute("style", style, "style"); } Tooltip.generateTooltip(fc, attrs, rw); String styleClass = (String) attrs.get("styleClass"); if (null == styleClass) { styleClass=""; } if(pull!=null && (pull.equals(A.RIGHT) || pull.equals(A.LEFT)) ) { rw.writeAttribute("class", styleClass.concat(" ").concat(getContainerStyles()).concat(" ").concat(A.PULL).concat("-").concat(pull),"class"); } else { rw.writeAttribute("class", styleClass.concat(" ").concat(getContainerStyles()),"class"); } } /** * every container must override this method returning * the specific class(es) for its rendering * @return the specific class */ protected String getContainerStyles() { throw new UnsupportedOperationException("Please Extend this class."); } @Override public void encodeEnd(FacesContext fc) throws IOException { fc.getResponseWriter() .endElement(H.UL); Tooltip.activateTooltips(fc, getAttributes(), this); } @Override public String getFamily() { return COMPONENT_FAMILY; } }
package org.xins.util.service.ldap; /** * LDAP search request. Combines * {@link AuthenticationDetails authentication details} and a * {@link Query query}. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.115 */ final class Request extends Object { // Class fields // Class functions // Constructors /** * Constructs a new <code>Request</code> object. * * @param authenticationDetails * the authentication details, can be <code>null</code>. * * @param query * the query to be executed, can be <code>null</code>. */ Request(AuthenticationDetails authenticationDetails, Query query) { _authenticationDetails = authenticationDetails; _query = query; } // Fields /** * The authentication details. Can be <code>null</code>. */ private final AuthenticationDetails _authenticationDetails; /** * The query. Can be <code>null</code>. */ private final Query _query; // Methods /** * Returns the authentication details. * * @return * the authentication details, can be <code>null</code>. */ AuthenticationDetails getAuthenticationDetails() { return _authenticationDetails; } /** * Returns the query. * * @return * the qeury, can be <code>null</code>. */ Query getQuery() { return _query; } }
package net.databinder.components; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.InputStream; import wicket.Component; import wicket.Resource; import wicket.WicketRuntimeException; import wicket.markup.ComponentTag; import wicket.markup.html.image.Image; import wicket.markup.html.image.resource.RenderedDynamicImageResource; import wicket.model.ICompoundModel; import wicket.model.IModel; /** * Renders its model text into a PNG, using any typeface available to the JVM. The size of * the image is determined by the model text and the characteristics of font selected. The * default font is 14pt sans, plain black on a white background. The image's alt attribute * will be set to the model text. <p>This class is inspired by, and draws code from, Wicket's * DefaultButtonImageResource. </p> * @author Nathan Hamblen * @see wicket.markup.html.image.resource.DefaultButtonImageResource */ public class RenderedLabel extends Image { private Color backgroundColor = Color.WHITE; private Color color = Color.BLACK; private Font font = new Font("sans", Font.PLAIN, 14); private RenderedTextImageResource resource; /** * Constructor to be used if model is derived from a compound property model. The * model object <b>must</b> be a string. * @param id */ public RenderedLabel(String id) { super(id); setImageResource(resource = new RenderedTextImageResource()); } /** * Constructor with explicit model. The model object <b>must</b> be a string. * @param id Wicket id * @param model model for */ public RenderedLabel(String id, IModel model) { super(id, model); setImageResource(resource = new RenderedTextImageResource()); } /** Adds alt attribute for accessibility. */ @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("alt", getText()); } /** Restores compound model resolution that is disabled in the Image superclass. */ @Override protected IModel initModel() { // c&p'd from Component for (Component current = getParent(); current != null; current = current.getParent()) { final IModel model = current.getModel(); if (model instanceof ICompoundModel) { setVersioned(false); return model; } } return null; } /** * Inner class that renders the model text into an image resource. * @see wicket.markup.html.image.resource.DefaultButtonImageResource */ protected class RenderedTextImageResource extends RenderedDynamicImageResource { public RenderedTextImageResource() { super(10, 10,"png"); // tiny default that will resize to fit text } /** Renders text into image. */ protected boolean render(final Graphics2D graphics) { String text = getText(); // get text from outer class model final int width = getWidth(), height = getHeight(); // Fill background graphics.setColor(backgroundColor); graphics.fillRect(0, 0, width, height); if (text == null) return true; // no text? we're done here // Get size of text graphics.setFont(font); final FontMetrics fontMetrics = graphics.getFontMetrics(); final int dxText = fontMetrics.stringWidth(text); final int dyText = fontMetrics.getHeight(); if (dxText > width || dyText > height) { setWidth(dxText); setHeight(dyText); return false; } else { // Turn on anti-aliasing graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Draw text at baseline graphics.setColor(color); graphics.drawString(text, 0, fontMetrics.getAscent()); return true; } } } /** @return String to be rendered */ protected String getText() { try { return (String) getModelObject(); } catch (ClassCastException e) { throw new WicketRuntimeException("A RenderedLabel's model object MUST be a String.", e); } } public Color getBackgroundColor() { return backgroundColor; } public RenderedLabel setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; resource.invalidate(); return this; } public Color getColor() { return color; } /** @param color Color to print text */ public RenderedLabel setColor(Color color) { this.color = color; resource.invalidate(); return this; } public Font getFont() { return font; } public RenderedLabel setFont(Font font) { this.font = font; resource.invalidate(); return this; } /** * Utility method for creating Font objects from resources. * @param fontRes Resource containing a TrueType font descriptor. * @return Plain, 16pt font derived from the resource. */ public static Font fontForResource(Resource fontRes) { try { InputStream is = fontRes.getResourceStream().getInputStream(); Font font = Font.createFont(Font.TRUETYPE_FONT, is); is.close(); return font.deriveFont(Font.PLAIN, 16); } catch (Throwable e) { throw new WicketRuntimeException("Error loading font resources", e); } } }
package org.xins.server; import java.util.List; import java.util.StringTokenizer; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.text.ParseException; /** * Authorization filter for IP addresses. An <code>IPFilter</code> object is * created and used as follows: * * <blockquote><code>IPFilter filter = IPFilter.parseFilter("10.0.0.0/24"); * <br>if (filter.isAuthorized("10.0.0.1")) { * <br>&nbsp;&nbsp;&nbsp;// IP is granted access * <br>} else { * <br>&nbsp;&nbsp;&nbsp;// IP is denied access * <br>}</code></blockquote> * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * @author Peter Troon (<a href="mailto:peter.troon@nl.wanadoo.com">peter.troon@nl.wanadoo.com</a>) */ public final class IPFilter extends Object { // Class fields /** * The character that delimits the 4 sections of an IP address. */ private static final String IP_ADDRESS_DELIMETER = "."; // Class functions public static final IPFilter parseFilter(String expression) throws IllegalArgumentException, ParseException { MandatoryArgumentChecker.check("expression", expression); String ip = null; String mask = null; boolean validFilter = true; int slashPosition = expression.indexOf('/'); if (slashPosition < 0 || slashPosition == expression.length() - 1) { validFilter = false; } else { ip = expression.substring(0, slashPosition); } if (validFilter == true && isValidIp(ip) == false) { validFilter = false; } if (validFilter == true) { mask = expression.substring(slashPosition + 1); } if (validFilter == true && isValidMask(mask) == false) { validFilter = false; } if (validFilter == false) { throw new ParseException("The provided filter " + expression + " is invalid."); } return new IPFilter(expression); } // Constructors /** * Creates an <code>IPFilter</code> object for the specified filter * expression. The expression consists of a base IP address and a bit * count. The bit count indicates how many bits in an IP address must match * the bits in the base IP address. * * @param expression * the filter expression, cannot be <code>null</code> and must match the * form: * <code><em>a</em>.<em>a</em>.<em>a</em>.<em>a</em>/<em>n</em></code>, * where <em>a</em> is a number between 0 and 255, with no leading * zeroes, and <em>n</em> is a number between <em>0</em> and * <em>32</em>, no leading zeroes. */ private IPFilter(String expression) { _expression = expression; } // Fields /** * The expression of this filter. */ private final String _expression; // Methods /** * Returns the filter expression. * * @return * the original filter expression, never <code>null</code>. */ public final String getExpression() { return _expression; } public final boolean isAuthorized(String ip) throws IllegalArgumentException, ParseException { MandatoryArgumentChecker.check("ip", ip); if (isValidIp(ip) == false) { throw new ParseException("The provided IP " + ip + " is invalid."); } return false; // TODO } /** * Returns a textual representation of this filter. The implementation of * this method returns the filter expression passed. * * @return * a textual presentation, never <code>null</code>. */ public final String toString() { return getExpression(); } private static boolean isValidIp(String ip) { StringTokenizer tokenizer = new StringTokenizer(ip, IP_ADDRESS_DELIMETER); String currIPSection = null; boolean validToken = true; boolean validIP = false; int counter = 0; while (tokenizer.hasMoreTokens() && validToken == true) { currIPSection = tokenizer.nextToken(); validToken = isValidIPSection(currIPSection); counter++; } if (validToken == true && counter == 4) { validIP = true; } return validIP; } private static boolean isValidMask(String mask) { return isAllowedValue(mask, 32); } private static boolean isValidIPSection(String ipSection) { return isAllowedValue(ipSection, 255); } private static boolean isAllowedValue(String value, int maxAllowedValue) { boolean validValue = true; int intValue = -1; try { intValue = Integer.parseInt(value); } catch (NumberFormatException nfe) { validValue = false; } if (intValue < 0 || intValue > maxAllowedValue) { validValue = false; } return validValue; } }
package net.databinder.components; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import wicket.Component; import wicket.Resource; import wicket.ResourceReference; import wicket.SharedResources; import wicket.WicketRuntimeException; import wicket.markup.ComponentTag; import wicket.markup.html.image.Image; import wicket.markup.html.image.resource.RenderedDynamicImageResource; import wicket.model.ICompoundModel; import wicket.model.IModel; import wicket.util.string.Strings; /** * Renders its model text into a PNG, using any typeface available to the JVM. The size of * the image is determined by the model text and the characteristics of font selected. The * default font is 14pt sans, plain black on a white background. The background may be set * to null for alpha transparency, which will appear gray in outdated browsers. The image's * alt attribute will be set to the model text, and width and height attributes will be * set appropriately. * <p> If told to use a shared image resource, RenderedLabel will add its image * to the application's shared resources and reference it from a permanent, unique, * browser-chacheable URL. (Shared resources are incompatible with some clustering * configurations.) * <p> This class is inspired by, and draws code from, Wicket's DefaultButtonImageResource. </p> * @author Nathan Hamblen * @see wicket.markup.html.image.resource.DefaultButtonImageResource * @see SharedResources */ public class RenderedLabel extends Image { private static final long serialVersionUID = 1L; private Color backgroundColor = Color.WHITE; private Color color = Color.BLACK; private Font font = new Font("sans", Font.PLAIN, 14); private Integer maxWidth; /** If true, resource is shared across application with a permanent URL. */ private boolean isShared = false; /** Hash of the most recently displayed label attributes. -1 is initial value, 0 for blank labels. */ int labelHash = -1; RenderedTextImageResource resource; /** * Constructor to be used if model is derived from a compound property model. * @param id Wicket id */ public RenderedLabel(String id) { super(id); init(); } /** * Constructor for compound property model and shared resource pool. * @param id Wicket id * @param shareResource true to add to shared resource pool */ public RenderedLabel(String id, boolean shareResource) { this(id); this.isShared = shareResource; init(); } /** * Constructor with explicit model. * @param id Wicket id * @param model model for */ public RenderedLabel(String id, IModel model) { super(id, model); init(); } /** * Constructor with explicit model. * @param id Wicket id * @param model model for * @param shareResource true to add to shared resource pool */ public RenderedLabel(String id, IModel model, boolean shareResource) { this(id, model); this.isShared = shareResource; init(); } /** Perform generic initialization. */ protected void init() { setEscapeModelStrings(false); } @Override protected void onBeforeRender() { int curHash = getLabelHash(); if (isShared) { if (labelHash != curHash) { String hash = Integer.toHexString(curHash); SharedResources shared = getApplication().getSharedResources(); resource = (RenderedTextImageResource) shared.get(RenderedLabel.class, hash, null, hash, false); if (resource == null) shared.add(RenderedLabel.class, hash, null, null, resource = new RenderedTextImageResource(this, true)); setImageResourceReference(new ResourceReference(RenderedLabel.class, hash)); } } else { if (resource == null) setImageResource(resource = new RenderedTextImageResource(this, false)); else if (labelHash != curHash) resource.setState(this); } resource.setCacheable(isShared); labelHash = getLabelHash(); } /** * @return false if model string is empty. */ @Override public boolean isVisible() { return getText() != null; } /** * Adds image-specific attributes including width, height, and alternate text. A hash is appended * to the source URL to trigger a reload whenever drawing attributes change. */ @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); if (!isShared) { String url = tag.getAttributes().getString("src"); url = url + ((url.indexOf("?") >= 0) ? "&" : "?"); url = url + "wicket:antiCache=" + Integer.toHexString(labelHash); tag.put("src", url); } resource.preload(); tag.put("width", resource.getWidth() ); tag.put("height", resource.getHeight() ); tag.put("alt", getText()); } protected int getLabelHash() { String text = getText(); if (text == null) return 0; int hash= text.hashCode() ^ font.hashCode() ^ color.hashCode(); if (backgroundColor != null) hash ^= backgroundColor.hashCode(); if (maxWidth != null) hash ^= maxWidth.hashCode(); return hash; } /** Restores compound model resolution that is disabled in the Image superclass. */ @Override protected IModel initModel() { // c&p'd from Component for (Component current = getParent(); current != null; current = current.getParent()) { final IModel model = current.getModel(); if (model instanceof ICompoundModel) { setVersioned(false); return model; } } return null; } /** * Inner class that renders the model text into an image resource. * @see wicket.markup.html.image.resource.DefaultButtonImageResource */ protected static class RenderedTextImageResource extends RenderedDynamicImageResource { private Color backgroundColor; private Color color; private Font font; private Integer maxWidth; private String renderedText; public RenderedTextImageResource(RenderedLabel label, boolean isShared) { super(1, 1,"png"); // tiny default that will resize to fit text setType(BufferedImage.TYPE_INT_ARGB); // allow alpha transparency setCacheable(isShared); setState(label); } protected void setState(RenderedLabel label) { backgroundColor = label.getBackgroundColor(); color = label.getColor(); font = label.getFont(); maxWidth = label.getMaxWidth(); renderedText = label.getText(); invalidate(); } /** Renders text into image. */ protected boolean render(final Graphics2D graphics) { final int width = getWidth(), height = getHeight(); // draw background if not null, otherwise leave transparent if (backgroundColor != null) { graphics.setColor(backgroundColor); graphics.fillRect(0, 0, width, height); } // render as a 1x1 pixel if text is empty if (renderedText == null) { if (width == 1 && height == 1) return true; setWidth(1); setHeight(1); return false; } // Get size of text graphics.setFont(font); final FontMetrics metrics = graphics.getFontMetrics(); List<String> lines = new LinkedList<String>(); int dxText = breakLines(renderedText, metrics, lines), lineHeight = metrics.getHeight(), dyText = lineHeight * lines.size(); // resize and redraw if we need to if (dxText != width || dyText != height) { setWidth(dxText); setHeight(dyText); return false; } // Turn on anti-aliasing graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setColor(color); // Draw each line at its baseline int baseline = metrics.getAscent(); for (String line : lines) { graphics.drawString(line, 0, baseline); baseline += lineHeight; } return true; } /** * Breaks source string into lines no longer than this label's maxWidth, if not null. * @param source this label's model, previously retrieved * @param metrics metrics for the font we will use for display * @param outputLines list to receive lines generated by this function * @return length in pixels of the longest line */ protected int breakLines(String source, FontMetrics metrics, List<String> outputLines) { if (maxWidth == null) { outputLines.add(source); return metrics.stringWidth(source); } String sp = " "; String words[] = source.split(sp); StringBuilder line = new StringBuilder(); int topWidth = 0; for (String word : words) { if (line.length() >0) { int curWidth = metrics.stringWidth(line + sp + word); if (curWidth > maxWidth) { outputLines.add(line.toString()); line.setLength(0); } else line.append(sp); } line.append(word); topWidth = Math.max(metrics.stringWidth(line.toString()), topWidth); } outputLines.add(line.toString()); return topWidth; } /** * Normally, image rendering is deferred until the resource is requested, but * this method allows us to render the image when its markup is rendered. This way * the model will not need to be reattached when we serve the image, and we can * use the size information in the IMG tag. */ public void preload() { getImageData(); } } /** @return String to be rendered */ protected String getText() { String text = getModelObjectAsString(); return Strings.isEmpty(text) ? null : text; } public Color getBackgroundColor() { return backgroundColor; } /** * Specify a background color to match the page. Specify null for a transparent background blended * with the alpha channel, causing IE6 to display a gray background. * @param backgroundColor color or null for transparent * @return this for chaining */ public RenderedLabel setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; return this; } public Color getColor() { return color; } /** @param color Color to print text */ public RenderedLabel setColor(Color color) { this.color = color; return this; } public Font getFont() { return font; } public RenderedLabel setFont(Font font) { this.font = font; return this; } public Integer getMaxWidth() { return maxWidth; } /** * Specify a maximum pixel width, causing longer renderings to wrap. * @param maxWidth maximum width in pixels * @return this, for chaining */ public RenderedLabel setMaxWidth(Integer maxWidth) { this.maxWidth = maxWidth; return this; } /** * Utility method for creating Font objects from resources. * @param fontRes Resource containing a TrueType font descriptor. * @return Plain, 16pt font derived from the resource. */ public static Font fontForResource(Resource fontRes) { try { InputStream is = fontRes.getResourceStream().getInputStream(); Font font = Font.createFont(Font.TRUETYPE_FONT, is); is.close(); return font.deriveFont(Font.PLAIN, 16); } catch (Throwable e) { throw new WicketRuntimeException("Error loading font resources", e); } } }
package com.elusivehawk.util.storage; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.util.Collection; import com.elusivehawk.util.Logger; import com.elusivehawk.util.io.IByteReader; import com.elusivehawk.util.io.Serializers; import com.elusivehawk.util.math.VectorF; /** * * Helper class for creating NIO buffers. * <p> * If you just need something that emulates a buffer without the finite size, consider {@link Buffer} instead. * * @author Elusivehawk */ @SuppressWarnings("boxing") public final class BufferHelper { private BufferHelper(){} public static ByteBuffer createByteBuffer(int size) { if (size <= 0) { throw new RuntimeException(String.format("Cannot make a ByteBuffer with a size of %s", size)); } return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()); } public static CharBuffer createCharBuffer(int size) { return createByteBuffer(size << 1).asCharBuffer(); } public static DoubleBuffer createDoubleBuffer(int size) { return createByteBuffer(size << 3).asDoubleBuffer(); } public static FloatBuffer createFloatBuffer(int size) { return createByteBuffer(size << 2).asFloatBuffer(); } public static IntBuffer createIntBuffer(int size) { return createByteBuffer(size << 2).asIntBuffer(); } public static LongBuffer createLongBuffer(int size) { return createByteBuffer(size << 3).asLongBuffer(); } public static ShortBuffer createShortBuffer(int size) { return createByteBuffer(size << 1).asShortBuffer(); } public static ByteBuffer createWrapper(byte[] bs) { return ByteBuffer.wrap(bs); } public static CharBuffer createWrapper(char[] bs) { return CharBuffer.wrap(bs); } public static DoubleBuffer createWrapper(double[] bs) { return DoubleBuffer.wrap(bs); } public static FloatBuffer createWrapper(float[] bs) { return FloatBuffer.wrap(bs); } public static IntBuffer createWrapper(int[] bs) { return IntBuffer.wrap(bs); } public static LongBuffer createWrapper(long[] bs) { return LongBuffer.wrap(bs); } public static ShortBuffer createWrapper(short[] bs) { return ShortBuffer.wrap(bs); } public static ByteBuffer expand(ByteBuffer buf, int count) { return (ByteBuffer)createByteBuffer(buf.capacity() + count).put(((ByteBuffer)buf.rewind())).rewind(); } public static CharBuffer expand(CharBuffer buf, int count) { return (CharBuffer)createCharBuffer(buf.capacity() + count).put((CharBuffer)buf.rewind()).rewind(); } public static DoubleBuffer expand(DoubleBuffer buf, int count) { return (DoubleBuffer)createDoubleBuffer(buf.capacity() + count).put((DoubleBuffer)buf.rewind()).rewind(); } public static FloatBuffer expand(FloatBuffer buf, int count) { return (FloatBuffer)createFloatBuffer(buf.capacity() + count).put((FloatBuffer)buf.rewind()).rewind(); } public static IntBuffer expand(IntBuffer buf, int count) { return (IntBuffer)createIntBuffer(buf.capacity() + count).put((IntBuffer)buf.rewind()).rewind(); } public static LongBuffer expand(LongBuffer buf, int count) { return (LongBuffer)createLongBuffer(buf.capacity() + count).put((LongBuffer)buf.rewind()).rewind(); } public static ShortBuffer expand(ShortBuffer buf, int count) { return (ShortBuffer)createShortBuffer(buf.capacity() + count).put((ShortBuffer)buf.rewind()).rewind(); } public static ByteBuffer makeByteBuffer(byte... data) { return (ByteBuffer)createByteBuffer(data.length).put(data).flip(); } public static ByteBuffer makeByteBuffer(Collection<Byte> data) { ByteBuffer ret = createByteBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static ByteBuffer makeByteBuffer(Number... data) { ByteBuffer ret = createByteBuffer(data.length); for (Number n : data) { ret.put(n.byteValue()); } ret.flip(); return ret; } public static ByteBuffer makeByteBuffer(ByteBuffer buf, int offset, int count) { ByteBuffer ret = createByteBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static ByteBuffer makeByteBuffer(IByteReader r) { return makeByteBuffer(r.remaining(), r); } public static ByteBuffer makeByteBuffer(int length, IByteReader r) { ByteBuffer ret = createByteBuffer(length); try { for (int c = 0; c < length; c++) { ret.put(r.read()); } ret.flip(); } catch (Throwable e) { Logger.err(e); } return ret; } public static ByteBuffer makeByteBuffer(ByteBuffer... bufs) { int length = 0; for (ByteBuffer buf : bufs) { length += buf.remaining(); } ByteBuffer ret = createByteBuffer(length); for (ByteBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static ByteBuffer makeByteBuffer(CharSequence str) { return makeByteBuffer(str.toString().getBytes()); } public static CharBuffer makeCharBuffer(char... data) { return (CharBuffer)createCharBuffer(data.length).put(data).flip(); } public static CharBuffer makeCharBuffer(Collection<Character> data) { CharBuffer ret = createCharBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static CharBuffer makeCharBuffer(CharBuffer buf, int offset, int count) { CharBuffer ret = createCharBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static CharBuffer makeCharBuffer(CharBuffer... bufs) { int length = 0; for (CharBuffer buf : bufs) { length += buf.remaining(); } CharBuffer ret = createCharBuffer(length); for (CharBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static DoubleBuffer makeDoubleBuffer(double... data) { return (DoubleBuffer)createDoubleBuffer(data.length).put(data).flip(); } public static DoubleBuffer makeDoubleBuffer(Collection<Double> data) { DoubleBuffer ret = createDoubleBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static DoubleBuffer makeDoubleBuffer(Number... data) { DoubleBuffer ret = createDoubleBuffer(data.length); for (Number n : data) { ret.put(n.doubleValue()); } ret.flip(); return ret; } public static DoubleBuffer makeDoubleBuffer(DoubleBuffer buf, int offset, int count) { DoubleBuffer ret = createDoubleBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static DoubleBuffer makeDoubleBuffer(DoubleBuffer... bufs) { int length = 0; for (DoubleBuffer buf : bufs) { length += buf.remaining(); } DoubleBuffer ret = createDoubleBuffer(length); for (DoubleBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static FloatBuffer makeFloatBuffer(float... data) { return (FloatBuffer)createFloatBuffer(data.length).put(data).flip(); } public static FloatBuffer makeFloatBuffer(Collection<Float> data) { FloatBuffer ret = createFloatBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static FloatBuffer makeFloatBuffer(Number... data) { FloatBuffer ret = createFloatBuffer(data.length); for (Number n : data) { ret.put(n.floatValue()); } return ret; } public static FloatBuffer makeFloatBuffer(FloatBuffer buf, int offset, int count) { FloatBuffer ret = createFloatBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static FloatBuffer makeFloatBuffer(FloatBuffer... bufs) { int length = 0; for (FloatBuffer buf : bufs) { length += buf.remaining(); } FloatBuffer ret = createFloatBuffer(length); for (FloatBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static IntBuffer makeIntBuffer(int... data) { return (IntBuffer)createIntBuffer(data.length).put(data).flip(); } public static IntBuffer makeIntBuffer(Collection<Integer> data) { IntBuffer ret = createIntBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static IntBuffer makeIntBuffer(Number... data) { IntBuffer ret = createIntBuffer(data.length); for (Number n : data) { ret.put(n.intValue()); } ret.flip(); return ret; } public static IntBuffer makeIntBuffer(IntBuffer buf, int offset, int count) { IntBuffer ret = createIntBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static IntBuffer makeIntBuffer(IntBuffer... bufs) { int length = 0; for (IntBuffer buf : bufs) { length += buf.remaining(); } IntBuffer ret = createIntBuffer(length); for (IntBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static LongBuffer makeLongBuffer(long... data) { return (LongBuffer)createLongBuffer(data.length).put(data).flip(); } public static LongBuffer makeLongBuffer(Collection<Long> data) { LongBuffer ret = createLongBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static LongBuffer makeLongBuffer(Number... data) { LongBuffer ret = createLongBuffer(data.length); for (Number n : data) { ret.put(n.longValue()); } ret.flip(); return ret; } public static LongBuffer makeLongBuffer(LongBuffer buf, int offset, int count) { LongBuffer ret = createLongBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static LongBuffer makeLongBuffer(LongBuffer... bufs) { int length = 0; for (LongBuffer buf : bufs) { length += buf.remaining(); } LongBuffer ret = createLongBuffer(length); for (LongBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static ShortBuffer makeShortBuffer(short... data) { return (ShortBuffer)createShortBuffer(data.length).put(data).flip(); } public static ShortBuffer makeShortBuffer(Collection<Short> data) { ShortBuffer ret = createShortBuffer(data.size()); data.forEach(ret::put); ret.flip(); return ret; } public static ShortBuffer makeShortBuffer(Number... data) { ShortBuffer ret = createShortBuffer(data.length); for (Number n : data) { ret.put(n.shortValue()); } ret.flip(); return ret; } public static ShortBuffer makeShortBuffer(ShortBuffer buf, int offset, int count) { ShortBuffer ret = createShortBuffer(count); for (int c = 0; c < count; c++) { ret.put(buf.get(c + offset)); } ret.flip(); return ret; } public static ShortBuffer makeShortBuffer(ShortBuffer... bufs) { int length = 0; for (ShortBuffer buf : bufs) { length += buf.remaining(); } ShortBuffer ret = createShortBuffer(length); for (ShortBuffer buf : bufs) { ret.put(buf); } ret.flip(); return ret; } public static FloatBuffer makeVecFloatBufferf(Collection<VectorF> data) { int size = 0; for (VectorF vec : data) { size += vec.size(); } FloatBuffer ret = createFloatBuffer(size); data.forEach(((vec) -> { for (int c = 0; c < vec.size(); c++) { ret.put(vec.get(c)); } })); ret.flip(); return ret; } public static FloatBuffer makeVecFloatBufferf(VectorF... data) { int size = 0; for (VectorF vec : data) { size += vec.size(); } FloatBuffer ret = createFloatBuffer(size); for (VectorF vec : data) { for (int c = 0; c < vec.size(); c++) { ret.put(vec.get(c)); } } ret.flip(); return ret; } public static ByteBuffer toByteBuffer(DoubleBuffer buf) { ByteBuffer ret = createByteBuffer(buf.remaining() * 8); for (int c = buf.position(); c < buf.capacity(); c++) { Serializers.DOUBLE.toBytes(buf.get(c), ((bs) -> { ret.put(bs); return 8; })); } return ret; } public static ByteBuffer toByteBuffer(FloatBuffer buf) { ByteBuffer ret = createByteBuffer(buf.remaining() * 4); for (int c = buf.position(); c < buf.capacity(); c++) { Serializers.FLOAT.toBytes(buf.get(c), ((bs) -> { ret.put(bs); return 4; })); } return ret; } public static ByteBuffer toByteBuffer(IntBuffer buf) { ByteBuffer ret = createByteBuffer(buf.remaining() * 4); for (int c = buf.position(); c < buf.capacity(); c++) { Serializers.INTEGER.toBytes(buf.get(c), ((bs) -> { ret.put(bs); return 4; })); } return ret; } public static ByteBuffer toByteBuffer(LongBuffer buf) { ByteBuffer ret = createByteBuffer(buf.remaining() * 8); for (int c = buf.position(); c < buf.capacity(); c++) { Serializers.LONG.toBytes(buf.get(c), ((bs) -> { ret.put(bs); return 4; })); } return ret; } public static ByteBuffer toByteBuffer(ShortBuffer buf) { ByteBuffer ret = createByteBuffer(buf.remaining() * 2); for (int c = buf.position(); c < buf.capacity(); c++) { Serializers.SHORT.toBytes(buf.get(c), ((bs) -> { ret.put(bs); return 4; })); } return ret; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.FullTextIndex; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.ColumnDefinition; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.util.ArrayUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pClass, PersistenceContext context) { _pClass = pClass; Entity entity = pClass.getAnnotation(Entity.class); // see if this is a computed entity _computed = pClass.getAnnotation(Computed.class); if (_computed == null) { // if not, this class has a corresponding SQL table _tableName = _pClass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } } } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pClass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } boolean seenIdentityGenerator = false; // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pClass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.warning("Failed to read schema version [class=" + _pClass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller<?> fm = FieldMarshaller.createMarshaller(field); _fields.put(field.getName(), fm); fields.add(field.getName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller<?>>(); } _pkColumns.add(fm); } // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // check if this field is auto-generated GeneratedValue gv = fm.getGeneratedValue(); if (gv != null) { // we can only do this on numeric fields Class<?> ftype = field.getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column: " + field.getName()); } switch(gv.strategy()) { case AUTO: case IDENTITY: if (seenIdentityGenerator) { throw new IllegalArgumentException( "Persistent records can have at most one AUTO/IDENTITY generator."); } _valueGenerators.put(field.getName(), new IdentityValueGenerator(gv, this, fm)); seenIdentityGenerator = true; break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _valueGenerators.put( field.getName(), new TableValueGenerator(generator, gv, this, fm)); break; case SEQUENCE: // TODO throw new IllegalArgumentException( "SEQUENCE key generation strategy not yet supported."); } } } // if we did not find a schema version field, freak out (but not for computed records, for // whom there is no table) if (_tableName != null && _schemaVersion <= 0) { throw new IllegalStateException( pClass.getName() + "." + SCHEMA_VERSION_FIELD + " must be greater than zero."); } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // now check for @Entity annotations on the entire superclass chain Class<?> iterClass = pClass; do { entity = iterClass.getAnnotation(Entity.class); if (entity != null) { for (UniqueConstraint constraint : entity.uniqueConstraints()) { String[] conFields = constraint.fieldNames(); Set<String> colSet = new HashSet<String>(); for (int ii = 0; ii < conFields.length; ii ++) { FieldMarshaller<?> fm = _fields.get(conFields[ii]); if (fm == null) { throw new IllegalArgumentException( "Unknown unique constraint field: " + conFields[ii]); } colSet.add(fm.getColumnName()); } _uniqueConstraints.add(colSet); } for (Index index : entity.indices()) { if (_indexes.containsKey(index.name())) { continue; } _indexes.put(index.name(), index); } // if there are FTS indexes in the Table, map those out here for future use for (FullTextIndex fti : entity.fullTextIndices()) { if (_fullTextIndexes.containsKey(fti.name())) { continue; } _fullTextIndexes.put(fti.name(), fti); } } iterClass = iterClass.getSuperclass(); } while (PersistentRecord.class.isAssignableFrom(iterClass) && !PersistentRecord.class.equals(iterClass)); } /** * Returns the persistent class this is object is a marshaller for. */ public Class<T> getPersistentClass () { return _pClass; } /** * Returns the @Computed annotation definition of this entity, or null if none. */ public Computed getComputed () { return _computed; } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns all the persistent fields that correspond to concrete table columns. */ public String[] getColumnFieldNames () { return _columnFields; } public FullTextIndex getFullTextIndex (String name) { FullTextIndex fti = _fullTextIndexes.get(name); if (fti == null) { throw new IllegalStateException("Persistent class missing full text index " + "[class=" + _pClass + ", index=" + name + "]"); } return fti; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller<?> getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns the {@link ValueGenerator} objects used to automatically generate field values for * us when a new record is inserted. */ public Iterable<ValueGenerator> getValueGenerators () { return _valueGenerators.values(); } /** * Return the names of the columns that constitute the primary key of our associated persistent * record. */ public String[] getPrimaryKeyFields () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getField().getName(); } return pkcols; } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pClass.getName() + " does not define a primary key"); } return null; } try { Comparable<?>[] values = new Comparable<?>[_pkColumns.size()]; int nulls = 0, zeros = 0; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller<?> field = _pkColumns.get(ii); values[ii] = (Comparable<?>)field.getField().get(object); if (values[ii] == null) { nulls++; } else if (values[ii] instanceof Number && ((Number)values[ii]).intValue() == 0) { nulls++; // zeros are considered nulls; see below zeros++; } } // make sure the keys are all null or all non-null; we also allow primary keys where // there are zero-valued primitive primary key columns as along as there is at least // one non-zero valued additional key column; this is a compromise that allows sensible // things like (id=99, type=0) but unfortunately also allows less sensible things like // (id=0, type=5) while continuing to disallow the dangerous (id=0) if (nulls == 0 || (nulls == zeros)) { return makePrimaryKey(values); } else if (nulls == values.length) { return null; } // throw an informative error message StringBuilder keys = new StringBuilder(); for (int ii = 0; ii < _pkColumns.size(); ii++) { keys.append(", ").append(_pkColumns.get(ii).getField().getName()); keys.append("=").append(values[ii]); } throw new IllegalArgumentException("Primary key fields are mixed null and non-null " + "[class=" + _pClass.getName() + keys + "]."); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable<?>... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] fields = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { fields[ii] = _pkColumns.get(ii).getField().getName(); } return new Key<T>(_pClass, fields, values); } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied result set. */ public Key<T> makePrimaryKey (ResultSet rs) throws SQLException { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } Comparable<?>[] values = new Comparable<?>[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { Object keyValue = _pkColumns.get(ii).getFromSet(rs); if (!(keyValue instanceof Comparable<?>)) { throw new IllegalArgumentException("Key field must be Comparable<?> [field=" + _pkColumns.get(ii).getColumnName() + "]"); } values[ii] = (Comparable<?>) keyValue; } return makePrimaryKey(values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a properly constructed query (see {@link BuildVisitor}). */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pClass.newInstance(); for (FieldMarshaller<?> fm : _fields.values()) { if (!fields.contains(fm.getColumnName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.getAndWriteToObject(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [class=" + _pClass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Go through the registered {@link ValueGenerator}s for our persistent object and run the ones * that match the current postFactum phase, filling in the fields on the supplied object while * we go. * * The return value is only non-empty for the !postFactum phase, in which case it is a set of * field names that are associated with {@link IdentityValueGenerator}, because these need * special handling in the INSERT (specifically, 'DEFAULT' must be supplied as a value in the * eventual SQL). */ public Set<String> generateFieldValues ( Connection conn, DatabaseLiaison liaison, Object po, boolean postFactum) { Set<String> idFields = new HashSet<String>(); for (ValueGenerator vg : _valueGenerators.values()) { if (!postFactum && vg instanceof IdentityValueGenerator) { idFields.add(vg.getFieldMarshaller().getField().getName()); } if (vg.isPostFactum() != postFactum) { continue; } try { int nextValue = vg.nextGeneratedValue(conn, liaison); vg.getFieldMarshaller().getField().set(po, nextValue); } catch (Exception e) { throw new IllegalStateException( "Failed to assign primary key [type=" + _pClass + "]", e); } } return idFields; } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (SchemaMigration migration) { _schemaMigs.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (PersistenceContext ctx) throws DatabaseException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pClass + "]."); } _initialized = true; final SQLBuilder builder = ctx.getSQLBuilder(new DepotTypes(ctx, _pClass)); // perform the context-sensitive initialization of the field marshallers for (FieldMarshaller<?> fm : _fields.values()) { fm.init(builder); } // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; ColumnDefinition[] declarations = new ColumnDefinition[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { FieldMarshaller<?> fm = _fields.get(_allFields[ii]); // include all persistent non-computed fields ColumnDefinition colDef = fm.getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; declarations[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); declarations = ArrayUtil.splice(declarations, jj); // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { P_COLUMN, V_COLUMN, MV_COLUMN }, new ColumnDefinition[] { new ColumnDefinition("VARCHAR(255)", false, true, null), new ColumnDefinition("INTEGER", false, false, null), new ColumnDefinition("INTEGER", false, false, null) }, null, new String[] { P_COLUMN }); // add our new "migratingVersion" column if it's not already there liaison.addColumn(conn, SCHEMA_VERSION_TABLE, MV_COLUMN, "integer not null default 0", true); return 0; } }); // fetch all relevant information regarding our table from the database TableMetaData metaData = TableMetaData.load(ctx, getTableName()); // determine whether or not this record has ever been seen int currentVersion = ctx.invoke(new ReadVersion()); if (currentVersion == -1) { log.info("Creating initial version record for " + _pClass.getName() + "."); // if not, create a version entry with version zero ctx.invoke(new SimpleModifier() { protected int invoke (DatabaseLiaison liaison, Statement stmt) throws SQLException { try { return stmt.executeUpdate( "insert into " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " values('" + getTableName() + "', 0 , 0)"); } catch (SQLException e) { // someone else might be doing this at the exact same time which is OK, // we'll coordinate with that other process in the next phase if (liaison.isDuplicateRowException(e)) { return 0; } else { throw e; } } } }); } // now check whether we need to migrate our database schema boolean gotMigrationLock = false; while (!gotMigrationLock) { currentVersion = ctx.invoke(new ReadVersion()); if (currentVersion >= _schemaVersion) { checkForStaleness(metaData, ctx, builder); return; } // try to update migratingVersion to the new version to indicate to other processes // that we are handling the migration and that they should wait if (ctx.invoke(new UpdateMigratingVersion(_schemaVersion, 0)) > 0) { break; // we got the lock, let's go } // we didn't get the lock, so wait 5 seconds and then check to see if the other process // finished the update or failed in which case we'll try to grab the lock ourselves try { log.info("Waiting on migration lock for " + _pClass.getName() + "."); Thread.sleep(5000); } catch (InterruptedException ie) { throw new DatabaseException("Interrupted while waiting on migration lock."); } } try { if (!metaData.tableExists) { // if the table does not exist, create it createTable(ctx, builder, declarations); metaData = TableMetaData.load(ctx, getTableName()); } else { // if it does exist, run our migrations metaData = runMigrations(ctx, metaData, builder, currentVersion); } // check for stale columns now that the table is up to date checkForStaleness(metaData, ctx, builder); // and update our version in the schema version table ctx.invoke(new SimpleModifier() { protected int invoke (DatabaseLiaison liaison, Statement stmt) throws SQLException { return stmt.executeUpdate( "update " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " set " + liaison.columnSQL(V_COLUMN) + " = " + _schemaVersion + " where " + liaison.columnSQL(P_COLUMN) + " = '" + getTableName() + "'"); } }); } finally { // set our migrating version back to zero try { if (ctx.invoke(new UpdateMigratingVersion(0, _schemaVersion)) == 0) { log.warning("Failed to restore migrating version to zero!", "record", _pClass); } } catch (Exception e) { log.warning("Failure restoring migrating version! Bad bad!", "record", _pClass, e); } } } protected void createTable (PersistenceContext ctx, final SQLBuilder builder, final ColumnDefinition[] declarations) throws DatabaseException { log.info("Creating initial table '" + getTableName() + "'."); final String[][] uniqueConCols = new String[_uniqueConstraints.size()][]; int kk = 0; for (Set<String> colSet : _uniqueConstraints) { uniqueConCols[kk++] = colSet.toArray(new String[colSet.size()]); } final Iterable<Index> indexen = _indexes.values(); ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // create the table String[] primaryKeyColumns = null; if (_pkColumns != null) { primaryKeyColumns = new String[_pkColumns.size()]; for (int ii = 0; ii < primaryKeyColumns.length; ii ++) { primaryKeyColumns[ii] = _pkColumns.get(ii).getColumnName(); } } liaison.createTableIfMissing( conn, getTableName(), fieldsToColumns(_columnFields), declarations, uniqueConCols, primaryKeyColumns); // add its indexen for (Index idx : indexen) { liaison.addIndexToTable( conn, getTableName(), fieldsToColumns(idx.fields()), getTableName() + "_" + idx.name(), idx.unique()); } // create our value generators for (ValueGenerator vg : _valueGenerators.values()) { vg.create(conn, liaison); } // and its full text search indexes for (FullTextIndex fti : _fullTextIndexes.values()) { builder.addFullTextSearch(conn, DepotMarshaller.this, fti); } return 0; } }); } protected TableMetaData runMigrations (PersistenceContext ctx, TableMetaData metaData, final SQLBuilder builder, int currentVersion) throws DatabaseException { log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); if (_schemaMigs.size() > 0) { // run our pre-default-migrations for (SchemaMigration migration : _schemaMigs) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // we don't know what the pre-migrations did so we have to re-read metadata metaData = TableMetaData.load(ctx, getTableName()); } // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(metaData.indexColumns.keySet()); // figure out which columns we have in the table now, so that when all is said and done we // can see what new columns we have in the table and run the creation code for any value // generators that are defined on those columns (we can't just track the columns we add in // our automatic migrations because someone might register custom migrations that add // columns specially) Set<String> preMigrateColumns = new HashSet<String>(metaData.tableColumns); // add any missing columns for (String fname : _columnFields) { final FieldMarshaller<?> fmarsh = _fields.get(fname); if (metaData.tableColumns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column final ColumnDefinition coldef = fmarsh.getColumnDefinition(); log.info("Adding column to " + getTableName() + ": " + fmarsh.getColumnName()); ctx.invoke(new Modifier.Simple() { @Override protected String createQuery (DatabaseLiaison liaison) { return "alter table " + liaison.tableSQL(getTableName()) + " add column " + liaison.columnSQL(fmarsh.getColumnName()) + " " + liaison.expandDefinition(coldef); } }); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (!coldef.isNullable() && (coldef.getType().equalsIgnoreCase("timestamp") || coldef.getType().equalsIgnoreCase("datetime"))) { log.info("Assigning current time to " + fmarsh.getColumnName() + "."); ctx.invoke(new Modifier.Simple() { @Override protected String createQuery (DatabaseLiaison liaison) { // TODO: is NOW() standard SQL? return "update " + liaison.tableSQL(getTableName()) + " set " + liaison.columnSQL(fmarsh.getColumnName()) + " = NOW()"; } }); } } // add or remove the primary key as needed if (hasPrimaryKey() && metaData.pkName == null) { log.info("Adding primary key."); ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addPrimaryKey( conn, getTableName(), fieldsToColumns(getPrimaryKeyFields())); return 0; } }); } else if (!hasPrimaryKey() && metaData.pkName != null) { final String pkName = metaData.pkName; log.info("Dropping primary key: " + pkName); ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.dropPrimaryKey(conn, getTableName(), pkName); return 0; } }); } // add any named indices that exist on the record but not yet on the table for (final Index index : _indexes.values()) { final String ixName = getTableName() + "_" + index.name(); if (metaData.indexColumns.containsKey(ixName)) { // this index already exists metaData.indexColumns.remove(ixName); continue; } // but this is a new, named index, so we create it ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addIndexToTable( conn, getTableName(), fieldsToColumns(index.fields()), ixName, index.unique()); return 0; } }); } // now check if there are any @Entity(uniqueConstraints) that need to be created Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(metaData.indexColumns.values()); // unique constraints are unordered and may be unnamed, so we view them only as column sets for (Set<String> colSet : _uniqueConstraints) { if (uniqueIndices.contains(colSet)) { // the table already contains precisely this column set continue; } // else build the new constraint; we'll name it after one of its columns, adding _N // to resolve any possible ambiguities, because using all the column names in the // index name may exceed the maximum length of an SQL identifier String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } final String[] colArr = colSet.toArray(new String[colSet.size()]); final String fName = indexName; ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addIndexToTable(conn, getTableName(), colArr, fName, true); return 0; } }); } // next we create any full text search indexes that exist on the record but not in the // table, first step being to do a dialect-sensitive enumeration of existing indexes Set<String> tableFts = new HashSet<String>(); builder.getFtsIndexes(metaData.tableColumns, metaData.indexColumns.keySet(), tableFts); // then iterate over what should be there for (final FullTextIndex recordFts : _fullTextIndexes.values()) { if (tableFts.contains(recordFts.name())) { // the table already contains this one continue; } // but not this one, so let's create it ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { builder.addFullTextSearch(conn, DepotMarshaller.this, recordFts); return 0; } }); } // we do not auto-remove columns but rather require that SchemaMigration.Drop records be // registered by hand to avoid accidentally causing the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (SchemaMigration migration : _schemaMigs) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // now reload our table metadata so that we can see what columns we have now metaData = TableMetaData.load(ctx, getTableName()); // initialize value generators for any columns that have been newly added for (String column : metaData.tableColumns) { if (preMigrateColumns.contains(column)) { continue; } // see if we have a value generator for this new column final ValueGenerator valgen = _valueGenerators.get(column); if (valgen == null) { continue; } // note: if someone renames a column that has an identity value generator, things will // break because Postgres automatically creates a table_column_seq sequence that is // used to generate values for that column and god knows what happens when that is // renamed; plus we're potentially going to try to reinitialize it if it has a non-zero // initialValue which will use the new column name to obtain the sequence name which // ain't going to work either; we punt! ctx.invoke(new Modifier() { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { valgen.create(conn, liaison); return 0; } }); } return metaData; } // translate an array of field names to an array of column names protected String[] fieldsToColumns (String[] fields) { String[] columns = new String[fields.length]; for (int ii = 0; ii < columns.length; ii ++) { FieldMarshaller<?> fm = _fields.get(fields[ii]); if (fm == null) { throw new IllegalArgumentException( "Unknown field on record [field=" + fields[ii] + ", class=" + _pClass + "]"); } columns[ii] = fm.getColumnName(); } return columns; } /** * Checks that there are no database columns for which we no longer have Java fields. */ protected void checkForStaleness (TableMetaData meta, PersistenceContext ctx, SQLBuilder builder) throws DatabaseException { for (String fname : _columnFields) { FieldMarshaller<?> fmarsh = _fields.get(fname); meta.tableColumns.remove(fmarsh.getColumnName()); } for (String column : meta.tableColumns) { if (builder.isPrivateColumn(column)) { continue; } log.warning(getTableName() + " contains stale column '" + column + "'."); } } protected abstract class SimpleModifier extends Modifier { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { Statement stmt = conn.createStatement(); try { return invoke(liaison, stmt); } finally { stmt.close(); } } protected abstract int invoke (DatabaseLiaison liaison, Statement stmt) throws SQLException; } // this is a Modifier not a Query because we want to be sure we're talking to the database // server to whom we would talk if we were doing a modification (ie. the master, not a // read-only slave) protected class ReadVersion extends SimpleModifier { protected int invoke (DatabaseLiaison liaison, Statement stmt) throws SQLException { ResultSet rs = stmt.executeQuery( " select " + liaison.columnSQL(V_COLUMN) + " from " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " where " + liaison.columnSQL(P_COLUMN) + " = '" + getTableName() + "'"); return (rs.next()) ? rs.getInt(1) : -1; } } protected class UpdateMigratingVersion extends SimpleModifier { public UpdateMigratingVersion (int newMigratingVersion, int guardVersion) { _newMigratingVersion = newMigratingVersion; _guardVersion = guardVersion; } protected int invoke (DatabaseLiaison liaison, Statement stmt) throws SQLException { return stmt.executeUpdate( "update " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " set " + liaison.columnSQL(MV_COLUMN) + " = " + _newMigratingVersion + " where " + liaison.columnSQL(P_COLUMN) + " = '" + getTableName() + "'" + " and " + liaison.columnSQL(MV_COLUMN) + " = " + _guardVersion); } protected int _newMigratingVersion, _guardVersion; } protected static class TableMetaData { public boolean tableExists; public Set<String> tableColumns = new HashSet<String>(); public Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); public String pkName; public Set<String> pkColumns = new HashSet<String>(); public static TableMetaData load (PersistenceContext ctx, final String tableName) throws DatabaseException { return ctx.invoke(new Query.Trivial<TableMetaData>() { @Override public TableMetaData invoke (Connection conn, DatabaseLiaison dl) throws SQLException { return new TableMetaData(conn.getMetaData(), tableName); } }); } public TableMetaData (DatabaseMetaData meta, String tableName) throws SQLException { tableExists = meta.getTables("", "", tableName, null).next(); if (!tableExists) { return; } ResultSet rs = meta.getColumns(null, null, tableName, "%"); while (rs.next()) { tableColumns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } rs = meta.getPrimaryKeys(null, null, tableName); while (rs.next()) { pkName = rs.getString("PK_NAME"); pkColumns.add(rs.getString("COLUMN_NAME")); } } } /** The persistent object class that we manage. */ protected Class<T> _pClass; /** The name of our persistent object table. */ protected String _tableName; /** The @Computed annotation of this entity, or null. */ protected Computed _computed; /** A mapping of field names to value generators for that field. */ protected Map<String, ValueGenerator> _valueGenerators = new HashMap<String, ValueGenerator>(); /** A field marshaller for each persistent field in our object. */ protected Map<String, FieldMarshaller<?>> _fields = new HashMap<String, FieldMarshaller<?>>(); /** The field marshallers for our persistent object's primary key columns or null if it did not * define a primary key. */ protected ArrayList<FieldMarshaller<?>> _pkColumns; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The indexes defined in @Entity annotations for this record. */ protected Map<String, Index> _indexes = new HashMap<String, Index>(); /** The unique constraints defined in @Entity annotations for this record. */ protected Set<Set<String>> _uniqueConstraints = new HashSet<Set<String>>(); protected Map<String, FullTextIndex> _fullTextIndexes = new HashMap<String, FullTextIndex>(); /** The version of our persistent object schema as specified in the class definition. */ protected int _schemaVersion = -1; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered schema migrations to run prior to doing the default migration. */ protected ArrayList<SchemaMigration> _schemaMigs = new ArrayList<SchemaMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; /** The name of the 'persistentClass' column in the {@link #SCHEMA_VERSION_TABLE}. */ protected static final String P_COLUMN = "persistentClass"; /** The name of the 'version' column in the {@link #SCHEMA_VERSION_TABLE}. */ protected static final String V_COLUMN = "version"; /** The name of the 'migratingVersion' column in the {@link #SCHEMA_VERSION_TABLE}. */ protected static final String MV_COLUMN = "migratingVersion"; }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.Table; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.clause.Where; import com.samskivert.util.ArrayUtil; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; Entity entity = pclass.getAnnotation(Entity.class); Table table = null; // see if this is a computed entity Computed computed = pclass.getAnnotation(Computed.class); if (computed == null) { // if not, this class has a corresponding SQL table _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } _postamble = entity.postamble(); } // check for a Table annotation, for unique constraints table = pclass.getAnnotation(Table.class); } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(fm.getColumnName(), fm); fields.add(fm.getColumnName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator(); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator(generator); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // if we're a computed entity, stop here if (_tableName == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { // include all persistent non-computed fields String colDef = _fields.get(_allFields[ii]).getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; _declarations.add(colDef); jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); // determine whether we have any index definitions if (entity != null) { for (Index index : entity.indices()) { // TODO: delegate this to a database specific SQL generator _declarations.add(index.type() + " index " + index.name() + " (" + StringUtil.join(index.columns(), ", ") + ")"); } } // add any unique constraints given if (table != null) { for (UniqueConstraint constraint : table.uniqueConstraints()) { _declarations.add( "UNIQUE (" + StringUtil.join(constraint.columnNames(), ", ") + ")"); } } // add the primary key, if we have one if (hasPrimaryKey()) { _declarations.add("PRIMARY KEY (" + getPrimaryKeyColumns() + ")"); } // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pclass.getName() + " does not define a primary key"); } return null; } try { Comparable[] values = new Comparable[_pkColumns.size()]; boolean hasNulls = false; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); if (values[ii] == null || Integer.valueOf(0).equals(values[ii])) { // if this is the first null we see but not the first field, freak out if (!hasNulls && ii > 0) { throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } hasNulls = true; } else if (hasNulls) { // if this is a non-null field and we've previously seen nulls, also freak throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } } // if all the fields were null, return null, else build a key return hasNulls ? null : makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] columns = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { columns[ii] = _pkColumns.get(ii).getColumnName(); } return new Key<T>(_pclass, columns, values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getField().getName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.getValue(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will insert the supplied persistent object into the database. */ public PreparedStatement createInsert (Connection conn, Object po) throws SQLException { requireNotComputed("insert rows into"); try { StringBuilder insert = new StringBuilder(); insert.append("insert into ").append(getTableName()); insert.append(" (").append(StringUtil.join(_columnFields, ",")); insert.append(")").append(" values("); for (int ii = 0; ii < _columnFields.length; ii++) { if (ii > 0) { insert.append(", "); } insert.append("?"); } insert.append(")"); // TODO: handle primary key, nullable fields specially? PreparedStatement pstmt = conn.prepareStatement(insert.toString()); int idx = 0; for (String field : _columnFields) { _fields.get(field).setValue(po, pstmt, ++idx); } return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the supplied persistent object using the supplied key. */ public PreparedStatement createUpdate (Connection conn, Object po, Where key) throws SQLException { return createUpdate(conn, po, key, _columnFields); } /** * Creates a statement that will update the supplied persistent object * using the supplied key. */ public PreparedStatement createUpdate ( Connection conn, Object po, Where key, String[] modifiedFields) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); try { PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (String field : modifiedFields) { _fields.get(field).setValue(po, pstmt, ++idx); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object " + "[pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the specified set of fields for all persistent objects * that match the supplied key. */ public PreparedStatement createPartialUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (Object value : modifiedValues) { // TODO: use the field marshaller? pstmt.setObject(++idx, value); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } /** * Creates a statement that will delete all rows matching the supplied key. */ public PreparedStatement createDelete (Connection conn, Where key) throws SQLException { requireNotComputed("delete rows from"); StringBuilder query = new StringBuilder("delete from " + getTableName()); key.appendClause(null, query); PreparedStatement pstmt = conn.prepareStatement(query.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * Creates a statement that will update the specified set of fields, using the supplied literal * SQL values, for all persistent objects that match the supplied key. */ public PreparedStatement createLiteralUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); for (int ii = 0; ii < modifiedFields.length; ii++) { if (ii > 0) { update.append(", "); } update.append(modifiedFields[ii]).append(" = "); update.append(modifiedValues[ii]); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (EntityMigration migration) { _migrations.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (PersistenceContext ctx) throws PersistenceException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pclass + "]."); } _initialized = true; // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { JDBCUtil.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass VARCHAR(255) NOT NULL", "version INTEGER NOT NULL" }, ""); return 0; } }); // now create the table for our persistent class if it does not exist ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { if (!JDBCUtil.tableExists(conn, getTableName())) { log.info("Creating table " + getTableName() + " (" + _declarations + ") " + _postamble); String[] definition = _declarations.toArray(new String[_declarations.size()]); JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble); updateVersion(conn, _schemaVersion); } return 0; } }); // if we have a key generator, initialize that too if (_keyGenerator != null) { ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { _keyGenerator.init(conn); return 0; } }); } // if schema versioning is disabled, stop now if (_schemaVersion < 0) { return; } // make sure the versions match int currentVersion = ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { String query = "select version from " + SCHEMA_VERSION_TABLE + " where persistentClass = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } }); if (currentVersion == _schemaVersion) { return; } // otherwise try to migrate the schema log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // run our pre-default-migrations for (EntityMigration migration : _migrations) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // enumerate all of the columns now that we've run our pre-migrations final Set<String> columns = new HashSet<String>(); final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, getTableName(), false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } return 0; } }); // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet()); // add any missing columns for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); if (columns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column String coldef = fmarsh.getColumnDefinition(); String query = "alter table " + getTableName() + " add column " + coldef; // try to add it to the appropriate spot int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName()); if (fidx == 0) { query += " first"; } else { query += " after " + _allFields[fidx-1]; } log.info("Adding column to " + getTableName() + ": " + coldef); ctx.invoke(new Modifier.Simple(query)); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (coldef.toLowerCase().indexOf(" timestamp") != -1 || coldef.toLowerCase().indexOf(" datetime") != -1) { query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()"; log.info("Assigning current time to column: " + query); ctx.invoke(new Modifier.Simple(query)); } } // add or remove the primary key as needed if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) { String pkdef = "primary key (" + getPrimaryKeyColumns() + ")"; log.info("Adding primary key to " + getTableName() + ": " + pkdef); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef)); } else if (!hasPrimaryKey() && indexColumns.containsKey("PRIMARY")) { indexColumns.remove("PRIMARY"); log.info("Dropping primary from " + getTableName()); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key")); } // add any missing indices Entity entity = _pclass.getAnnotation(Entity.class); for (Index index : (entity == null ? new Index[0] : entity.indices())) { if (indexColumns.containsKey(index.name())) { indexColumns.remove(index.name()); continue; } String indexdef = "create " + index.type() + " index " + index.name() + " on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")"; log.info("Adding index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } // to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values()); Table table; if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) { Set<String> colSet = new HashSet<String>(); for (UniqueConstraint constraint : table.uniqueConstraints()) { // for each given UniqueConstraint, build a new column set colSet.clear(); for (String column : constraint.columnNames()) { colSet.add(column); } // and check if the table contained this set if (uniqueIndices.contains(colSet)) { continue; // good, carry on } // else build the index; we'll use mysql's convention of naming it after a column, // with possible _N disambiguation; luckily we made a copy of the index names! String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } String[] columnArr = colSet.toArray(new String[colSet.size()]); String indexdef = "create unique index " + indexName + " on " + getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")"; log.info("Adding unique index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } } // we do not auto-remove columns but rather require that EntityMigration.Drop records be // registered by hand to avoid accidentally causin the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (EntityMigration migration : _migrations) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // record our new version in the database ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { updateVersion(conn, _schemaVersion); return 0; } }); } protected String getPrimaryKeyColumns () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getColumnName(); } return StringUtil.join(pkcols, ", "); } protected void updateVersion (Connection conn, int version) throws SQLException { String update = "update " + SCHEMA_VERSION_TABLE + " set version = " + version + " where persistentClass = '" + getTableName() + "'"; String insert = "insert into " + SCHEMA_VERSION_TABLE + " values('" + getTableName() + "', " + version + ")"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected void requireNotComputed (String action) throws SQLException { if (getTableName() == null) { throw new IllegalArgumentException( "Can't " + action + " computed entities [class=" + _pclass + "]"); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns * or null if it did not define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The version of our persistent object schema as specified in the class * definition. */ protected int _schemaVersion = -1; /** Used when creating and migrating our table schema. */ protected ArrayList<String> _declarations = new ArrayList<String>(); /** Used when creating and migrating our table schema. */ protected String _postamble = ""; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered entity migrations to run prior to doing the default migration. */ protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.velocity; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Properties; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.context.Context; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.io.VelocityWriter; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.util.SimplePool; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.event.EventCartridge; import org.apache.velocity.app.event.MethodExceptionEventHandler; import com.samskivert.servlet.HttpErrorException; import com.samskivert.servlet.MessageManager; import com.samskivert.servlet.RedirectException; import com.samskivert.servlet.SiteIdentifier; import com.samskivert.servlet.SiteResourceLoader; import com.samskivert.servlet.util.FriendlyException; import com.samskivert.util.ConfigUtil; import com.samskivert.util.StringUtil; import static com.samskivert.Log.log; /** * The dispatcher servlet builds upon Velocity's architecture. It does so in the following ways: * * <ul> <li> It defines the notion of a logic object which populates the context with data to be * used to satisfy a particular request. The logic is not a servlet and is therefore limited in * what it can do while populating data. Experience dictates that ultimate flexibility leads to bad * design decisions and that this is a place where that sort of thing can be comfortably nipped in * the bud. <br><br> * * <li> It allows template files to be referenced directly in the URL while maintaining the ability * to choose a cobranded template based on information in the request. The URI is mapped to a * servlet based on some simple mapping rules. This provides template designers with a clearer * understanding of the structure of a web application as well as with an easy way to test their * templates in the absence of an associated servlet. <br><br> * * <li> It provides a common error handling paradigm that simplifies the task of authoring web * applications. * </ul> * * <p><b>URI to servlet mapping</b><br> The mapping process allows the Velocity framework to be * invoked for all requests ending in a particular file extension (usually <code>.wm</code>). It is * necessary to instruct your servlet engine of choice to invoke the <code>DispatcherServlet</code> * for all requests ending in that extension. For Apache/JServ this looks something like this: * * <pre> * ApJServAction .wm /servlets/com.samskivert.velocity.Dispatcher * </pre> * * The request URI then defines the path of the template that will be used to satisfy the * request. To understand how code is selected to go along with the request, let's look at an * example. Consider the following configuration: * * <pre> * applications=whowhere * whowhere.base_uri=/whowhere * whowhere.base_pkg=whowhere.logic * </pre> * * This defines an application identified as <code>whowhere</code>. An application is defined by * three parameters, the application identifier, the <code>base_uri</code>, and the * <code>base_pkg</code>. The <code>base_uri</code> defines the prefix shared by all pages served * by the application and which serves to identify which application to invoke when processing a * request. The <code>base_pkg</code> is used to construct the logic classname based on the URI and * the <code>base_uri</code> parameter. * * <p> Now let's look at a sample request to determine how the logic classname is * resolved. Consider the following request URI: * * <pre> * /whowhere/view/trips.wm * </pre> * * It begins with <code>/whowhere</code> which tells the dispatcher that it's part of the * <code>whowhere</code> application. That application's <code>base_uri</code> is then stripped * from the URI leaving <code>/view/trips.wm</code>. The slashes are converted into periods to map * directories to packages, giving us <code>view.trips.wm</code>. Finally, the * <code>base_pkg</code> is prepended and the trailing <code>.wm</code> extension removed. * * <p> Thus the class invoked to populate the context for this request is * <code>whowhere.servlets.view.trips</code> (note that the classname <em>is</em> lowercase which * is an intentional choice in resolving conflicting recommendations that classnames should always * start with a capital letter and URLs should always be lowercase). * * <p> The template used to generate the result is loaded based on the full URI, essentially with a * call to <code>getTemplate("/whowhere/view/trips.wm")</code> in this example. This is the place * where more sophisticated cobranding support could be inserted in the future (ie. if I ever want * to use this to develop a cobranded web site). * * @see Logic */ public class DispatcherServlet extends HttpServlet implements MethodExceptionEventHandler { /** The HTTP content type context key. */ public static final String CONTENT_TYPE = "default.contentType"; /** * Performs various initialization. */ public void init (ServletConfig config) throws ServletException { super.init(config); // load up our application configuration try { String appcl = config.getInitParameter(APP_CLASS_KEY); if (StringUtil.isBlank(appcl)) { _app = new Application(); } else { Class appclass = Class.forName(appcl); _app = (Application)appclass.newInstance(); } // now initialize the applicaiton String logicPkg = config.getInitParameter(LOGIC_PKG_KEY); _app.init(config, getServletContext(), StringUtil.isBlank(logicPkg) ? "" : logicPkg); } catch (Throwable t) { throw new ServletException("Error instantiating Application: " + t, t); } try { Velocity.init(loadConfiguration(config)); } catch (Exception e) { throw new ServletException("Error initializing Velocity: " + e, e); } _defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); // determine the character set we'll use _charset = config.getInitParameter(CHARSET_KEY); if (_charset == null) { _charset = "UTF-8"; } } /** * Handles HTTP <code>GET</code> requests by calling {@link #doRequest()}. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doRequest(request, response); } /** * Handles HTTP <code>POST</code> requests by calling {@link #doRequest()}. */ public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doRequest(request, response); } /** * Clean up after ourselves and our application. */ public void destroy () { super.destroy(); // shutdown our application _app.shutdown(); } /** * We load our velocity properties from the classpath rather than from a file. */ protected Properties loadConfiguration (ServletConfig config) throws IOException { String propsPath = config.getInitParameter(INIT_PROPS_KEY); if (propsPath == null) { throw new IOException(INIT_PROPS_KEY + " must point to the velocity properties file " + "in the servlet configuration."); } // config util loads properties files from the classpath Properties props = ConfigUtil.loadProperties(propsPath); if (props == null) { throw new IOException("Unable to load velocity properties " + "from file '" + INIT_PROPS_KEY + "'."); } // if we failed to create our application for whatever reason; bail if (_app == null) { return props; } // let the application set up velocity properties _app.configureVelocity(config, props); // if no file resource loader path has been set and a // site-specific jar file path was provided, wire up our site // resource manager if (props.getProperty("file.resource.loader.path") == null) { SiteResourceLoader siteLoader = _app.getSiteResourceLoader(); if (siteLoader != null) { log.info("Velocity loading templates from site loader."); props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS, SiteResourceManager.class.getName()); _usingSiteLoading = true; } else { // otherwise use a servlet context resource loader log.info("Velocity loading templates from servlet context."); props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS, ServletContextResourceManager.class.getName()); } } // wire up our #import directive props.setProperty("userdirective", ImportDirective.class.getName()); // configure the servlet context logger props.put(RuntimeSingleton.RUNTIME_LOG_LOGSYSTEM_CLASS, ServletContextLogger.class.getName()); // now return our augmented properties return props; } /** * Loads up the template appropriate for this request, locates and invokes any associated logic * class and finally returns the prepared template which will be merged with the prepared * context. */ public Template handleRequest (HttpServletRequest req, HttpServletResponse rsp, Context ctx) throws Exception { InvocationContext ictx = (InvocationContext)ctx; Logic logic = null; // listen for exceptions so that we can report them EventCartridge ec = ictx.getEventCartridge(); if (ec == null) { ec = new EventCartridge(); ec.attachToContext(ictx); ec.addEventHandler(this); } // if our application failed to initialize, fail with a 500 response if (_app == null) { rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } // obtain the siteid for this request and stuff that into the context int siteId = SiteIdentifier.DEFAULT_SITE_ID; SiteIdentifier ident = _app.getSiteIdentifier(); if (ident != null) { siteId = ident.identifySite(req); } if (_usingSiteLoading) { ctx.put("__siteid__", Integer.valueOf(siteId)); } // put the context path in the context as well to make it easier to // construct full paths ctx.put("context_path", req.getContextPath()); // then select the template Template tmpl = null; try { tmpl = selectTemplate(siteId, ictx); } catch (ResourceNotFoundException rnfe) { // send up a 404. For some annoying reason, Jetty tells Apache // that all is okay (200) when sending its own custom error pages, // forcing us to use Jetty's custom error page handling code rather // than passing it up the chain to be dealt with appropriately. rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } // assume the request is in the default character set unless it has // actually been sensibly supplied by the browser if (req.getCharacterEncoding() == null) { req.setCharacterEncoding(_charset); } // assume an HTML response in the default character set unless // otherwise massaged by the logic rsp.setContentType("text/html; charset=" + _charset); Exception error = null; try { // insert the application into the context in case the logic or a // tool wishes to make use of it ictx.put(APPLICATION_KEY, _app); // if the application provides a message manager, we want create a // translation tool and stuff that into the context MessageManager msgmgr = _app.getMessageManager(); if (msgmgr != null) { I18nTool i18n = new I18nTool(req, msgmgr); ictx.put(I18NTOOL_KEY, i18n); } // create a form tool for use by the template FormTool form = new FormTool(req); ictx.put(FORMTOOL_KEY, form); // create a new string tool for use by the template StringTool string = new StringTool(); ictx.put(STRINGTOOL_KEY, string); // create a new data tool for use by the tempate DataTool datatool = new DataTool(); ictx.put(DATATOOL_KEY, datatool); // create a curreny tool set up to use the correct locale CurrencyTool ctool = new CurrencyTool(req.getLocale()); ictx.put(CURRENCYTOOL_KEY, ctool); // allow the application to prepare the context _app.prepareContext(ictx); // allow the application to do global access control _app.checkAccess(ictx); // resolve the appropriate logic class for this URI and execute it // if it exists String path = req.getServletPath(); logic = resolveLogic(path); if (logic != null) { logic.invoke(_app, ictx); } } catch (Exception e) { error = e; } // if an error occurred processing the template, allow the application // to convert it to something more appropriate and then handle it String errmsg = null; try { if (error != null) { throw _app.translateException(error); } } catch (RedirectException re) { rsp.sendRedirect(re.getRedirectURL()); return null; } catch (HttpErrorException hee) { String msg = hee.getErrorMessage(); if (msg != null) { rsp.sendError(hee.getErrorCode(), msg); } else { rsp.sendError(hee.getErrorCode()); } return null; } catch (FriendlyException fe) { // grab the error message, we'll deal with it shortly errmsg = fe.getMessage(); } catch (Exception e) { errmsg = _app.handleException(req, logic, e); } // if we have an error message, insert it into the template if (errmsg != null) { // try using the application to localize the error message // before we insert it MessageManager msgmgr = _app.getMessageManager(); if (msgmgr != null) { errmsg = msgmgr.getMessage(req, errmsg); } ictx.put(ERROR_KEY, errmsg); } return tmpl; } /** * Called when a method throws an exception during template * evaluation. */ public Object methodException (Class clazz, String method, Exception e) throws Exception { log.log(Level.WARNING, "Exception [class=" + clazz.getName() + ", method=" + method + "].", e); return ""; } /** * Returns the reference to the application that is handling this * request. * * @return The application in effect for this request or null if no * application was selected to handle the request. */ public static Application getApplication (InvocationContext context) { return (Application)context.get(APPLICATION_KEY); } /** * Handles all requests (by default). * * @param request HttpServletRequest object containing client request. * @param response HttpServletResponse object for the response. */ protected void doRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InvocationContext context = null; try { context = new InvocationContext(request, response); setContentType(request, response); Template template = handleRequest(request, response, context); if (template != null) { mergeTemplate(template, context); } } catch (Exception e) { log.log(Level.WARNING, "doRequest failed [uri=" + request.getRequestURI() + "].", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } /** * Sets the content type of the response, defaulting to {@link #defaultContentType} if not * overriden. Delegates to {@link #chooseCharacterEncoding(HttpServletRequest)} to select the * appropriate character encoding. */ protected void setContentType (HttpServletRequest request, HttpServletResponse response) { String contentType = _defaultContentType; int index = contentType.lastIndexOf(';') + 1; if (index <= 0 || (index < contentType.length() && contentType.indexOf("charset", index) == -1)) { // append the character encoding which we'd like to use String encoding = chooseCharacterEncoding(request); if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) { contentType += "; charset=" + encoding; } } response.setContentType(contentType); } /** * Chooses the output character encoding to be used as the value for the "charset=" portion of * the HTTP Content-Type header (and thus returned by * <code>response.getCharacterEncoding()</code>). Called by {@link #setContentType} if an * encoding isn't already specified by Content-Type. By default, chooses the value of * RuntimeSingleton's <code>output.encoding</code> property. */ protected String chooseCharacterEncoding (HttpServletRequest request) { return RuntimeSingleton.getString( RuntimeConstants.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING); } /** * This method is called to select the appropriate template for this request. The default * implementation simply loads the template using Velocity's default template loading services * based on the URI provided in the request. * * @param ctx The context of this request. * * @return The template to be used in generating the response. */ protected Template selectTemplate (int siteId, InvocationContext ctx) throws ResourceNotFoundException, ParseErrorException, Exception { String path = ctx.getRequest().getServletPath(); if (_usingSiteLoading) { // if we're using site resource loading, we need to prefix the path with the site // identifier path = siteId + ":" + path; } // log.info("Loading template [path=" + path + "]."); return RuntimeSingleton.getTemplate(path); } protected void mergeTemplate (Template template, InvocationContext context) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, UnsupportedEncodingException, IOException, Exception { HttpServletResponse response = context.getResponse(); ServletOutputStream output = response.getOutputStream(); // ASSUMPTION: response.setContentType() has been called. String encoding = response.getCharacterEncoding(); VelocityWriter vw = null; try { vw = (VelocityWriter)_writerPool.get(); if (vw == null) { vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true); } else { vw.recycle(new OutputStreamWriter(output, encoding)); } template.merge(context, vw); } catch (IOException ioe) { // the client probably crashed or aborted the connection ungracefully, so use log.info log.info("Failed to write response [uri=" + context.getRequest().getRequestURI() + ", error=" + ioe + "]"); } finally { if (vw != null) { try { // flush and put back into the pool don't close to allow us to play nicely with // others. vw.flush(); } catch (IOException e) { // do nothing } // Clear the VelocityWriter's reference to its internal OutputStreamWriter to allow // the latter to be GC'd while vw is pooled. vw.recycle(null); _writerPool.put(vw); } } } /** * This method is called to select the appropriate logic for this request URI. * * @return The logic to be used in generating the response or null if no logic could be * matched. */ protected Logic resolveLogic (String path) { // look for a cached logic instance String lclass = _app.generateClass(path); Logic logic = _logic.get(lclass); if (logic == null) { try { Class pcl = Class.forName(lclass); logic = (Logic)pcl.newInstance(); } catch (ClassNotFoundException cnfe) { // nothing interesting to report } catch (Throwable t) { log.log(Level.WARNING, "Unable to instantiate logic for application [path=" + path + ", lclass=" + lclass + "].", t); } // if something failed, use a dummy in it's place so that we don't sit around all day // freaking out about our inability to instantiate the proper logic class if (logic == null) { logic = new DummyLogic(); } // cache the resolved logic instance _logic.put(lclass, logic); } return logic; } /** The application being served by this dispatcher servlet. */ protected Application _app; /** A table of resolved logic instances. */ protected HashMap<String,Logic> _logic = new HashMap<String,Logic>(); /** The character set in which serve our responses. */ protected String _charset; /** Set to true if we're using the {@link SiteResourceLoader}. */ protected boolean _usingSiteLoading; /** Our default content type. */ protected String _defaultContentType; /** A pool of VelocityWriter instances. */ protected static SimplePool _writerPool = new SimplePool(40); /** Describes the location of our properties. */ protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties"; /** This is the key used in the context for error messages. */ protected static final String ERROR_KEY = "error"; /** This is the key used to store a reference back to the dispatcher servlet in our invocation * context. */ protected static final String APPLICATION_KEY = "%_app_%"; /** The key used to store the translation tool in the context. */ protected static final String I18NTOOL_KEY = "i18n"; /** The key used to store the form tool in the context. */ protected static final String FORMTOOL_KEY = "form"; /** The key used to store the string tool in the context. */ protected static final String STRINGTOOL_KEY = "string"; /** The key used to store the data tool in the context. */ protected static final String DATATOOL_KEY = "data"; /** The key used to store the currency tool in the context. */ protected static final String CURRENCYTOOL_KEY = "cash"; /** The servlet parameter key specifying the application class. */ protected static final String APP_CLASS_KEY = "app_class"; /** The servlet parameter key specifying the base logic package. */ protected static final String LOGIC_PKG_KEY = "logic_package"; /** The servlet parameter key specifying the default character set. */ protected static final String CHARSET_KEY = "charset"; /** The default content type for responses. */ protected static final String DEFAULT_CONTENT_TYPE = "text/html"; /** The default encoding for the output stream. */ protected static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1"; }
package net.openhft.chronicle.map; import com.sun.nio.file.SensitivityWatchEventModifier; import net.openhft.chronicle.core.util.ThrowingFunction; import org.jetbrains.annotations.NotNull; import java.io.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; /** * A {@link Map} implementation that stores each entry as a file in a * directory. The <code>key</code> is the file name and the <code>value</code> * is the contents of the file. This map will only handle <code>String</code>'s. * <p> * The class is effectively an abstraction over a directory in the file system. * Therefore when the underlying files are changed an event will be fired to those * registered for notifications. * Since every write to this map will cause a change to underlying * file system the event will distinguish between a programmatic event * (i.e one caused my the actions of the map itself) and an event that * has been triggered as a direct result of a file being manipulated outside * this class. * <p> * Updates will be fired every time the file is saved but will be suppressed * if the value has not changed. To avoid temporary files (e.g. if edited in vi) * being included in the map, any file starting with a '.' will be ignored. * <p> * Note the {@link WatchService} is extremely OS dependant. Mas OSX registers * very few events if they are done quickly and there is a significant delay * between the event and the event being triggered. */ public class FilePerKeyMap implements Map<String, String>, Closeable { private final Path dirPath; private final Map<File, FileRecord> lastFile = new ConcurrentHashMap<>(); private final List<Consumer<FPMEvent>> listeners = new ArrayList<>(); private final Thread fileFpmWatcher; private volatile boolean closed = false; private boolean putReturnsNull; private boolean snappyValues; private ThrowingFunction<InputStream, InputStream, IOException> reading = i -> i; private ThrowingFunction<OutputStream, OutputStream, IOException> writing = o -> o; public FilePerKeyMap(String dir) throws IOException { this.dirPath = Paths.get(dir); Files.createDirectories(dirPath); WatchService watcher = FileSystems.getDefault().newWatchService(); dirPath.register(watcher, new WatchEvent.Kind[]{ StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY}, SensitivityWatchEventModifier.HIGH ); fileFpmWatcher = new Thread(new FPMWatcher(watcher), dir + "-watcher"); fileFpmWatcher.start(); } public void registerForEvents(Consumer<FPMEvent> listener) { listeners.add(listener); } public void unregisterForEvents(Consumer<FPMEvent> listener) { listeners.remove(listener); } public void valueMarshaller(ThrowingFunction<InputStream, InputStream, IOException> reading, ThrowingFunction<OutputStream, OutputStream, IOException> writing) { this.reading = reading; this.writing = writing; } private void fireEvent(FPMEvent event) { for (Consumer<FPMEvent> listener : listeners) { listener.accept(event); } } @Override public int size() { return (int) getFiles().count(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(Object key) { return getFiles().anyMatch(p -> p.getFileName().toString().equals(key)); } @Override public boolean containsValue(Object value) { return getFiles().anyMatch(p -> getFileContents(p).equals(value)); } @Override public String get(Object key) { Path path = dirPath.resolve((String) key); return getFileContents(path); } @Override public String put(String key, String value) { if (closed) throw new IllegalStateException("closed"); Path path = dirPath.resolve(key); String existingValue = putReturnsNull ? null : getFileContents(path); writeToFile(path, value); return existingValue; } @Override public String remove(Object key) { if (closed) throw new IllegalStateException("closed"); String existing = get(key); if (existing != null) { deleteFile(dirPath.resolve((String) key)); } return existing; } @Override public void putAll(Map<? extends String, ? extends String> m) { m.entrySet().stream().forEach(e -> put(e.getKey(), e.getValue())); } @Override public void clear() { getFiles().forEach(this::deleteFile); } @NotNull @Override public Set<String> keySet() { return getFiles().map(p -> p.getFileName().toString()) .collect(Collectors.toSet()); } @NotNull @Override public Collection<String> values() { return getFiles().map(p -> getFileContents(p)) .collect(Collectors.toSet()); } @NotNull @Override public Set<Entry<String, String>> entrySet() { return getFiles().map(p -> (Entry<String, String>) new FPMEntry(p.getFileName().toString(), getFileContents(p))) .collect(Collectors.toSet()); } private Stream<Path> getFiles() { try { return Files.walk(dirPath).filter(p -> !Files.isDirectory(p)); } catch (IOException e) { throw new RuntimeException(e); } } String getFileContents(Path path) { try { File file = path.toFile(); FileRecord last = lastFile.get(file); if (last != null && file.lastModified() == last.timestamp) return last.contents; return getFileContents0(path); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } String getFileContents0(Path path) throws IOException { if (!Files.exists(path)) return null; File file = path.toFile(); ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length()); byte[] bytes = new byte[1024]; try (InputStream fis = reading.apply(new FileInputStream(file))) { for (int len; (len = fis.read(bytes)) > 0; ) baos.write(bytes, 0, len); } return baos.toString(); } private void writeToFile(Path path, String value) { File file = path.toFile(); File tmpFile = new File(file.getParentFile(), "." + file.getName()); try (PrintWriter pw = new PrintWriter(new BufferedOutputStream(writing.apply(new FileOutputStream(tmpFile))))) { pw.write(value); } catch (IOException e) { throw new AssertionError(e); } tmpFile.renameTo(file); } private void deleteFile(Path path) { File key = path.toFile(); key.delete(); } public void close() { closed = true; fileFpmWatcher.interrupt(); } public void putReturnsNull(boolean putReturnsNull) { this.putReturnsNull = putReturnsNull; } public void snappyValues(boolean snappyValues) { this.snappyValues = snappyValues; } private static class FPMEntry<String> implements Entry<String, String> { private String key; private String value; public FPMEntry(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { String lastValue = this.value; this.value = value; return lastValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FPMEntry<?> fpmEntry = (FPMEntry<?>) o; if (key != null ? !key.equals(fpmEntry.key) : fpmEntry.key != null) return false; return !(value != null ? !value.equals(fpmEntry.value) : fpmEntry.value != null); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } } private class FPMWatcher implements Runnable { private final WatchService watcher; public FPMWatcher(WatchService watcher) { this.watcher = watcher; } @Override public void run() { try { while (true) { WatchKey key = null; try { key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { // todo log a warning. continue; } // get file name WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); String mapKey = fileName.toString(); if (mapKey.startsWith(".")) { //this avoids temporary files being added to the map continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { Path p = dirPath.resolve(fileName); try { String mapVal = getFileContents0(p); lastFile.put(p.toFile(), new FileRecord(p.toFile().lastModified(), mapVal)); fireEvent(new FPMEvent(FPMEvent.EventType.NEW, mapKey, null, mapVal)); } catch (FileNotFoundException ignored) { } } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { Path p = dirPath.resolve(fileName); FileRecord lastVal = lastFile.remove(p.toFile()); String lastContent = lastVal == null ? null : lastVal.contents; fireEvent(new FPMEvent(FPMEvent.EventType.DELETE, mapKey, lastContent, null)); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { try { Path p = dirPath.resolve(fileName); String mapVal = getFileContents0(p); String lastVal = null; if (mapVal != null) { FileRecord rec = lastFile.put(p.toFile(), new FileRecord(p.toFile().lastModified(), mapVal)); if (rec != null) lastVal = rec.contents; } if (lastVal != null && lastVal.equals(mapVal)) { //Nothing has changed don't fire an event continue; } fireEvent(new FPMEvent(FPMEvent.EventType.UPDATE, mapKey, lastVal, mapVal)); } catch (FileNotFoundException ignored) { } } } } catch (InterruptedException e) { return; } finally { if (key != null) key.reset(); } } } catch (Throwable e) { if (!closed) e.printStackTrace(); } } } } class FileRecord { final long timestamp; final String contents; FileRecord(long timestamp, String contents) { this.timestamp = timestamp; this.contents = contents; } }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media; import java.awt.Graphics2D; import java.awt.Shape; import java.util.ArrayList; import java.util.Comparator; import com.samskivert.util.ObserverList.ObserverOp; import com.samskivert.util.ObserverList; import com.samskivert.util.SortableArrayList; import com.samskivert.util.Tuple; /** * Manages, ticks, and paints {@link AbstractMedia}. */ public abstract class AbstractMediaManager implements MediaConstants { /** * Provides this media manager with its host and region manager. */ public void init (MediaHost host, RegionManager remgr) { _host = host; _remgr = remgr; } /** * Returns region manager in use by this manager. */ public RegionManager getRegionManager () { return _remgr; } /** * Creates a graphics that can be used to compute metrics or whatever else a media might need. * The caller should call {@link Graphics2D#dispose} on the returned object when it is done * with it. */ public Graphics2D createGraphics () { return _host.createGraphics(); } /** * Must be called every frame so that the media can be properly updated. */ public void tick (long tickStamp) { _tickStamp = tickStamp; tickAllMedia(tickStamp); dispatchNotifications(); // we clear our tick stamp when we're about to be painted, this lets us handle situations // when yet more media is slipped in between our being ticked and our being painted } /** * This will always be called prior to the {@link #paint} calls for a particular tick. Because * it is possible that there will be no dirty regions and thus no calls to {@link #paint} this * method exists so that the media manager can guarantee that it will be notified when all * ticking is complete and the painting phase has begun. */ public void willPaint () { // now that we're done ticking, we can safely clear this _tickStamp = 0; } /** * Renders all registered media in the given layer that intersect the supplied clipping * rectangle to the given graphics context. * * @param layer the layer to render; one of {@link #FRONT}, {@link #BACK}, or {@link #ALL}. * The front layer contains all animations with a positive render order; the back layer * contains all animations with a negative render order; all, both. */ public void paint (Graphics2D gfx, int layer, Shape clip) { for (int ii = 0, nn = _media.size(); ii < nn; ii++) { AbstractMedia media = _media.get(ii); int order = media.getRenderOrder(); try { if (((layer == ALL) || (layer == FRONT && order >= 0) || (layer == BACK && order < 0)) && clip.intersects(media.getBounds())) { media.paint(gfx); } } catch (Exception e) { Log.warning("Failed to render media [media=" + media + ", e=" + e + "]."); Log.logStackTrace(e); } } } /** * If the manager is paused for some length of time, it should be fast forwarded by the * appropriate number of milliseconds. This allows media to smoothly pick up where they left * off rather than abruptly jumping into the future, thinking that some outrageous amount of * time passed since their last tick. */ public void fastForward (long timeDelta) { if (_tickStamp > 0) { Log.warning("Egads! Asked to fastForward() during a tick."); Thread.dumpStack(); } for (int ii = 0, nn = _media.size(); ii < nn; ii++) { _media.get(ii).fastForward(timeDelta); } } /** * Returns true if the specified media is being managed by this media manager. */ public boolean isManaged (AbstractMedia media) { return _media.contains(media); } /** * Called by a {@link VirtualMediaPanel} when the view that contains our media is scrolled. * * @param dx the scrolled distance in the x direction (in pixels). * @param dy the scrolled distance in the y direction (in pixels). */ public void viewLocationDidChange (int dx, int dy) { // let our media know for (int ii = 0, ll = _media.size(); ii < ll; ii++) { _media.get(ii).viewLocationDidChange(dx, dy); } } /** * Called by a {@link AbstractMedia} when its render order has changed. */ public void renderOrderDidChange (AbstractMedia media) { if (_tickStamp > 0) { Log.warning("Egads! Render order changed during a tick."); Thread.dumpStack(); } _media.remove(media); _media.insertSorted(media, RENDER_ORDER); } /** * Calls {@link AbstractMedia#tick} on all media to give them a chance to move about, change * their look, generate dirty regions, and so forth. */ protected void tickAllMedia (long tickStamp) { // we use _tickpos so that it can be adjusted if media is added or removed during the tick // dispatch for (_tickpos = 0; _tickpos < _media.size(); _tickpos++) { tickMedia(_media.get(_tickpos), tickStamp); } _tickpos = -1; } /** * Inserts the specified media into this manager, return true on success. */ protected boolean insertMedia (AbstractMedia media) { if (_media.contains(media)) { Log.warning("Attempt to insert media more than once [media=" + media + "]."); Thread.dumpStack(); return false; } media.init(this); int ipos = _media.insertSorted(media, RENDER_ORDER); // if we've started our tick but have not yet painted our media, we need to take care that // this newly added media will be ticked before our upcoming render if (_tickStamp > 0L) { if (_tickpos == -1) { // if we're done with our own call to tick(), we need to tick this new media tickMedia(media, _tickStamp); } else if (ipos <= _tickpos) { // otherwise, we're in the middle of our call to tick() and we only need to tick // this guy if he's being inserted before our current tick position (if he's // inserted after our current position, we'll get to him as part of this tick // iteration) _tickpos++; tickMedia(media, _tickStamp); } } return true; } /** A helper function used to call {@link AbstractMedia#tick}. */ protected final void tickMedia (AbstractMedia media, long tickStamp) { if (media._firstTick == 0L) { media.willStart(tickStamp); } media.tick(tickStamp); } /** * Removes the specified media from this manager, return true on success. */ protected boolean removeMedia (AbstractMedia media) { int mpos = _media.indexOf(media); if (mpos != -1) { _media.remove(mpos); media.invalidate(); media.shutdown(); // if we're in the middle of ticking, we need to adjust the _tickpos if necessary if (mpos <= _tickpos) { _tickpos } return true; } Log.warning("Attempt to remove media that wasn't inserted [media=" + media + "]."); return false; } /** * Clears all media from the manager and calls {@link AbstractMedia#shutdown} on each. This * does not invalidate the media's vacated bounds; it is assumed that it will be ok. */ protected void clearMedia () { if (_tickStamp > 0) { Log.warning("Egads! Requested to clearMedia() during a tick."); Thread.dumpStack(); } for (int ii = _media.size() - 1; ii >= 0; ii _media.remove(ii).shutdown(); } } /** * Queues the notification for dispatching after we've ticked all the media. */ public void queueNotification (ObserverList observers, ObserverOp event) { _notify.add(new Tuple<ObserverList,ObserverOp>(observers, event)); } /** Type safety jockeying. */ protected abstract SortableArrayList<? extends AbstractMedia> createMediaList (); /** * Dispatches all queued media notifications. */ protected void dispatchNotifications () { for (int ii = 0, nn = _notify.size(); ii < nn; ii++) { Tuple<ObserverList,ObserverOp> tuple = _notify.get(ii); tuple.left.apply(tuple.right); } _notify.clear(); } /** The media host we're working with. */ protected MediaHost _host; /** The region manager. */ protected RegionManager _remgr; /** List of observers to notify at the end of the tick. */ protected ArrayList<Tuple<ObserverList,ObserverOp>> _notify = new ArrayList<Tuple<ObserverList,ObserverOp>>(); /** Our render-order sorted list of media. */ @SuppressWarnings("unchecked") protected SortableArrayList<AbstractMedia> _media = (SortableArrayList<AbstractMedia>)createMediaList(); /** The position in our media list that we're ticking (while in the middle of a call to {@link * #tick}) otherwise -1. */ protected int _tickpos = -1; /** The tick stamp if the manager is in the midst of a call to {@link #tick}, else 0. */ protected long _tickStamp; /** Used to sort media by render order. */ protected static final Comparator<AbstractMedia> RENDER_ORDER = new Comparator<AbstractMedia>() { public int compare (AbstractMedia am1, AbstractMedia am2) { int result = am1._renderOrder - am2._renderOrder; // if render order is same, use hashcode to keep them stable relative to each other return (result != 0) ? result : am1.hashCode() - am2.hashCode(); } }; }
// Vilya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.server; import com.samskivert.util.IntMap; import com.samskivert.util.IntMaps; import com.samskivert.util.ListUtil; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.presents.dobj.ChangeListener; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.NamedEvent; import com.threerings.presents.dobj.ObjectAddedEvent; import com.threerings.presents.dobj.ObjectDeathListener; import com.threerings.presents.dobj.ObjectDestroyedEvent; import com.threerings.presents.dobj.ObjectRemovedEvent; import com.threerings.presents.dobj.OidListListener; import com.threerings.presents.dobj.RootDObjectManager; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.InvocationManager; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.server.PlaceRegistry; import com.threerings.parlor.client.TableService; import com.threerings.parlor.data.ParlorCodes; import com.threerings.parlor.data.Table; import com.threerings.parlor.data.TableConfig; import com.threerings.parlor.data.TableLobbyObject; import com.threerings.parlor.game.data.GameConfig; import com.threerings.parlor.game.data.GameObject; import com.threerings.parlor.game.server.GameManager; import static com.threerings.parlor.Log.log; /** * A table manager can be used by a place manager (or other entity) to take care of the management * of a table matchmaking service on a particular distributed object. */ public class TableManager implements ParlorCodes, TableProvider { /** * Creates a table manager that will manage tables in the supplied distributed object (which * must implement {@link TableLobbyObject}. */ public TableManager (RootDObjectManager omgr, InvocationManager invmgr, PlaceRegistry plreg, DObject tableObject) { _omgr = omgr; _invmgr = invmgr; _plreg = plreg; // set up our object references _tlobj = (TableLobbyObject)tableObject; _tlobj.setTableService(invmgr.registerDispatcher(new TableDispatcher(this))); _dobj = tableObject; // if our table is in a "place" add ourselves as a listener so that we can tell if a user // leaves the place without leaving their table if (_dobj instanceof PlaceObject) { _dobj.addListener(_placeListener); } } /** * This must be called when the table manager is no longer needed. */ public void shutdown () { if (_tlobj != null) { _invmgr.clearDispatcher(_tlobj.getTableService()); _tlobj.setTableService(null); } if (_dobj instanceof PlaceObject) { _dobj.removeListener(_placeListener); } _tlobj = null; _dobj = null; } /** * Set the subclass of Table that this instance should generate. */ public void setTableClass (Class<? extends Table> tableClass) { _tableClass = tableClass; } /** * Allow a player in the first position of a table to boot others. */ public void setAllowBooting (boolean allowBooting) { _allowBooting = allowBooting; } /** * Creates a table for the specified creator and returns said table. * * @exception InvocationException thrown if the table could not be created for any reason. */ public Table createTable (BodyObject creator, TableConfig tableConfig, GameConfig config) throws InvocationException { // make sure the caller is not already in a table if (_boidMap.containsKey(creator.getOid())) { throw new InvocationException(ALREADY_AT_TABLE); } // create a brand spanking new table Table table; try { table = _tableClass.newInstance(); } catch (Exception e) { log.warning("Table.newInstance() failed [class=" + _tableClass + ", e=" + e + "]."); throw new InvocationException(INTERNAL_ERROR); } table.init(_dobj.getOid(), tableConfig, config); if (table.bodyOids != null && table.bodyOids.length > 0) { // stick the creator into the first non-AI position int cpos = (config.ais == null) ? 0 : config.ais.length; String error = table.setPlayer(cpos, creator); if (error != null) { log.warning("Unable to add creator to position zero of table!? [table=" + table + ", creator=" + creator + ", error=" + error + "]."); // bail out now and abort the table creation process throw new InvocationException(error); } // make a mapping from the creator to this table notePlayerAdded(table, creator); } // stick the table into the table lobby object _tlobj.addToTables(table); // also stick it into our tables tables _tables.put(table.tableId, table); // if the table has only one seat, start the game immediately if (table.shouldBeStarted()) { createGame(table); } return table; } // from interface TableProvider public void createTable (ClientObject caller, TableConfig tableConfig, GameConfig config, TableService.ResultListener listener) throws InvocationException { BodyObject creator = (BodyObject)caller; // if we're managing tables in a place, make sure the creator is an occupant of the place // in which they are requesting to create a table if (_dobj instanceof PlaceObject && !((PlaceObject)_dobj).occupants.contains(creator.getOid())) { log.warning("Requested to create a table in a place not occupied by the creator " + "[creator=" + creator + ", ploid=" + _dobj.getOid() + "]."); throw new InvocationException(INTERNAL_ERROR); } // if createTable() returns, we're good to go listener.requestProcessed(createTable(creator, tableConfig, config).tableId); } // from interface TableProvider public void joinTable (ClientObject caller, int tableId, int position, TableService.InvocationListener listener) throws InvocationException { BodyObject joiner = (BodyObject)caller; // make sure the caller is not already in a table if (_boidMap.containsKey(joiner.getOid())) { throw new InvocationException(ALREADY_AT_TABLE); } // look the table up Table table = _tables.get(tableId); if (table == null) { throw new InvocationException(NO_SUCH_TABLE); } // request that the user be added to the table at that position String error = table.setPlayer(position, joiner); // if that failed, report the error if (error != null) { throw new InvocationException(error); } // if the table is sufficiently full, start the game automatically if (table.shouldBeStarted()) { createGame(table); } else { // make a mapping from this player to this table notePlayerAdded(table, joiner); } // update the table in the lobby _tlobj.updateTables(table); // there is normally no success response. the client will see // themselves show up in the table that they joined } // from interface TableProvider public void leaveTable (ClientObject caller, int tableId, TableService.InvocationListener listener) throws InvocationException { BodyObject leaver = (BodyObject)caller; // look the table up Table table = _tables.get(tableId); if (table == null) { throw new InvocationException(NO_SUCH_TABLE); } // if the table is in play, the user is not allowed to leave (he must leave the game) if (table.inPlay()) { throw new InvocationException(GAME_ALREADY_STARTED); } // request that the user be removed from the table if (!table.clearPlayer(leaver.getVisibleName())) { throw new InvocationException(NOT_AT_TABLE); } // remove the mapping from this user to the table if (null == notePlayerRemoved(leaver.getOid(), leaver)) { log.warning("No body to table mapping to clear? [leaver=" + leaver.who() + ", table=" + table + "]."); } // either update or delete the table depending on whether or not we just removed the last // player if (table.isEmpty()) { purgeTable(table); } else { _tlobj.updateTables(table); } // there is normally no success response. the client will see // themselves removed from the table they just left } // from interface TableProvider public void startTableNow (ClientObject caller, int tableId, TableService.InvocationListener listener) throws InvocationException { BodyObject starter = (BodyObject)caller; Table table = _tables.get(tableId); if (table == null) { throw new InvocationException(NO_SUCH_TABLE); } else if (starter.getOid() != table.bodyOids[0]) { throw new InvocationException(MUST_BE_CREATOR); } else if (!table.mayBeStarted()) { throw new InvocationException(INTERNAL_ERROR); } createGame(table); } // from interface TableProvider public void bootPlayer (ClientObject caller, int tableId, Name target, TableService.InvocationListener listener) throws InvocationException { BodyObject booter = (BodyObject) caller; Table table = _tables.get(tableId); if (table == null) { throw new InvocationException(NO_SUCH_TABLE); } else if ( ! _allowBooting) { throw new InvocationException(INTERNAL_ERROR); } int position = ListUtil.indexOf(table.players, target); if (position < 0) { throw new InvocationException(NOT_AT_TABLE); } else if (booter.getOid() != table.bodyOids[0]) { throw new InvocationException(MUST_BE_CREATOR); } else if (booter.getOid() == table.bodyOids[position]) { throw new InvocationException(NO_SELF_BOOT); } // Remember to keep him banned table.addBannedUser(target); // Remove the player from the table if (notePlayerRemoved(table.bodyOids[position]) == null) { log.warning("No body to table mapping to clear? [position=" + position + ", table=" + table + "]."); } table.clearPlayerPos(position); _tlobj.updateTables(table); } /** * Removes the table from all of our internal tables and from its lobby's distributed object. */ protected void purgeTable (Table table) { // remove the table from our tables table _tables.remove(table.tableId); // clear out all matching entries in the boid map if (table.bodyOids != null) { for (int ii = 0; ii < table.bodyOids.length; ii++) { if (table.bodyOids[ii] != 0) { notePlayerRemoved(table.bodyOids[ii]); } } } // remove the mapping by gameOid Table removed = _goidMap.remove(table.gameOid); // no-op if gameOid == 0 // remove the table from the lobby object _tlobj.removeFromTables(table.tableId); // remove the listener too so we do not get a request later on to update the occupants or // unmap this table if (removed != null) { DObject gameObj = _omgr.getObject(table.gameOid); if (gameObj != null) { gameObj.removeListener(_gameListener); } } } /** * Called when a player is added to a table to set up our mappings. */ protected void notePlayerAdded (Table table, BodyObject body) { _boidMap.put(body.getOid(), table); body.addListener(_userListener); } /** * Called when a player leaves the room and we're not sure if the user is still online. */ final protected Table notePlayerRemoved (int playerOid) { return notePlayerRemoved(playerOid, (BodyObject)_omgr.getObject(playerOid)); } /** * Called when a player leaves a table to clear our mappings. * @param body will be non-null if the user is still online. */ protected Table notePlayerRemoved (int playerOid, BodyObject body) { if (body != null) { body.removeListener(_userListener); } return _boidMap.remove(playerOid); } /** * Called when we're ready to create a game (either an invitation has been accepted or a table * is ready to start. If there is a problem creating the game manager, it should be reported in * the logs. * * @return the oid of the newly-created game. */ protected int createGame (final Table table) throws InvocationException { try { GameManager gmgr = createGameManager(createConfig(table)); GameObject gobj = (GameObject)gmgr.getPlaceObject(); gameCreated(table, gobj, gmgr); return gobj.getOid(); } catch (Throwable t) { log.warning("Failed to create manager for game [config=" + table.config + "]: " + t); throw new InvocationException(INTERNAL_ERROR); } } /** * This method should validate that the (client provided) configuration in the supplied {@link * Table} object is valid and fill in any extra information that is the purview of the server. */ protected GameConfig createConfig (Table table) { // fill the players array into the game config table.config.players = table.getPlayers(); // we just trust the rest by default, yay! return table.config; } /** * Creates a {@link GameManager} using the supplied config. Used by {@link #createGame}, but * extracted into a method to allow customization of this process. */ protected GameManager createGameManager (GameConfig config) throws InstantiationException, InvocationException { return (GameManager)_plreg.createPlace(config); } /** * Called when our game has been created, we take this opportunity to clean up the table and * transition it to "in play" mode. */ protected void gameCreated (Table table, GameObject gameobj, GameManager gmgr) { // update the table with the newly created game object table.gameOid = gameobj.getOid(); // add it to the gameOid map _goidMap.put(table.gameOid, table); // configure the privacy of the game gameobj.setIsPrivate(table.tconfig.privateTable); if (table.bodyOids != null) { // clear the player to table mappings as this game is underway for (int ii = 0; ii < table.bodyOids.length; ii++) { if (table.bodyOids[ii] != 0) { notePlayerRemoved(table.bodyOids[ii]); } } } // add an object death listener to unmap the table when the game finally goes away gameobj.addListener(_gameListener); // and then update the lobby object that contains the table _tlobj.updateTables(table); } /** * Called when a game created from a table managed by this table manager was destroyed. We * remove the associated table. */ protected void unmapTable (int gameOid) { // if we've been shutdown, then we've got nothing to worry about if (_tlobj == null) { return; } Table table = _goidMap.get(gameOid); if (table != null) { purgeTable(table); } else { log.warning("Requested to unmap table that wasn't mapped [gameOid=" + gameOid + "]."); } } /** * Called when the occupants in a game change: publishes new info. */ protected void updateOccupants (int gameOid) { // if we've been shutdown, then we've got nothing to worry about if (_tlobj == null) { return; } Table table = _goidMap.get(gameOid); if (table == null) { log.warning("Unable to find table for running game [gameOid=" + gameOid + "]."); return; } // update this table's occupants information and update the table GameObject gameObj = (GameObject)_omgr.getObject(gameOid); table.updateOccupants(gameObj); _tlobj.updateTables(table); } /** * Called when a body is known to have left either the room that contains our tables or logged * off of the server. */ protected void bodyLeft (int bodyOid) { // look up the table to which this player is mapped Table pender = notePlayerRemoved(bodyOid); if (pender == null) { return; } // remove this player from the table if (!pender.clearPlayerByOid(bodyOid)) { log.warning("Attempt to remove body from mapped table failed [table=" + pender + ", bodyOid=" + bodyOid + "]."); return; } // either update or delete the table depending on whether or not we just removed the last // player if (pender.isEmpty()) { purgeTable(pender); } else { _tlobj.updateTables(pender); } } /** Listens to all games and updates the table objects as necessary. */ protected class GameListener implements ObjectDeathListener, OidListListener { // from ObjectDeathListener public void objectDestroyed (ObjectDestroyedEvent event) { unmapTable(event.getTargetOid()); } // from OidListListener public void objectAdded (ObjectAddedEvent event) { maybeCheckOccupants(event); } // from OidListListener public void objectRemoved (ObjectRemovedEvent event) { maybeCheckOccupants(event); } /** Check to see if the set event causes us to update the table. */ protected void maybeCheckOccupants (NamedEvent event) { if (GameObject.OCCUPANTS.equals(event.getName())) { updateOccupants(event.getTargetOid()); } } } // END: class GameDeathListener /** Listens to all users who have joined a table, takes care of removing them * as necessary. */ protected class UserListener implements AttributeChangeListener, ObjectDeathListener { // from AttributeChangeListener public void attributeChanged (AttributeChangedEvent event) { // Remove folks from tables when they disconnect if (BodyObject.STATUS.equals(event.getName())) { if (event.getByteValue() == OccupantInfo.DISCONNECTED) { bodyLeft(event.getTargetOid()); } } } // from ObjectDeathListener public void objectDestroyed (ObjectDestroyedEvent event) { // Remove folks from tables when they die bodyLeft(event.getTargetOid()); } } // END: class UserListener /** Listens for players leaving the place that contains our tables. */ protected ChangeListener _placeListener = new OidListListener() { public void objectAdded (ObjectAddedEvent event) { // nothing doing } public void objectRemoved (ObjectRemovedEvent event) { // if an occupant departed, see if they are in a pending table if (event.getName().equals(PlaceObject.OCCUPANTS)) { bodyLeft(event.getOid()); } } }; /** A reference to the distributed object in which we're managing tables. */ protected DObject _dobj; /** A reference to our distributed object casted to a table lobby object. */ protected TableLobbyObject _tlobj; /** The class of table we instantiate. */ protected Class<? extends Table> _tableClass = Table.class; /** The table of pending tables. */ protected IntMap<Table> _tables = IntMaps.newHashIntMap(); /** A mapping from body oid to table. */ protected IntMap<Table> _boidMap = IntMaps.newHashIntMap(); /** Once a game starts, a mapping from gameOid to table. */ protected IntMap<Table> _goidMap = IntMaps.newHashIntMap(); /** A listener that prunes tables after the game dies. */ protected ChangeListener _gameListener = new GameListener(); /** A listener that removes users from tables when they're no longer able to play. */ protected ChangeListener _userListener = new UserListener(); /** Whether or not tables should support booting. */ protected boolean _allowBooting = false; protected RootDObjectManager _omgr; protected InvocationManager _invmgr; protected PlaceRegistry _plreg; }
package com.weblyzard.api.client; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.BadRequestException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotAllowedException; import javax.ws.rs.NotAuthorizedException; import javax.ws.rs.NotFoundException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.glassfish.jersey.logging.LoggingFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import lombok.extern.slf4j.Slf4j; @Slf4j public abstract class BasicClient { private static final String ENV_WEBLYZARD_API_URL = "WEBLYZARD_API_URL"; private static final String ENV_WEBLYZARD_API_USER = "WEBLYZARD_API_USER"; private static final String ENV_WEBLYZARD_API_PASS = "WEBLYZARD_API_PASS"; private static final String FALLBACK_WEBLYZARD_API_URL = "http://localhost:8080"; private static final String ENV_WEBLYZARD_API_DEBUG = "WEBLYZARD_API_DEBUG"; private final WebTarget baseTarget; private Map<String, WebTarget> webTargets = new ConcurrentHashMap<>(); private Logger logger = Logger.getLogger(getClass().getName()); /** Constructor using environment variables. */ public BasicClient() { this(System.getenv(ENV_WEBLYZARD_API_URL)); ClientBuilder.newClient(); } /** * Constructor using environment variables with a custom url. * * @param weblyzardUrl the url to the service, or FALLBACK_WEBLYZARD_API_URL if null */ public BasicClient(String weblyzardUrl) { this(weblyzardUrl, System.getenv(ENV_WEBLYZARD_API_USER), System.getenv(ENV_WEBLYZARD_API_PASS)); } /** * Constructor using a custom url, username and password. * * @param weblyzardUrl the url to the service, or FALLBACK_WEBLYZARD_API_URL if null * @param username may be null * @param password may be null */ public BasicClient(String weblyzardUrl, String username, String password) { ClientConfig config = new ClientConfig(); if (Boolean.parseBoolean(System.getenv(ENV_WEBLYZARD_API_DEBUG))) { // https://jersey.java.net/documentation/latest/user-guide.html#logging_chapter // -> Example 21.1. Logging on client-side config.register(new LoggingFeature(logger, Level.SEVERE, LoggingFeature.Verbosity.PAYLOAD_TEXT, LoggingFeature.DEFAULT_MAX_ENTITY_SIZE)); } if (username != null && password != null) { config.register(HttpAuthenticationFeature.basicBuilder().credentials(username, password) .build()); } this.baseTarget = ClientBuilder.newClient(config) .target(weblyzardUrl == null ? FALLBACK_WEBLYZARD_API_URL : weblyzardUrl) .register(new JacksonJsonProvider()); } public WebTarget getTarget(String urlTemplate) { this.webTargets.putIfAbsent(urlTemplate, this.baseTarget.path(urlTemplate)); return this.webTargets.get(urlTemplate); } public WebTarget getBaseTarget() { return this.baseTarget; } public void checkResponseStatus(Response response) throws WebApplicationException { switch (response.getStatus()) { case 200: return; case 204: return; case 400: throw new BadRequestException(response); case 401: throw new NotAuthorizedException(response); case 404: throw new NotFoundException(response); case 405: throw new NotAllowedException(response); case 500: throw new InternalServerErrorException(response); default: throw new WebApplicationException(response); } } }
package net.sf.xenqtt.client; import java.net.ConnectException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.sf.xenqtt.Log; import net.sf.xenqtt.MqttCommandCancelledException; import net.sf.xenqtt.MqttInterruptedException; import net.sf.xenqtt.MqttQosNotGrantedException; import net.sf.xenqtt.MqttTimeoutException; import net.sf.xenqtt.message.ChannelManager; import net.sf.xenqtt.message.ChannelManagerImpl; import net.sf.xenqtt.message.ConnAckMessage; import net.sf.xenqtt.message.ConnectMessage; import net.sf.xenqtt.message.ConnectReturnCode; import net.sf.xenqtt.message.DisconnectMessage; import net.sf.xenqtt.message.MessageHandler; import net.sf.xenqtt.message.MqttChannel; import net.sf.xenqtt.message.MqttChannelRef; import net.sf.xenqtt.message.MqttMessage; import net.sf.xenqtt.message.PubAckMessage; import net.sf.xenqtt.message.PubCompMessage; import net.sf.xenqtt.message.PubMessage; import net.sf.xenqtt.message.PubRecMessage; import net.sf.xenqtt.message.PubRelMessage; import net.sf.xenqtt.message.QoS; import net.sf.xenqtt.message.SubAckMessage; import net.sf.xenqtt.message.SubscribeMessage; import net.sf.xenqtt.message.UnsubAckMessage; import net.sf.xenqtt.message.UnsubscribeMessage; /** * Base class for both synchronous and asynchronous {@link MqttClient} implementations */ abstract class AbstractMqttClient implements MqttClient { private final String brokerUri; private final ChannelManager manager; private final ReconnectionStrategy reconnectionStrategy; private final Executor executor; private final ExecutorService executorService; private final ScheduledExecutorService reconnectionExecutor; private final MessageHandler messageHandler; private final MqttClientListener mqttClientListener; private final AsyncClientListener asyncClientListener; private final Map<Integer, Object> dataByMessageId; private final AtomicInteger messageIdGenerator = new AtomicInteger(); private volatile MqttChannelRef channel; private volatile ConnectMessage connectMessage; private volatile boolean firstConnectPending = true; private volatile List<MqttMessage> unsentMessages; // FIXME [jim] - add constructors that take host/port and ctors that take URI /** * Constructs a synchronous instance of this class using an {@link Executor} owned by this class. * * @param brokerUri * The URL to the broker to connect to. For example, tcp://q.m2m.io:1883 * @param mqttClientListener * Handles events from this client's channel * @param reconnectionStrategy * The algorithm used to reconnect to the broker if the connection is lost * @param messageHandlerThreadPoolSize * The number of threads used to handle incoming messages and invoke the {@link AsyncClientListener listener's} methods * @param messageResendIntervalSeconds * Seconds between attempts to resend a message that is {@link MqttMessage#isAckable()}. 0 to disable message resends * @param blockingTimeoutSeconds * Seconds until a blocked method invocation times out and an {@link MqttTimeoutException} is thrown. -1 will create a non-blocking API, 0 will * create a blocking API with no timeout, > 0 will create a blocking API with the specified timeout. */ AbstractMqttClient(String brokerUri, MqttClientListener mqttClientListener, ReconnectionStrategy reconnectionStrategy, int messageHandlerThreadPoolSize, int messageResendIntervalSeconds, int blockingTimeoutSeconds) { this(brokerUri, mqttClientListener, null, reconnectionStrategy, Executors.newFixedThreadPool(messageHandlerThreadPoolSize), messageResendIntervalSeconds, blockingTimeoutSeconds); } /** * Constructs a synchronous instance of this class using a user provided {@link Executor}. * * @param brokerUri * The URL to the broker to connect to. For example, tcp://q.m2m.io:1883 * @param mqttClientListener * Handles events from this client's channel * @param reconnectionStrategy * The algorithm used to reconnect to the broker if the connection is lost * @param executor * The executor used to handle incoming messages and invoke the {@link AsyncClientListener listener's} methods. This class will NOT shut down the * executor. * @param messageResendIntervalSeconds * Seconds between attempts to resend a message that is {@link MqttMessage#isAckable()}. 0 to disable message resends * @param blockingTimeoutSeconds * Seconds until a blocked method invocation times out and an {@link MqttTimeoutException} is thrown. -1 will create a non-blocking API, 0 will * create a blocking API with no timeout, > 0 will create a blocking API with the specified timeout. */ AbstractMqttClient(String brokerUri, MqttClientListener mqttClientListener, ReconnectionStrategy reconnectionStrategy, Executor executor, int messageResendIntervalSeconds, int blockingTimeoutSeconds) { this(brokerUri, mqttClientListener, null, reconnectionStrategy, executor, messageResendIntervalSeconds, blockingTimeoutSeconds); } /** * Constructs an asynchronous instance of this class using an {@link Executor} owned by this class. * * @param brokerUri * The URL to the broker to connect to. For example, tcp://q.m2m.io:1883 * @param AsyncClientListener * asyncClientListener Handles events from this client's channel * @param reconnectionStrategy * The algorithm used to reconnect to the broker if the connection is lost * @param messageHandlerThreadPoolSize * The number of threads used to handle incoming messages and invoke the {@link AsyncClientListener listener's} methods * @param messageResendIntervalSeconds * Seconds between attempts to resend a message that is {@link MqttMessage#isAckable()}. 0 to disable message resends */ AbstractMqttClient(String brokerUri, AsyncClientListener asyncClientListener, ReconnectionStrategy reconnectionStrategy, int messageHandlerThreadPoolSize, int messageResendIntervalSeconds) { this(brokerUri, asyncClientListener, asyncClientListener, reconnectionStrategy, Executors.newFixedThreadPool(messageHandlerThreadPoolSize), messageResendIntervalSeconds, -1); } /** * Constructs an asynchronous instance of this class using a user provided {@link Executor}. * * @param brokerUri * The URL to the broker to connect to. For example, tcp://q.m2m.io:1883 * @param asyncClientListener * Handles events from this client's channel * @param reconnectionStrategy * The algorithm used to reconnect to the broker if the connection is lost * @param executor * The executor used to handle incoming messages and invoke the {@link AsyncClientListener listener's} methods. This class will NOT shut down the * executor. * @param messageResendIntervalSeconds * Seconds between attempts to resend a message that is {@link MqttMessage#isAckable()}. 0 to disable message resends */ AbstractMqttClient(String brokerUri, AsyncClientListener asyncClientListener, ReconnectionStrategy reconnectionStrategy, Executor executor, int messageResendIntervalSeconds) { this(brokerUri, asyncClientListener, asyncClientListener, reconnectionStrategy, executor, messageResendIntervalSeconds, -1); } /** * @see net.sf.xenqtt.client.MqttClient#connect(java.lang.String, boolean, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, * net.sf.xenqtt.message.QoS, boolean) */ @Override public final ConnectReturnCode connect(String clientId, boolean cleanSession, int keepAliveSeconds, String userName, String password, String willTopic, String willMessage, QoS willQos, boolean willRetain) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { ConnectMessage message = new ConnectMessage(clientId, cleanSession, keepAliveSeconds, userName, password, willTopic, willMessage, willQos, willRetain); return doConnect(message); } /** * @see net.sf.xenqtt.client.MqttClient#connect(java.lang.String, boolean, int) */ @Override public final ConnectReturnCode connect(String clientId, boolean cleanSession, int keepAliveSeconds) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { ConnectMessage message = new ConnectMessage(clientId, cleanSession, keepAliveSeconds); return doConnect(message); } /** * @see net.sf.xenqtt.client.MqttClient#connect(java.lang.String, boolean, int, java.lang.String, java.lang.String) */ @Override public final ConnectReturnCode connect(String clientId, boolean cleanSession, int keepAliveSeconds, String userName, String password) throws MqttCommandCancelledException, MqttTimeoutException, InterruptedException { ConnectMessage message = new ConnectMessage(clientId, cleanSession, keepAliveSeconds, userName, password); return doConnect(message); } /** * @see net.sf.xenqtt.client.MqttClient#connect(java.lang.String, boolean, int, java.lang.String, java.lang.String, net.sf.xenqtt.message.QoS, boolean) */ @Override public final ConnectReturnCode connect(String clientId, boolean cleanSession, int keepAliveSeconds, String willTopic, String willMessage, QoS willQos, boolean willRetain) throws MqttTimeoutException, MqttInterruptedException { ConnectMessage message = new ConnectMessage(clientId, cleanSession, keepAliveSeconds, willTopic, willMessage, willQos, willRetain); return doConnect(message); } /** * @see net.sf.xenqtt.client.MqttClient#disconnect() */ @Override public final void disconnect() throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { DisconnectMessage message = new DisconnectMessage(); manager.send(channel, message); } /** * @see net.sf.xenqtt.client.MqttClient#subscribe(net.sf.xenqtt.client.Subscription[]) */ @Override public final Subscription[] subscribe(Subscription[] subscriptions) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { String[] topics = new String[subscriptions.length]; QoS[] requestedQoses = new QoS[subscriptions.length]; for (int i = 0; i < subscriptions.length; i++) { topics[i] = subscriptions[i].getTopic(); requestedQoses[i] = subscriptions[i].getQos(); } int messageId = nextMessageId(subscriptions); SubscribeMessage message = new SubscribeMessage(messageId, topics, requestedQoses); SubAckMessage ack = manager.send(channel, message); return ack == null ? null : grantedSubscriptions(subscriptions, ack); } /** * @see net.sf.xenqtt.client.MqttClient#subscribe(java.util.List) */ @Override public final List<Subscription> subscribe(List<Subscription> subscriptions) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { Subscription[] array = subscribe(subscriptions.toArray(new Subscription[subscriptions.size()])); return array == null ? null : Arrays.asList(array); } /** * @see net.sf.xenqtt.client.MqttClient#unsubscribe(java.lang.String[]) */ @Override public final void unsubscribe(String[] topics) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { int messageId = nextMessageId(topics); UnsubscribeMessage message = new UnsubscribeMessage(messageId, topics); manager.send(channel, message); } /** * @see net.sf.xenqtt.client.MqttClient#unsubscribe(java.util.List) */ @Override public final void unsubscribe(List<String> topics) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { unsubscribe(topics.toArray(new String[topics.size()])); } /** * @see net.sf.xenqtt.client.MqttClient#publish(net.sf.xenqtt.client.PublishMessage) */ @Override public final void publish(PublishMessage message) throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { // FIXME [jim] - test message not set at qos 0 if (message.pubMessage.getQoSLevel() > 0) { int messageId = nextMessageId(message); message.pubMessage.setMessageId(messageId); } manager.send(channel, message.pubMessage); } /** * @see net.sf.xenqtt.client.MqttClient#close() */ @Override public final void close() throws MqttCommandCancelledException, MqttTimeoutException, MqttInterruptedException { manager.close(channel); } /** * Stops this client. Closes the connection to the broker if it is open. Blocks until shutdown is complete. Any other methods called after this have * unpredictable results. * * @throws MqttInterruptedException * If the thread is {@link Thread#interrupt() interrupted} */ public final void shutdown() throws MqttInterruptedException { this.manager.shutdown(); reconnectionExecutor.shutdownNow(); try { reconnectionExecutor.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { throw new MqttInterruptedException(e); } if (executorService != null) { executorService.shutdownNow(); try { executorService.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { throw new MqttInterruptedException(e); } } } /** * Package visible and only for use by the {@link MqttClientFactory} */ AbstractMqttClient(String brokerUri, MqttClientListener mqttClientListener, AsyncClientListener asyncClientListener, ReconnectionStrategy reconnectionStrategy, Executor executor, ChannelManager manager, ScheduledExecutorService reconnectionExecutor) { this.brokerUri = brokerUri; this.mqttClientListener = mqttClientListener; this.asyncClientListener = asyncClientListener; this.executor = executor; this.reconnectionExecutor = reconnectionExecutor; this.executorService = null; this.messageHandler = new AsyncMessageHandler(); this.reconnectionStrategy = reconnectionStrategy; this.manager = manager; this.dataByMessageId = asyncClientListener == null ? null : new ConcurrentHashMap<Integer, Object>(); this.channel = manager.newClientChannel(brokerUri, messageHandler); } private AbstractMqttClient(String brokerUri, MqttClientListener mqttClientListener, AsyncClientListener asyncClientListener, ReconnectionStrategy reconnectionStrategy, Executor executor, int messageResendIntervalSeconds, int blockingTimeoutSeconds) { this.brokerUri = brokerUri; this.mqttClientListener = mqttClientListener; this.asyncClientListener = asyncClientListener; this.executor = executor; this.executorService = null; this.reconnectionExecutor = Executors.newSingleThreadScheduledExecutor(); this.messageHandler = new AsyncMessageHandler(); this.reconnectionStrategy = reconnectionStrategy != null ? reconnectionStrategy : new NullReconnectStrategy(); this.dataByMessageId = asyncClientListener == null ? null : new ConcurrentHashMap<Integer, Object>(); this.manager = new ChannelManagerImpl(messageResendIntervalSeconds, blockingTimeoutSeconds); this.manager.init(); this.channel = manager.newClientChannel(brokerUri, messageHandler); } private AbstractMqttClient(String brokerUri, MqttClientListener mqttClientListener, AsyncClientListener asyncClientListener, ReconnectionStrategy reconnectionStrategy, ExecutorService executorService, int messageResendIntervalSeconds, int blockingTimeoutSeconds) { this.brokerUri = brokerUri; this.mqttClientListener = mqttClientListener; this.asyncClientListener = asyncClientListener; this.executor = executorService; this.executorService = executorService; this.reconnectionExecutor = Executors.newSingleThreadScheduledExecutor(); this.messageHandler = new AsyncMessageHandler(); this.reconnectionStrategy = reconnectionStrategy != null ? reconnectionStrategy : new NullReconnectStrategy(); this.dataByMessageId = asyncClientListener == null ? null : new ConcurrentHashMap<Integer, Object>(); this.manager = new ChannelManagerImpl(messageResendIntervalSeconds, blockingTimeoutSeconds); this.manager.init(); this.channel = manager.newClientChannel(brokerUri, messageHandler); } private int nextMessageId(Object messageData) { // TODO [jim] - need to deal with what happens when we have an in-flight message that is already using a message ID that we come around to again. Is // this even realistic? int next = messageIdGenerator.incrementAndGet(); if (next > 0xffff) { messageIdGenerator.compareAndSet(next, 0); return nextMessageId(messageData); } if (dataByMessageId != null) { dataByMessageId.put(next, messageData); } return next; } private ConnectReturnCode doConnect(ConnectMessage message) { connectMessage = message; MqttMessage ack = manager.send(channel, message); return ack == null ? null : ((ConnAckMessage) ack).getReturnCode(); } private Subscription[] grantedSubscriptions(Subscription[] requestedSubscriptions, SubAckMessage ack) { boolean match = true; // TODO [jim] - what if the number of granted qoses does not match the number of requested subscriptions? QoS[] grantedQoses = ack.getGrantedQoses(); Subscription[] grantedSubscriptions = new Subscription[requestedSubscriptions.length]; for (int i = 0; i < requestedSubscriptions.length; i++) { grantedSubscriptions[i] = new Subscription(requestedSubscriptions[i].getTopic(), grantedQoses[i]); if (requestedSubscriptions[i].getQos() != grantedQoses[i]) { match = false; } } if (!match) { throw new MqttQosNotGrantedException(grantedSubscriptions); } return grantedSubscriptions; } private void tryReconnect(Throwable cause) { boolean reconnecting = false; if (channel != null) { long reconnectDelay = 0; if (cause != null && !(cause instanceof ConnectException)) { reconnectDelay = reconnectionStrategy.connectionLost(this, cause); reconnecting = reconnectDelay >= 0; } if (reconnecting) { unsentMessages = manager.getUnsentMessages(channel); reconnectionExecutor.schedule(new ClientReconnector(), reconnectDelay, TimeUnit.MILLISECONDS); } else { manager.cancelBlockingCommands(channel); } } mqttClientListener.disconnected(this, cause, reconnecting); } private final class AsyncMessageHandler implements MessageHandler { private final MqttClient client = AbstractMqttClient.this; /** * @see net.sf.xenqtt.message.MessageHandler#connect(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.ConnectMessage) */ @Override public void connect(final MqttChannel channel, final ConnectMessage message) throws Exception { // this should never be received by a client } /** * @see net.sf.xenqtt.message.MessageHandler#connAck(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.ConnAckMessage) */ @Override public void connAck(final MqttChannel channel, final ConnAckMessage message) throws Exception { if (message.getReturnCode() == ConnectReturnCode.ACCEPTED) { executor.execute(new Runnable() { @Override public void run() { reconnectionStrategy.connectionEstablished(); if (unsentMessages != null) { for (MqttMessage message : unsentMessages) { manager.send(channel, message); } } } }); } if (asyncClientListener != null) { executor.execute(new Runnable() { @Override public void run() { try { asyncClientListener.connected(client, message.getReturnCode()); } catch (Exception e) { Log.error(e, "Failed to process message for %s: %s", channel, message); } } }); } } /** * @see net.sf.xenqtt.message.MessageHandler#publish(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubMessage) */ @Override public void publish(final MqttChannel channel, final PubMessage message) throws Exception { executor.execute(new Runnable() { @Override public void run() { try { mqttClientListener.publishReceived(client, new PublishMessage(manager, channel, message)); } catch (Exception e) { Log.error(e, "Failed to process message for %s: %s", channel, message); } } }); } /** * @see net.sf.xenqtt.message.MessageHandler#pubAck(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubAckMessage) */ @Override public void pubAck(final MqttChannel channel, final PubAckMessage message) throws Exception { if (asyncClientListener != null) { executor.execute(new Runnable() { @Override public void run() { try { PublishMessage publishMessage = (PublishMessage) dataByMessageId.get(message.getMessageId()); asyncClientListener.published(client, publishMessage); } catch (Exception e) { Log.error(e, "Failed to process message for %s: %s", channel, message); } } }); } } /** * @see net.sf.xenqtt.message.MessageHandler#pubRec(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubRecMessage) */ @Override public void pubRec(final MqttChannel channel, final PubRecMessage message) throws Exception { // TODO [jim] - qos2 not supported } /** * @see net.sf.xenqtt.message.MessageHandler#pubRel(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubRelMessage) */ @Override public void pubRel(final MqttChannel channel, final PubRelMessage message) throws Exception { // TODO [jim] - qos2 not supported } /** * @see net.sf.xenqtt.message.MessageHandler#pubComp(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubCompMessage) */ @Override public void pubComp(final MqttChannel channel, final PubCompMessage message) throws Exception { // TODO [jim] - qos2 not supported } /** * @see net.sf.xenqtt.message.MessageHandler#subscribe(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.SubscribeMessage) */ @Override public void subscribe(final MqttChannel channel, final SubscribeMessage message) throws Exception { // this should never be received by a client } /** * @see net.sf.xenqtt.message.MessageHandler#subAck(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.SubAckMessage) */ @Override public void subAck(final MqttChannel channel, final SubAckMessage message) throws Exception { if (asyncClientListener != null) { executor.execute(new Runnable() { @Override public void run() { try { Subscription[] requestedSubscriptions = (Subscription[]) dataByMessageId.get(message.getMessageId()); try { Subscription[] grantedSubscriptions = grantedSubscriptions(requestedSubscriptions, message); asyncClientListener.subscribed(client, requestedSubscriptions, grantedSubscriptions, true); } catch (MqttQosNotGrantedException e) { asyncClientListener.subscribed(client, requestedSubscriptions, e.getGrantedSubscriptions(), false); } } catch (Exception e) { Log.error(e, "Failed to process message for %s: %s", channel, message); } } }); } } /** * @see net.sf.xenqtt.message.MessageHandler#unsubscribe(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.UnsubscribeMessage) */ @Override public void unsubscribe(final MqttChannel channel, final UnsubscribeMessage message) throws Exception { // this should never be received by a client } /** * @see net.sf.xenqtt.message.MessageHandler#unsubAck(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.UnsubAckMessage) */ @Override public void unsubAck(final MqttChannel channel, final UnsubAckMessage message) throws Exception { if (asyncClientListener != null) { executor.execute(new Runnable() { @Override public void run() { try { String[] topics = (String[]) dataByMessageId.get(message.getMessageId()); asyncClientListener.unsubscribed(client, topics); } catch (Exception e) { Log.error(e, "Failed to process message for %s: %s", channel, message); } } }); } } /** * @see net.sf.xenqtt.message.MessageHandler#disconnect(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.DisconnectMessage) */ @Override public void disconnect(final MqttChannel channel, final DisconnectMessage message) throws Exception { // this should never be received by a client } /** * @see net.sf.xenqtt.message.MessageHandler#channelOpened(net.sf.xenqtt.message.MqttChannel) */ @Override public void channelOpened(final MqttChannel channel) { if (!firstConnectPending && connectMessage != null) { executor.execute(new Runnable() { @Override public void run() { try { doConnect(connectMessage); } catch (Exception e) { Log.error(e, "Failed to process channelOpened for %s: cause=", channel); } } }); } else { firstConnectPending = false; } } /** * @see net.sf.xenqtt.message.MessageHandler#channelClosed(net.sf.xenqtt.message.MqttChannel, java.lang.Throwable) */ @Override public void channelClosed(final MqttChannel channel, final Throwable cause) { executor.execute(new Runnable() { @Override public void run() { try { tryReconnect(cause); } catch (Exception e) { Log.error(e, "Failed to process channelClosed for %s: cause=", channel, cause); } } }); } } private final class ClientReconnector implements Runnable { /** * @see java.lang.Runnable#run() */ @Override public void run() { try { channel = manager.newClientChannel(brokerUri, messageHandler); } catch (Throwable t) { tryReconnect(t); } } } }
package net.tropicraft.world.worldgen; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public abstract class TCGenBase extends WorldGenerator { World worldObj; Random rand; /**Used in placeBlockLine*/ static final byte otherCoordPairs[] = { 2, 0, 0, 1, 2, 1 }; /**Blocks normally checked in the check methods*/ List<Block> standardAllowedBlocks = Arrays.asList(Blocks.air, Blocks.leaves, Blocks.tallgrass, Blocks.snow_layer); public TCGenBase(World world, Random random) { worldObj = world; rand = random; } /** Checks if the ID is that of a leaf block*/ public boolean isLeafBlock(Block block) { return block == Blocks.leaves; // TODO: Add tropileaves } public abstract boolean generate(int i, int j, int k); /** Allows this class to work as a WorldGenerator object */ @Override public boolean generate(World world, Random rand, int i, int j, int k) { worldObj = world; this.rand = rand; return generate(i, j, k); } /** * Generates a circle * @param x The x coordinate of the center of the circle * @param y The y coordinate of the center of the circle * @param z The z coordinate of the center of the circle * @param outerRadius The radius of the circle's outside edge * @param innerRadius The radius of the circle's inner edge, 0 for a full circle * @param id The ID to generate with * @param meta The metadata to generate with * @param solid Whether it should place the block if another block is already occupying that space */ public boolean genCircle(int x, int y, int z, double outerRadius, double innerRadius, Block block, int meta, boolean solid) { boolean hasGenned = false; for(int i = (int)(-outerRadius - 1) + x; i <= (int)(outerRadius + 1) + x; i++) { for(int k = (int)(-outerRadius - 1) + z; k <= (int)(outerRadius + 1) + z; k++) { double d = (i - x) * (i - x) + (k - z) * (k - z); if(d <= outerRadius * outerRadius && d >= innerRadius * innerRadius) { if(worldObj.isAirBlock(i, y, k) || solid) { if(worldObj.setBlock(i, y, k, block, meta, 3)) { hasGenned = true; } } } } } return hasGenned; } /** * Checks whether any blocks not specified in allowedBlockList exist in that circle * @param x The x coordinate of the center of the circle * @param y The y coordinate of the center of the circle * @param z The z coordinate of the center of the circle * @param outerRadius The radius of the circle's outside edge * @param innerRadius The radius of the circle's inner edge, 0 for a full circle * @param allowedBlockList The blocks to exclude from the check * @return Whether any blocks not specified in allowedBlockList exist in that circle */ public boolean checkCircle(int i, int j, int k, double outerRadius, double innerRadius, List allowedBlockList) { for(int x = (int)(-outerRadius - 2) + i; x < (int)(outerRadius + 2) + i; x++) { for(int z = (int)(-outerRadius - 2) + k; z < (int)(outerRadius + 2) + k; z++) { double d = (i - x) * (i - x) + (k - z) * (k - z); if(d <= outerRadius * outerRadius && d >= innerRadius * innerRadius) { if(!allowedBlockList.contains(worldObj.getBlock(x, j, z))) { System.out.println("t2"); return false; } } } } return true; } /** * Checks whether any blocks not specified in allowedBlockList exist in that line * @param ai One end of the line * @param ai1 The other end of the line * @param allowedBlockList The block to exclude from the check * @return Whether any blocks not specified in allowedBlockList exist in that circle */ public boolean checkBlockLine(int ai[], int ai1[], List allowedBlockList) { int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return false; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); if(!allowedBlockList.contains(worldObj.getBlock(ai3[0], ai3[1], ai3[2]))) { return false; } } return true; } /** * Places a line from coords ai to coords ai1 * @param ai One end of the line * @param ai1 The other end of the line * @param block The block to place * @param meta The block metadata to place * @return The coords that blocks were placed on */ public ArrayList<int[]> placeBlockLine(int ai[], int ai1[], Block block, int meta) { ArrayList<int[]> places = new ArrayList<int[]>(); int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return null; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); worldObj.setBlock(ai3[0], ai3[1], ai3[2], block, meta, 3); places.add(new int[] { ai3[0], ai3[1], ai3[2] }); } return places; } /** * Checks whether any blocks not specified in allowedBlockList exist in that line of circles * @param ai One end of the line * @param ai1 The other end of the line * @param outerRadius The radius of the circle's outside edge * @param innerRadius The radius of the circle's inner edge, 0 for a full circle * @param allowedBlockList The block to exclude from the check * @return */ public boolean checkBlockCircleLine(int ai[], int ai1[], double outerRadius, double innerRadius, List allowedBlockList) { ArrayList<int[]> places = new ArrayList<int[]>(); int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return false; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); if(!checkCircle(ai3[0], ai3[1], ai3[2], outerRadius, innerRadius, allowedBlockList)) { return false; } } return true; } /** * Checks whether any blocks not specified in allowedBlockList exist in that line of circles and if not places the block circle line * @param ai One end of the line * @param ai1 The other end of the line * @param outerRadius The radius of the circle's outside edge * @param innerRadius The radius of the circle's inner edge, 0 for a full circle * @param block The block to generate the block circle line with * @param meta The metadata to generate the block circle line with * @param allowedBlockList The block to exclude from the check * @return The coordinates where a circle was generated */ public ArrayList<int[]> checkAndPlaceBlockCircleLine(int ai[], int ai1[], double outerRadius, double innerRadius, Block block, int meta, List allowedBlockList) { ArrayList<int[]> places = new ArrayList<int[]>(); int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return null; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); if(!checkCircle(ai3[0], ai3[1], ai3[2], outerRadius, innerRadius, allowedBlockList)) { return null; } } k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { System.out.println("watwat"); ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); genCircle(ai3[0], ai3[1], ai3[2], outerRadius, innerRadius, block, meta, true); places.add(new int[] { ai3[0], ai3[1], ai3[2] }); } return places; } /** * Checks if any blocks not specified in allowedBlockList exist within the line and if not places the line * @param ai One end of the line * @param ai1 The other end of the line * @param block The block to generate the block circle line with * @param meta The metadata to generate the block circle line with * @param allowedBlockList The block to exclude from the check * @return The coordinates where a block was placed */ public ArrayList<int[]> checkAndPlaceBlockLine(int ai[], int ai1[], Block block, int meta, List allowedBlockList) { ArrayList<int[]> places = new ArrayList<int[]>(); int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return null; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); if(!allowedBlockList.contains(worldObj.getBlock(ai3[0], ai3[1], ai3[2]))) { return null; } } for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); worldObj.setBlock(ai3[0], ai3[1], ai3[2], block, meta, 3); places.add(new int[] { ai3[0], ai3[1], ai3[2] }); } return places; } /** * Places a block circle line * @param ai One end of the line * @param ai1 The other end of the line * @param outerRadius The radius of the circle's outside edge * @param innerRadius The radius of the circle's inner edge, 0 for a full circle * @param block The block to generate the block circle line with * @param meta The metadata to generate the block circle line with * @param allowedBlockList The block to exclude from the check * @return The coordinates where a circle was generated */ public ArrayList<int[]> placeBlockCircleLine(int ai[], int ai1[], double distance, double distance2, Block block, int meta) { ArrayList<int[]> places = new ArrayList<int[]>(); int ai2[] = { 0, 0, 0 }; byte byte0 = 0; int j = 0; for(; byte0 < 3; byte0++) { ai2[byte0] = ai1[byte0] - ai[byte0]; if(Math.abs(ai2[byte0]) > Math.abs(ai2[j])) { j = byte0; } } if(ai2[j] == 0) { return null; } byte byte1 = otherCoordPairs[j]; byte byte2 = otherCoordPairs[j + 3]; byte byte3; if(ai2[j] > 0) { byte3 = 1; } else { byte3 = -1; } double d = (double)ai2[byte1] / (double)ai2[j]; double d1 = (double)ai2[byte2] / (double)ai2[j]; int ai3[] = { 0, 0, 0 }; int k = 0; for(int l = ai2[j] + byte3; k != l; k += byte3) { ai3[j] = MathHelper.floor_double((double)(ai[j] + k) + 0.5D); ai3[byte1] = MathHelper.floor_double((double)ai[byte1] + (double)k * d + 0.5D); ai3[byte2] = MathHelper.floor_double((double)ai[byte2] + (double)k * d1 + 0.5D); genCircle(ai3[0], ai3[1], ai3[2], distance, distance2, block, meta, true); places.add(new int[] { ai3[0], ai3[1], ai3[2] }); } return places; } /** * Generates a sphere at the specified coordinates * @param x The x coordinate * @param y The y coordinate * @param z The z coordinate * @param outerRadius The radius of the sphere's outside edge * @param block The block to generate the sphere with * @param meta The block metadata to generate the sphere with */ public void genSphere(int x, int y, int z, int outerRadius, Block block, int meta) { for(int i = x - outerRadius; i < x + outerRadius; i++) { for(int j = y - outerRadius; j < y + outerRadius; j++) { for(int k = z - outerRadius; k < z + outerRadius; k++) { if(worldObj.isAirBlock(i, j, k)) { int distance1 = (i - x) * (i - x) + (j - y) * (j - y) + (k - z) * (k - z); if(distance1 <= outerRadius) { worldObj.setBlock(i, j, k, block, meta, 3); } } } } } } /** * Gets the terrain height at the specified coordinates * @param x The x coordinate * @param z The z coordinate * @return The terrain height at the specified coordinates */ public int getTerrainHeightAt(int x, int z) { for(int y = 256; y > 0; y { Block block = worldObj.getBlock(x, y, z); if(block == Blocks.dirt || block == Blocks.grass || block == Blocks.sand || block == Blocks.stone) { return y + 1; } } return 0; } /** * Gets a random angle in radians * @return A random angle in radians */ public double randAngle() { return rand.nextDouble() * 3.1415926535897931D * 2D; } }
package net.whydah.identity.admin; import net.whydah.identity.admin.config.AppConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CookieManager { private static final String USER_TOKEN_REFERENCE_NAME = "whydahusertoken_useradminwebapp"; private static final Logger logger = LoggerFactory.getLogger(CookieManager.class); private static final int DEFAULT_COOKIE_MAX_AGE = 365 * 24 * 60 * 60; private static String cookiedomain = null; private CookieManager() { } static { try { cookiedomain = AppConfig.readProperties().getProperty("cookiedomain"); } catch (IOException e) { logger.warn("AppConfig.readProperties failed. cookiedomain was set to {}", cookiedomain, e); } } public static void createAndSetUserTokenCookie(String userTokenId, Integer tokenRemainingLifetimeSeconds, HttpServletResponse response) { Cookie cookie = new Cookie(USER_TOKEN_REFERENCE_NAME, userTokenId); updateCookie(cookie, userTokenId, tokenRemainingLifetimeSeconds, response); } public static void updateUserTokenCookie(String userTokenId, Integer tokenRemainingLifetimeSeconds, HttpServletRequest request, HttpServletResponse response) { Cookie cookie = getUserTokenCookie(request); updateCookie(cookie, userTokenId, tokenRemainingLifetimeSeconds, response); } private static void updateCookie(Cookie cookie, String cookieValue, Integer tokenRemainingLifetimeSeconds, HttpServletResponse response) { if (cookieValue != null) { cookie.setValue(cookieValue); } //Only name and value are sent back to the server from the browser. The other attributes are only used by the browser to determine of the cookie should be sent or not. //http://en.wikipedia.org/wiki/HTTP_cookie#Setting_a_cookie if (tokenRemainingLifetimeSeconds == null) { tokenRemainingLifetimeSeconds = DEFAULT_COOKIE_MAX_AGE; } cookie.setMaxAge(tokenRemainingLifetimeSeconds); if (cookiedomain != null && !cookiedomain.isEmpty()) { cookie.setDomain(cookiedomain); } cookie.setPath("/"); cookie.setSecure(true); logger.debug("Created/updated cookie with name={}, value/userTokenId={}, domain={}, path={}, maxAge={}, secure={}", cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure()); response.addCookie(cookie); } public static void clearUserTokenCookie(HttpServletRequest request, HttpServletResponse response) { Cookie cookie = getUserTokenCookie(request); if (cookie != null) { cookie.setValue(""); cookie.setMaxAge(0); if (cookiedomain != null && !cookiedomain.isEmpty()) { cookie.setDomain(cookiedomain); } cookie.setPath("/"); cookie.setSecure(true); logger.trace("Cleared cookie with name={}, value/userTokenId={}, domain={}, path={}, maxAge={}, secure={}", cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure()); response.addCookie(cookie); } } public static String getUserTokenIdFromCookie(HttpServletRequest request) { Cookie userTokenCookie = getUserTokenCookie(request); if (userTokenCookie != null && userTokenCookie.getValue().length() > 7) { return userTokenCookie.getValue(); } return (userTokenCookie != null ? userTokenCookie.getValue() : null); } private static Cookie getUserTokenCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (Cookie cookie : cookies) { logger.debug("getUserTokenCookie: cookie with name={}, value={}", cookie.getName(), cookie.getValue()); if (USER_TOKEN_REFERENCE_NAME.equalsIgnoreCase(cookie.getName())) { return cookie; } } return null; } }
package nl.mpi.kinnate.gedcomimport; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JTextArea; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.kindata.DataTypes.RelationType; public class CsvImporter extends EntityImporter implements GenericImporter { public CsvImporter(boolean overwriteExistingLocal) { super(overwriteExistingLocal); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".csv")); } private String cleanCsvString(String valueString) { valueString = valueString.replaceAll("^\"", ""); valueString = valueString.replaceAll("\"$", ""); valueString = valueString.replaceAll("\"\"", ""); return valueString; } private EntityDocument getEntityDocument(JTextArea importTextArea, File destinationDirectory, HashMap<String, EntityDocument> createdDocuments, ArrayList<URI> createdNodes, String idString) throws ImportException { idString = super.cleanFileName(idString); EntityDocument currentEntity = createdDocuments.get(idString); if (currentEntity == null) { // create a new entity file currentEntity = new EntityDocument(destinationDirectory, idString); appendToTaskOutput(importTextArea, "created: " + currentEntity.getFilePath()); createdNodes.add(currentEntity.createDocument(overwriteExisting)); createdDocuments.put(idString, currentEntity); String typeString = "Entity"; if (createdNodeIds.get(typeString) == null) { ArrayList<String> idArray = new ArrayList<String>(); idArray.add(currentEntity.getUniquieIdentifier()); createdNodeIds.put(typeString, idArray); } else { createdNodeIds.get(typeString).add(currentEntity.getUniquieIdentifier()); } } return currentEntity; } @Override public URI[] importFile(JTextArea importTextArea, InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); HashMap<String, EntityDocument> createdDocuments = new HashMap<String, EntityDocument>(); createdNodeIds = new HashMap<String, ArrayList<String>>(); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); File destinationDirectory = super.getDestinationDirectory(); String inputLine; try { int maxImportCount = 10; // "ID","Gender","Name1","Name2","Name3","Name4","Name5","Name6","Date of Birth","Date of Death","sub_group","Parents1-ID","Parents1-Gender","Parents1-Name1","Parents1-Name2","Parents1-Name3","Parents1-Name4","Parents1-Name5","Parents1-Name6","Parents1-Date of Birth","Parents1-Date of Death","Parents1-sub_group","Parents2-ID","Parents2-Gender","Parents2-Name1","Parents2-Name2","Parents2-Name3","Parents2-Name4","Parents2-Name5","Parents2-Name6","Parents2-Date of Birth","Parents2-Date of Death","Parents2-sub_group","Spouses1-ID","Spouses1-Gender","Spouses1-Name1","Spouses1-Name2","Spouses1-Name3","Spouses1-Name4","Spouses1-Name5","Spouses1-Name6","Spouses1-Date of Birth","Spouses1-Date of Death","Spouses1-sub_group","Spouses2-ID","Spouses2-Gender","Spouses2-Name1","Spouses2-Name2","Spouses2-Name3","Spouses2-Name4","Spouses2-Name5","Spouses2-Name6","Spouses2-Date of Birth","Spouses2-Date of Death","Spouses2-sub_group","Spouses3-ID","Spouses3-Gender","Spouses3-Name1","Spouses3-Name2","Spouses3-Name3","Spouses3-Name4","Spouses3-Name5","Spouses3-Name6","Spouses3-Date of Birth","Spouses3-Date of Death","Spouses3-sub_group","Spouses4-ID","Spouses4-Gender","Spouses4-Name1","Spouses4-Name2","Spouses4-Name3","Spouses4-Name4","Spouses4-Name5","Spouses4-Name6","Spouses4-Date of Birth","Spouses4-Date of Death","Spouses4-sub_group","Spouses5-ID","Spouses5-Gender","Spouses5-Name1","Spouses5-Name2","Spouses5-Name3","Spouses5-Name4","Spouses5-Name5","Spouses5-Name6","Spouses5-Date of Birth","Spouses5-Date of Death","Spouses5-sub_group","Spouses6-ID","Spouses6-Gender","Spouses6-Name1","Spouses6-Name2","Spouses6-Name3","Spouses6-Name4","Spouses6-Name5","Spouses6-Name6","Spouses6-Date of Birth","Spouses6-Date of Death","Spouses6-sub_group","Children1-ID","Children1-Gender","Children1-Name1","Children1-Name2","Children1-Name3","Children1-Name4","Children1-Name5","Children1-Name6","Children1-Date of Birth","Children1-Date of Death","Children1-sub_group","Children2-ID","Children2-Gender","Children2-Name1","Children2-Name2","Children2-Name3","Children2-Name4","Children2-Name5","Children2-Name6","Children2-Date of Birth","Children2-Date of Death","Children2-sub_group","Children3-ID","Children3-Gender","Children3-Name1","Children3-Name2","Children3-Name3","Children3-Name4","Children3-Name5","Children3-Name6","Children3-Date of Birth","Children3-Date of Death","Children3-sub_group","Children4-ID","Children4-Gender","Children4-Name1","Children4-Name2","Children4-Name3","Children4-Name4","Children4-Name5","Children4-Name6","Children4-Date of Birth","Children4-Date of Death","Children4-sub_group","Children5-ID","Children5-Gender","Children5-Name1","Children5-Name2","Children5-Name3","Children5-Name4","Children5-Name5","Children5-Name6","Children5-Date of Birth","Children5-Date of Death","Children5-sub_group","Children6-ID","Children6-Gender","Children6-Name1","Children6-Name2","Children6-Name3","Children6-Name4","Children6-Name5","Children6-Name6","Children6-Date of Birth","Children6-Date of Death","Children6-sub_group","Children7-ID","Children7-Gender","Children7-Name1","Children7-Name2","Children7-Name3","Children7-Name4","Children7-Name5","Children7-Name6","Children7-Date of Birth","Children7-Date of Death","Children7-sub_group","Children8-ID","Children8-Gender","Children8-Name1","Children8-Name2","Children8-Name3","Children8-Name4","Children8-Name5","Children8-Name6","Children8-Date of Birth","Children8-Date of Death","Children8-sub_group","Children9-ID","Children9-Gender","Children9-Name1","Children9-Name2","Children9-Name3","Children9-Name4","Children9-Name5","Children9-Name6","Children9-Date of Birth","Children9-Date of Death","Children9-sub_group","Children10-ID","Children10-Gender","Children10-Name1","Children10-Name2","Children10-Name3","Children10-Name4","Children10-Name5","Children10-Name6","Children10-Date of Birth","Children10-Date of Death","Children10-sub_group","Children11-ID","Children11-Gender","Children11-Name1","Children11-Name2","Children11-Name3","Children11-Name4","Children11-Name5","Children11-Name6","Children11-Date of Birth","Children11-Date of Death","Children11-sub_group","Children12-ID","Children12-Gender","Children12-Name1","Children12-Name2","Children12-Name3","Children12-Name4","Children12-Name5","Children12-Name6","Children12-Date of Birth","Children12-Date of Death","Children12-sub_group","Children13-ID","Children13-Gender","Children13-Name1","Children13-Name2","Children13-Name3","Children13-Name4","Children13-Name5","Children13-Name6","Children13-Date of Birth","Children13-Date of Death","Children13-sub_group","Children14-ID","Children14-Gender","Children14-Name1","Children14-Name2","Children14-Name3","Children14-Name4","Children14-Name5","Children14-Name6","Children14-Date of Birth","Children14-Date of Death","Children14-sub_group","Children15-ID","Children15-Gender","Children15-Name1","Children15-Name2","Children15-Name3","Children15-Name4","Children15-Name5","Children15-Name6","Children15-Date of Birth","Children15-Date of Death","Children15-sub_group","Children16-ID","Children16-Gender","Children16-Name1","Children16-Name2","Children16-Name3","Children16-Name4","Children16-Name5","Children16-Name6","Children16-Date of Birth","Children16-Date of Death","Children16-sub_group","Children17-ID","Children17-Gender","Children17-Name1","Children17-Name2","Children17-Name3","Children17-Name4","Children17-Name5","Children17-Name6","Children17-Date of Birth","Children17-Date of Death","Children17-sub_group","Children18-ID","Children18-Gender","Children18-Name1","Children18-Name2","Children18-Name3","Children18-Name4","Children18-Name5","Children18-Name6","Children18-Date of Birth","Children18-Date of Death","Children18-sub_group","Children19-ID","Children19-Gender","Children19-Name1","Children19-Name2","Children19-Name3","Children19-Name4","Children19-Name5","Children19-Name6","Children19-Date of Birth","Children19-Date of Death","Children19-sub_group","Children20-ID","Children20-Gender","Children20-Name1","Children20-Name2","Children20-Name3","Children20-Name4","Children20-Name5","Children20-Name6","Children20-Date of Birth","Children20-Date of Death","Children20-sub_group" String headingLine = bufferedReader.readLine(); if (headingLine != null) { ArrayList<String> allHeadings = new ArrayList<String>(); for (String headingString : headingLine.split(",")) { String cleanHeading = cleanCsvString(headingString); allHeadings.add(cleanHeading); // appendToTaskOutput(importTextArea, "Heading: " + cleanHeading); } try { while ((inputLine = bufferedReader.readLine()) != null) { EntityDocument currentEntity = null; int valueCount = 0; for (String entityLineString : inputLine.split(",")) { String cleanValue = cleanCsvString(entityLineString); String headingString = allHeadings.get(valueCount); if (currentEntity == null) { currentEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); } else if (cleanValue.length() > 0) { if (headingString.startsWith("Spouses")) { if (headingString.matches("Spouses[\\d]*-ID")) { EntityDocument relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(RelationType.union, relatedEntity.getUniquieIdentifier(), relatedEntity.getFileName()); } else { appendToTaskOutput(importTextArea, "Ignoring: " + allHeadings.get(valueCount) + " : " + cleanValue); } } else if (headingString.startsWith("Parents")) { if (headingString.matches("Parents[\\d]*-ID")) { EntityDocument relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(RelationType.ancestor, relatedEntity.getUniquieIdentifier(), relatedEntity.getFileName()); } else { appendToTaskOutput(importTextArea, "Ignoring: " + allHeadings.get(valueCount) + " : " + cleanValue); } } else if (headingString.startsWith("Children")) { if (headingString.matches("Children[\\d]*-ID")) { EntityDocument relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(RelationType.descendant, relatedEntity.getUniquieIdentifier(), relatedEntity.getFileName()); } else { appendToTaskOutput(importTextArea, "Ignoring: " + allHeadings.get(valueCount) + " : " + cleanValue); } } else if (headingString.equals("Gender")) { String genderString = cleanValue; if ("0".equals(cleanValue)) { genderString = "female"; } else if ("1".equals(cleanValue)) { genderString = "male"; } else { throw new ImportException("Unknown gender type: " + genderString); } currentEntity.insertValue(headingString, genderString); appendToTaskOutput(importTextArea, "Setting value: " + allHeadings.get(valueCount) + " : " + cleanValue); } else { currentEntity.insertValue(headingString, cleanValue); appendToTaskOutput(importTextArea, "Setting value: " + allHeadings.get(valueCount) + " : " + cleanValue); } } valueCount++; } // if (maxImportCount-- < 0) { // appendToTaskOutput(importTextArea, "Aborting import due to max testing limit"); // break; // appendToTaskOutput(importTextArea, inputLine); // boolean skipFileEntity = false; // if (skipFileEntity) { // skipFileEntity = false; // while ((inputLine = bufferedReader.readLine()) != null) { // if (inputLine.startsWith("0")) { // break; } } catch (ImportException exception) { appendToTaskOutput(importTextArea, exception.getMessage()); } } appendToTaskOutput(importTextArea, "Saving all documents"); for (EntityDocument currentDocument : createdDocuments.values()) { currentDocument.saveDocument(); // appendToTaskOutput(importTextArea, "saved: " + currentDocument.getFilePath()); } } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error: " + exception.getMessage()); } // catch (ParserConfigurationException parserConfigurationException) { // new ArbilBugCatcher().logError(parserConfigurationException); // appendToTaskOutput(importTextArea, "Error: " + parserConfigurationException.getMessage()); // } catch (DOMException dOMException) { // new ArbilBugCatcher().logError(dOMException); // appendToTaskOutput(importTextArea, "Error: " + dOMException.getMessage()); // } catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); // }catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); return createdNodes.toArray(new URI[]{}); } }
package org.apache.commons.jexl.parser; import org.apache.commons.jexl.JexlContext; import org.apache.commons.jexl.util.Coercion; /** * Addition : either integer addition or string concatenation * * @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a> * @version $Id: ASTAddNode.java,v 1.5 2003/12/18 16:10:26 geirm Exp $ */ public class ASTAddNode extends SimpleNode { public ASTAddNode(int id) { super(id); } public ASTAddNode(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object value(JexlContext context) throws Exception { Object left = ((SimpleNode) jjtGetChild(0)).value(context); Object right = ((SimpleNode) jjtGetChild(1)).value(context); /* * the spec says 'and' */ if (left == null && right == null) return new Long(0); /* * if anything is float, double or string with ( "." | "E" | "e") * coerce all to doubles and do it */ if (left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double || ( left instanceof String && ( ((String) left).indexOf(".") != -1 || ((String) left).indexOf("e") != -1 || ((String) left).indexOf("E") != -1 ) ) || ( right instanceof String && ( ((String) right).indexOf(".") != -1 || ((String) right).indexOf("e") != -1 || ((String) right).indexOf("E") != -1) ) ) { /* * in the event that either is null and not both, then just make the * null a 0 */ Double l = left == null ? new Double(0) : Coercion.coerceDouble(left); Double r = right == null? new Double(0) : Coercion.coerceDouble(right); return new Double(l.doubleValue() + r.doubleValue()); } /* * attempt to use Longs */ try { Long l = left == null ? new Long(0) : Coercion.coerceLong(left); Long r = right == null ? new Long(0) : Coercion.coerceLong(right); return new Long(l.longValue() + r.longValue()); } catch( java.lang.NumberFormatException nfe ) { /* * Well, use strings! */ return left.toString().concat(right.toString()); } } }
package no.difi.sdp.client2.internal; import no.difi.begrep.sdp.schema_v10.SDPAvsender; import no.difi.begrep.sdp.schema_v10.SDPDigitalPost; import no.difi.begrep.sdp.schema_v10.SDPDigitalPostInfo; import no.difi.begrep.sdp.schema_v10.SDPDokument; import no.difi.begrep.sdp.schema_v10.SDPDokumentData; import no.difi.begrep.sdp.schema_v10.SDPEpostVarsel; import no.difi.begrep.sdp.schema_v10.SDPEpostVarselTekst; import no.difi.begrep.sdp.schema_v10.SDPFysiskPostInfo; import no.difi.begrep.sdp.schema_v10.SDPFysiskPostRetur; import no.difi.begrep.sdp.schema_v10.SDPFysiskPostadresse; import no.difi.begrep.sdp.schema_v10.SDPIso6523Authority; import no.difi.begrep.sdp.schema_v10.SDPManifest; import no.difi.begrep.sdp.schema_v10.SDPMottaker; import no.difi.begrep.sdp.schema_v10.SDPNorskPostadresse; import no.difi.begrep.sdp.schema_v10.SDPOrganisasjon; import no.difi.begrep.sdp.schema_v10.SDPPerson; import no.difi.begrep.sdp.schema_v10.SDPPrintinstruksjon; import no.difi.begrep.sdp.schema_v10.SDPPrintinstruksjoner; import no.difi.begrep.sdp.schema_v10.SDPRepetisjoner; import no.difi.begrep.sdp.schema_v10.SDPSikkerhetsnivaa; import no.difi.begrep.sdp.schema_v10.SDPSmsVarsel; import no.difi.begrep.sdp.schema_v10.SDPSmsVarselTekst; import no.difi.begrep.sdp.schema_v10.SDPTittel; import no.difi.begrep.sdp.schema_v10.SDPUtenlandskPostadresse; import no.difi.begrep.sdp.schema_v10.SDPVarsler; import no.difi.sdp.client2.domain.Avsender; import no.difi.sdp.client2.domain.Dokument; import no.difi.sdp.client2.domain.Forsendelse; import no.difi.sdp.client2.domain.digital_post.DigitalPost; import no.difi.sdp.client2.domain.digital_post.EpostVarsel; import no.difi.sdp.client2.domain.digital_post.SmsVarsel; import no.difi.sdp.client2.domain.fysisk_post.FysiskPost; import no.difi.sdp.client2.domain.fysisk_post.KonvoluttAdresse; import no.difi.sdp.client2.domain.fysisk_post.KonvoluttAdresse.Type; import no.difi.sdp.client2.domain.fysisk_post.Printinstruksjon; import org.w3.xmldsig.Reference; import org.w3.xmldsig.Signature; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static java.util.stream.Collectors.toList; import static no.difi.sdp.client2.domain.fysisk_post.KonvoluttAdresse.Type.NORSK; import static no.difi.sdp.client2.domain.fysisk_post.KonvoluttAdresse.Type.UTENLANDSK; import static no.difi.sdp.client2.internal.SdpTimeConstants.UTC; @SuppressWarnings("ConstantConditions") public class SDPBuilder { private static final String ORGNR_IDENTIFIER = "9908:"; public SDPManifest createManifest(final Forsendelse forsendelse) { SDPMottaker sdpMottaker = sdpMottaker(forsendelse.getDigitalPost()); SDPAvsender sdpAvsender = sdpAvsender(forsendelse.getAvsender()); String spraakkode = forsendelse.getSpraakkode(); SDPDokument sdpHovedDokument = sdpDokument(forsendelse.getDokumentpakke().getHoveddokument(), spraakkode); List<SDPDokument> sdpVedlegg = new ArrayList<>(); for (Dokument dokument : forsendelse.getDokumentpakke().getVedlegg()) { sdpVedlegg.add(sdpDokument(dokument, spraakkode)); } return new SDPManifest(sdpMottaker, sdpAvsender, sdpHovedDokument, sdpVedlegg, null); } public SDPDigitalPost buildDigitalPost(final Forsendelse forsendelse) { SDPAvsender sdpAvsender = sdpAvsender(forsendelse.getAvsender()); SDPMottaker sdpMottaker = sdpMottaker(forsendelse.getDigitalPost()); SDPDigitalPostInfo sdpDigitalPostInfo = sdpDigitalPostinfo(forsendelse); SDPFysiskPostInfo fysiskPostInfo = sdpFysiskPostInfo(forsendelse.getFysiskPost()); Signature signature = null; Reference dokumentpakkefingeravtrykk = null; return new SDPDigitalPost(signature, sdpAvsender, sdpMottaker, sdpDigitalPostInfo, fysiskPostInfo, dokumentpakkefingeravtrykk); } private SDPDokument sdpDokument(final Dokument dokument, final String spraakkode) { final String dokumentTittel = dokument.getTittel(); SDPTittel sdpTittel = dokumentTittel != null ? new SDPTittel(dokumentTittel, spraakkode) : null; SDPDokumentData sdpDokumentData = dokument.getMetadataDocument().map(d -> new SDPDokumentData(d.getFileName(), d.getMimeType())).orElse(null); return new SDPDokument(sdpTittel, sdpDokumentData, dokument.getFilnavn(), dokument.getMimeType()); } private SDPMottaker sdpMottaker(final DigitalPost digitalPost) { if (digitalPost == null) { return null; } SDPPerson sdpPerson = new SDPPerson(digitalPost.getMottaker().getPersonidentifikator(), digitalPost.getMottaker().getPostkasseadresse()); return new SDPMottaker(sdpPerson); } private SDPAvsender sdpAvsender(final Avsender avsender) { String fakturaReferanse = avsender.getFakturaReferanse(); String identifikator = avsender.getAvsenderIdentifikator(); SDPOrganisasjon organisasjon = sdpOrganisasjon(avsender); return new SDPAvsender(organisasjon, identifikator, fakturaReferanse); } private SDPOrganisasjon sdpOrganisasjon(final Avsender avsender) { return new SDPOrganisasjon(ORGNR_IDENTIFIER + avsender.getOrganisasjonsnummer(), SDPIso6523Authority.ISO_6523_ACTORID_UPIS); } private SDPDigitalPostInfo sdpDigitalPostinfo(final Forsendelse forsendelse) { DigitalPost digitalPost = forsendelse.getDigitalPost(); if (digitalPost == null) { return null; } ZonedDateTime virkningstidspunkt = null; if (digitalPost.getVirkningsdato() != null) { virkningstidspunkt = ZonedDateTime.ofInstant(digitalPost.getVirkningsdato().toInstant(), UTC); } boolean aapningskvittering = digitalPost.isAapningskvittering(); SDPSikkerhetsnivaa sikkerhetsnivaa = digitalPost.getSikkerhetsnivaa().getXmlValue(); SDPTittel tittel = new SDPTittel(digitalPost.getIkkeSensitivTittel(), forsendelse.getSpraakkode()); SDPVarsler varsler = sdpVarsler(forsendelse); return new SDPDigitalPostInfo(virkningstidspunkt, null, aapningskvittering, sikkerhetsnivaa, tittel, varsler); } private SDPFysiskPostInfo sdpFysiskPostInfo(FysiskPost fysiskPost) { if (fysiskPost == null) { return null; } return new SDPFysiskPostInfo() .withMottaker(sdpPostadresse(fysiskPost.getAdresse())) .withPosttype(fysiskPost.getPosttype().sdpType) .withUtskriftsfarge(fysiskPost.getUtskriftsfarge().sdpUtskriftsfarge) .withRetur(new SDPFysiskPostRetur(fysiskPost.getReturhaandtering().sdpReturhaandtering, sdpPostadresse(fysiskPost.getReturadresse()))) .withPrintinstruksjoner(sdpPrintinstruksjoner(fysiskPost.getPrintinstruksjoner())); } private SDPPrintinstruksjoner sdpPrintinstruksjoner(List<Printinstruksjon> printinstruksjoner) { if (printinstruksjoner == null) { return null; } return new SDPPrintinstruksjoner( printinstruksjoner.stream() .map(p -> new SDPPrintinstruksjon(p.getNavn(), p.getVerdi())) .collect(toList()) ); } private SDPFysiskPostadresse sdpPostadresse(KonvoluttAdresse adresse) { SDPFysiskPostadresse sdpAdresse = new SDPFysiskPostadresse().withNavn(adresse.getNavn()); if (adresse.er(UTENLANDSK)) { UpTo4ElementsOfList<String> adresselinjer = UpTo4ElementsOfList.extract(adresse.getAdresselinjer()); sdpAdresse.setUtenlandskAdresse(new SDPUtenlandskPostadresse(adresselinjer._1, adresselinjer._2, adresselinjer._3, adresselinjer._4, adresse.getLandkode(), adresse.getLand())); } else if (adresse.er(NORSK)) { UpTo4ElementsOfList<String> adresselinjer = UpTo4ElementsOfList.extract(adresse.getAdresselinjer()); sdpAdresse.setNorskAdresse(new SDPNorskPostadresse(adresselinjer._1, adresselinjer._2, adresselinjer._3, adresse.getPostnummer(), adresse.getPoststed())); } else { throw new IllegalArgumentException("Ukjent " + KonvoluttAdresse.class.getSimpleName() + "." + Type.class.getSimpleName() + ": " + adresse.getType()); } return sdpAdresse; } private SDPVarsler sdpVarsler(final Forsendelse forsendelse) { String spraakkode = forsendelse.getSpraakkode(); SDPEpostVarsel epostVarsel = sdpEpostVarsel(forsendelse.getDigitalPost().getEpostVarsel(), spraakkode); SDPSmsVarsel smsVarsel = sdpSmsVarsel(forsendelse.getDigitalPost().getSmsVarsel(), spraakkode); return new SDPVarsler(epostVarsel, smsVarsel); } private SDPSmsVarsel sdpSmsVarsel(final SmsVarsel smsVarsel, final String spraakkode) { if (smsVarsel != null) { SDPSmsVarselTekst smsVarselTekst = new SDPSmsVarselTekst(smsVarsel.getVarslingsTekst(), spraakkode); return new SDPSmsVarsel(smsVarsel.getMobilnummer(), smsVarselTekst, new SDPRepetisjoner(smsVarsel.getDagerEtter())); } return null; } private SDPEpostVarsel sdpEpostVarsel(final EpostVarsel epostVarsel, final String spraakkode) { if (epostVarsel != null) { SDPEpostVarselTekst epostVarselTekst = new SDPEpostVarselTekst(epostVarsel.getVarslingsTekst(), spraakkode); return new SDPEpostVarsel(epostVarsel.getEpostadresse(), epostVarselTekst, new SDPRepetisjoner(epostVarsel.getDagerEtter())); } return null; } static class UpTo4ElementsOfList<T> { final T _1; final T _2; final T _3; final T _4; static <T> UpTo4ElementsOfList<T> extract(Iterable<T> iterable) { return new UpTo4ElementsOfList<>(iterable); } private UpTo4ElementsOfList(Iterable<T> iterable) { Iterator<T> iterator = iterable.iterator(); _1 = iterator.hasNext() ? iterator.next() : null; _2 = iterator.hasNext() ? iterator.next() : null; _3 = iterator.hasNext() ? iterator.next() : null; _4 = iterator.hasNext() ? iterator.next() : null; } } }
package org.apache.commons.vfs.tasks; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import org.apache.commons.vfs.FileContent; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileType; import org.apache.tools.ant.BuildException; public class ShowFileTask extends VfsTask { private String url; private boolean showContent; private boolean recursive; private static final String INDENT = " "; /** * The URL of the file to display. */ public void setFile( final String url ) { this.url = url; } /** * Shows the content. Assumes the content is text, encoded using the * platform's default encoding. */ public void setShowContent( final boolean showContent ) { this.showContent = showContent; } /** * Recursively shows the decendents of the file. */ public void setRecursive( final boolean recursive ) { this.recursive = recursive; } /** * Executes the task. */ public void execute() throws BuildException { try { final FileObject file = resolveFile( url ); log( "Details of " + file.getName().getURI() ); showFile( file, INDENT ); } catch ( final Exception e ) { throw new BuildException( e ); } } /** * Logs the details of a file. */ private void showFile( final FileObject file, final String prefix ) throws Exception { // Write details StringBuffer msg = new StringBuffer( prefix ); msg.append( file.getName().getBaseName() ); if ( file.exists() ) { msg.append( " (" ); msg.append( file.getType().getName() ); msg.append( ")" ); } else { msg.append( " (unknown)" ); } log( msg.toString() ); if ( file.exists() ) { final String newPrefix = prefix + INDENT; if ( file.getType() == FileType.FILE ) { final FileContent content = file.getContent(); log( newPrefix + "Content-Length: " + content.getSize() ); log( newPrefix + "Last-Modified" + new Date( content.getLastModifiedTime() ) ); if ( showContent ) { log( newPrefix + "Content:" ); logContent( file, newPrefix ); } } else { final FileObject[] children = file.getChildren(); for ( int i = 0; i < children.length; i++ ) { FileObject child = children[ i ]; if ( recursive ) { showFile( child, newPrefix ); } else { log( newPrefix + child.getName().getBaseName() ); } } } } } /** * Writes the content of the file to Ant log. */ private void logContent( final FileObject file, final String prefix ) throws Exception { final InputStream instr = file.getContent().getInputStream(); try { final BufferedReader reader = new BufferedReader( new InputStreamReader( instr ) ); while ( true ) { final String line = reader.readLine(); if ( line == null ) { break; } log( prefix + line ); } } finally { instr.close(); } } }
package org.jsimpledb.kv.fdb; import com.foundationdb.Database; import com.foundationdb.FDB; import com.foundationdb.FDBException; import com.foundationdb.NetworkOptions; import java.util.concurrent.Executor; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.jsimpledb.kv.KVDatabase; import org.jsimpledb.kv.KVDatabaseException; /** * FoundationDB {@link KVDatabase} implementation. * * <p> * Allows specifying a {@linkplain #setKeyPrefix key prefix} for all keys, allowing multiple independent databases. * </p> */ public class FoundationKVDatabase implements KVDatabase { /** * The API version used by this class. */ public static final int API_VERSION = 200; private final FDB fdb = FDB.selectAPIVersion(API_VERSION); private final NetworkOptions options = this.fdb.options(); private String clusterFilePath; private byte[] databaseName = new byte[] { (byte)'D', (byte)'B' }; private byte[] keyPrefix; private Executor executor; private Database database; /** * Constructor. * * @throws FDBException if {@link #API_VERSION} is not supported */ public FoundationKVDatabase() { } /** * Get the {@link NetworkOptions} associated with this instance. * Options must be configured prior to {@link #start}. */ public NetworkOptions getNetworkOptions() { return this.options; } /** * Configure the {@link Executor} used for the FoundationDB networking event loop. */ public void setExecutor(Executor executor) { this.executor = executor; } /** * Configure the cluster file path. Default is null, which results in the default fdb.cluster file being used. */ public void setClusterFilePath(String clusterFilePath) { this.clusterFilePath = clusterFilePath; } /** * Configure the database name. Currently the default value ({@code "DB".getBytes()}) is the only valid value. */ public void setDatabaseName(byte[] databaseName) { this.databaseName = databaseName; } /** * Get the key prefix for all keys. * * @return key prefix, or null if there is none configured */ public byte[] getKeyPrefix() { return this.keyPrefix.clone(); } public void setKeyPrefix(byte[] keyPrefix) { if (this.database != null) throw new IllegalStateException("already started"); if (keyPrefix != null && keyPrefix.length > 0 && keyPrefix[0] == (byte)0xff) throw new IllegalArgumentException("prefix starts with 0xff"); this.keyPrefix = keyPrefix != null && keyPrefix.length > 0 ? keyPrefix.clone() : null; } public Database getDatabase() { if (this.database == null) throw new IllegalStateException("not started"); return this.database; } @PostConstruct public synchronized void start() { if (this.database != null) throw new IllegalStateException("already started"); this.database = this.fdb.open(this.clusterFilePath, this.databaseName); if (this.executor != null) this.fdb.startNetwork(this.executor); else this.fdb.startNetwork(); } /** * Stop this instance. Invokes {@link FDB#stopNetwork}. Does nothing if not {@linkplain #start started}. * * @throws FDBException if an error occurs */ @PreDestroy public synchronized void stop() { if (this.database == null) return; this.fdb.stopNetwork(); } @Override public FoundationKVTransaction createTransaction() { if (this.database == null) throw new IllegalStateException("not started"); try { return new FoundationKVTransaction(this, this.keyPrefix); } catch (FDBException e) { throw new KVDatabaseException(this, e); } } }