answer
stringlengths
17
10.2M
package edu.washington.escience.myriad.operator; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import org.junit.Test; import com.google.common.collect.ImmutableList; import edu.washington.escience.myriad.DbException; import edu.washington.escience.myriad.Schema; import edu.washington.escience.myriad.TupleBatch; import edu.washington.escience.myriad.Type; /** * To test BinaryFileScan, and it is based on the code from FileScanTest * * @author leelee * */ public class BinaryFileScanTest { @Test /** * Test default BinaryFileScan that reads data bytes in big endian format. */ public void testSimple() throws DbException { Schema schema = new Schema(ImmutableList.of(Type.INT_TYPE, Type.INT_TYPE)); String filename = "testdata" + File.separatorChar + "binaryfilescan" + File.separatorChar + "testSimple"; generateSimpleBinaryFile(filename, 2); BinaryFileScan bfs = new BinaryFileScan(schema, filename); assertEquals(2, getRowCount(bfs)); } @Test /** * Test default BinaryFileScan that reads data bytes in big endian format with the bin file * that has the astronomy data schema. */ public void testWithAstronomySchema() throws DbException { Type[] typeAr = { Type.LONG_TYPE, // iOrder Type.FLOAT_TYPE, // mass Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, // rho Type.FLOAT_TYPE, // temp Type.FLOAT_TYPE, // hsmooth Type.FLOAT_TYPE, // metals Type.FLOAT_TYPE, // tform Type.FLOAT_TYPE, // eps Type.FLOAT_TYPE // phi }; Schema schema = new Schema(Arrays.asList(typeAr)); String filename = "testdata" + File.separatorChar + "binaryfilescan" + File.separatorChar + "testWithAstronomySchema"; generateBinaryFile(filename, typeAr, 8); BinaryFileScan bfs = new BinaryFileScan(schema, filename); assertEquals(8, getRowCount(bfs)); } @Test /** * Test BinaryFileScan with the real cosmo data bin file */ public void testNumRowsFromCosmo24Star() throws DbException { Type[] typeAr = { Type.LONG_TYPE, // iOrder Type.FLOAT_TYPE, // mass Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, // metals Type.FLOAT_TYPE, // tform Type.FLOAT_TYPE, // eps Type.FLOAT_TYPE, // phi }; Schema schema = new Schema(Arrays.asList(typeAr)); String filename = "testdata" + File.separatorChar + "binaryfilescan" + File.separatorChar + "cosmo50cmb.256g2bwK.00024.star.bin"; BinaryFileScan bfs = new BinaryFileScan(schema, filename, true); assertEquals(1291, getRowCount(bfs)); } /** * Generates a binary file with the given file name, type array and the number of row. * * @param filename The filename to create. * @param typeAr The type array. * @param row The number of row. */ private void generateBinaryFile(String filename, Type[] typeAr, int row) { try { RandomAccessFile raf = new RandomAccessFile(filename, "rw"); for (int i = 0; i < row; i++) { for (Type element : typeAr) { switch (element) { case BOOLEAN_TYPE: raf.writeBoolean(true); break; case DOUBLE_TYPE: raf.writeDouble(i); break; case FLOAT_TYPE: raf.writeFloat(i); break; case INT_TYPE: raf.writeInt(i); break; case LONG_TYPE: raf.writeLong(i); break; default: throw new UnsupportedOperationException("can only write fix length field to bin file"); } } } raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Generates a simple binary file with the given file name with the given number of row. The generated binary file * will contains two int in each row. * * @param filename * @param row */ private void generateSimpleBinaryFile(String filename, int row) { try { RandomAccessFile raf = new RandomAccessFile(filename, "rw"); for (int i = 0; i < row; i++) { raf.writeInt(i); raf.writeInt(i); } raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Helper function used to run tests. * * @param fileScan the FileScan object to be tested. * @return the number of rows in the file. * @throws DbException if the file does not match the given Schema. */ private static int getRowCount(BinaryFileScan fileScan) throws DbException { fileScan.open(null); int count = 0; TupleBatch tb = null; while (!fileScan.eos()) { tb = fileScan.nextReady(); if (tb != null) { count += tb.numTuples(); } } return count; } }
package net.coobird.thumbnailator; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Arrays; import java.util.Iterator; import java.util.List; import javax.imageio.ImageIO; import net.coobird.thumbnailator.builders.BufferedImageBuilder; import net.coobird.thumbnailator.name.ConsecutivelyNumberedFilenames; import net.coobird.thumbnailator.name.Rename; import org.junit.Test; public class ThumbnailsBuilderInputOutputTest { /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> */ @Test public void of_BufferedImage_toFile_File_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); File destFile = new File("test-resources/Thumbnailator/tmp.png"); destFile.deleteOnExit(); // when Thumbnails.of(img) .size(100, 100) .toFile(destFile); // then assertEquals("png", getFormatName(new FileInputStream(destFile))); BufferedImage thumbnail = ImageIO.read(destFile); assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> */ @Test public void of_BufferedImage_toFile_String_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); String destFilePath = "test-resources/Thumbnailator/tmp.png"; // when Thumbnails.of(img) .size(100, 100) .toFile(destFilePath); // then File destFile = new File(destFilePath); destFile.deleteOnExit(); assertEquals("png", getFormatName(new FileInputStream(destFile))); BufferedImage thumbnail = ImageIO.read(destFile); assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_toFiles_Iterable_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Thumbnails.of(img) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); assertEquals("png", getFormatName(new FileInputStream(outFile))); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_asFiles_Iterable_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<File> thumbnails = Thumbnails.of(img) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals("png", getFormatName(new FileInputStream(thumbnails.get(0)))); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void of_BufferedImage_asBufferedImage_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when BufferedImage thumbnail = Thumbnails.of(img) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test public void of_BufferedImage_asBufferedImages_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.of(img) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test(expected=IllegalStateException.class) public void of_BufferedImage_toOutputStream_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // when Thumbnails.of(img) .size(50, 50) .toOutputStream(os); fail(); } catch (IllegalStateException e) { // then assertEquals("Output format not specified.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_BufferedImage_toOutputStreams_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // when Thumbnails.of(img) .size(50, 50) .toOutputStreams(Arrays.asList(os)); fail(); } catch (IllegalStateException e) { // then assertEquals("Output format not specified.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_iterableBufferedImages_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(img) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>The thumbnail is written to the specified file</li> * </ol> */ @Test public void of_BufferedImage_toFile_File_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); File destFile = new File("test-resources/Thumbnailator/tmp.png"); destFile.deleteOnExit(); // when Thumbnails.of(img) .size(100, 100) .outputFormat("png") .toFile(destFile); // then BufferedImage thumbnail = ImageIO.read(destFile); assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>The thumbnail is written to the specified file</li> * </ol> */ @Test public void of_BufferedImage_toFile_String_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); String destFilePath = "test-resources/Thumbnailator/tmp.png"; // when Thumbnails.of(img) .size(100, 100) .outputFormat("png") .toFile(destFilePath); // then File destFile = new File(destFilePath); destFile.deleteOnExit(); BufferedImage thumbnail = ImageIO.read(destFile); assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_toFiles_Iterable_OutputFormatSpecified() throws IOException { // given BufferedImage img1 = new BufferedImageBuilder(200, 200).build(); // when Thumbnails.of(img1) .size(50, 50) .outputFormat("png") .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_asFiles_Iterable_OutputFormatSpecified() throws IOException { // given BufferedImage img1 = new BufferedImageBuilder(200, 200).build(); // when List<File> thumbnails = Thumbnails.of(img1) .size(50, 50) .outputFormat("png") .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void of_BufferedImage_asBufferedImage_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when BufferedImage thumbnail = Thumbnails.of(img) .size(100, 100) .outputFormat("png") .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test public void of_BufferedImage_asBufferedImages_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.of(img) .size(100, 100) .outputFormat("png") .asBufferedImages(); // then assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(1, thumbnails.size()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toOutputStream()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_toOutputStream_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(img) .size(50, 50) .outputFormat("png") .toOutputStream(os); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toOutputStreams(Iterable<OutputStream>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_toOutputStreams_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(img) .size(50, 50) .outputFormat("png") .toOutputStreams(Arrays.asList(os)); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage)</li> * <li>outputFormat("png")</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImage_iterableBufferedImages_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(img) .size(50, 50) .outputFormat("png") .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toFile_File_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); File destFile = new File("test-resources/Thumbnailator/tmp.png"); destFile.deleteOnExit(); try { // when Thumbnails.of(img, img) .size(100, 100) .toFile(destFile); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> */ @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toFile_String_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); String destFilePath = "test-resources/Thumbnailator/tmp.png"; try { // when Thumbnails.of(img, img) .size(100, 100) .toFile(destFilePath); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_toFiles_Iterable_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Thumbnails.of(img, img) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); assertEquals("png", getFormatName(new FileInputStream(outFile))); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully. Image format is determined * by the extension of the file.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_asFiles_Iterable_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<File> thumbnails = Thumbnails.of(img, img) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals("png", getFormatName(new FileInputStream(thumbnails.get(0)))); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals("png", getFormatName(new FileInputStream(thumbnails.get(1)))); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); thumbnails.get(1).deleteOnExit(); } @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_asBufferedImage_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); try { // when Thumbnails.of(img, img) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void of_BufferedImages_asBufferedImages_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.of(img, img) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toOutputStream_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // when Thumbnails.of(img, img) .size(50, 50) .toOutputStream(os); fail(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to a single OutputStream.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_BufferedImages_toOutputStreams_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // when Thumbnails.of(img, img) .size(50, 50) .toOutputStreams(Arrays.asList(os)); fail(); } catch (IllegalStateException e) { // then assertEquals("Output format not specified.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_iterableBufferedImages_NoOutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(img, img) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail1 = iter.next(); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = iter.next(); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>The thumbnail is written to the specified file</li> * </ol> */ @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toFile_File_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); File destFile = new File("test-resources/Thumbnailator/tmp.png"); destFile.deleteOnExit(); try { // when Thumbnails.of(img, img) .size(100, 100) .outputFormat("png") .toFile(destFile); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>The thumbnail is written to the specified file</li> * </ol> */ @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toFile_String_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); String destFilePath = "test-resources/Thumbnailator/tmp.png"; try { // when Thumbnails.of(img, img) .size(100, 100) .outputFormat("png") .toFile(destFilePath); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } finally { // clean up new File(destFilePath).deleteOnExit(); } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_toFiles_Iterable_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Thumbnails.of(img, img) .size(50, 50) .outputFormat("png") .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); outFile1.deleteOnExit(); File outFile2 = new File("test-resources/Thumbnailator/temp-1.png"); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_asFiles_Iterable_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<File> thumbnails = Thumbnails.of(img, img) .size(50, 50) .outputFormat("png") .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); thumbnails.get(1).deleteOnExit(); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_asBufferedImage_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); try { // when Thumbnails.of(img, img) .size(100, 100) .outputFormat("png") .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void of_BufferedImages_asBufferedImages_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.of(img, img) .size(100, 100) .outputFormat("png") .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toOutputStream()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test(expected=IllegalArgumentException.class) public void of_BufferedImages_toOutputStream_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // when Thumbnails.of(img, img) .size(50, 50) .outputFormat("png") .toOutputStream(os); fail(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to a single OutputStream.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>toOutputStreams(Iterable<OutputStream>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_toOutputStreams_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); ByteArrayOutputStream os2 = new ByteArrayOutputStream(); // when Thumbnails.of(img, img) .size(50, 50) .outputFormat("png") .toOutputStreams(Arrays.asList(os1, os2)); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os1.toByteArray())); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); thumbnail = ImageIO.read(new ByteArrayInputStream(os2.toByteArray())); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(BufferedImage, BufferedImage)</li> * <li>outputFormat("png")</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_BufferedImages_iterableBufferedImages_OutputFormatSpecified() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(img, img) .size(50, 50) .outputFormat("png") .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages([BufferedImage])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromImages_Single_asBufferedImage() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when BufferedImage thumbnail = Thumbnails.fromImages(Arrays.asList(img)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromImages_Multiple_asBufferedImage() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); try { // when Thumbnails.fromImages(Arrays.asList(img, img)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromImages_Single_asBufferedImages() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.fromImages(Arrays.asList(img)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromImages_Multiple_asBufferedImages() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.fromImages(Arrays.asList(img, img)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages(Iterable[BufferedImage])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromImagesIterable_Single_asBufferedImage() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when BufferedImage thumbnail = Thumbnails.fromImages((Iterable<BufferedImage>)Arrays.asList(img)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromImagesIterable_Multiple_asBufferedImage() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); try { // when Thumbnails.fromImages((Iterable<BufferedImage>)Arrays.asList(img, img)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromImagesIterable_Single_asBufferedImages() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.fromImages((Iterable<BufferedImage>)Arrays.asList(img)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromImagesIterable_Multiple_asBufferedImages() throws IOException { // given BufferedImage img = new BufferedImageBuilder(200, 200).build(); // when List<BufferedImage> thumbnails = Thumbnails.fromImages((Iterable<BufferedImage>)Arrays.asList(img, img)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void of_File_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(f) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_File_toFiles_Rename() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.of(f1) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_File_asFiles_Rename() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.of(f1) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_File_toFiles_Iterable() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); // when Thumbnails.of(f1) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_File_asFiles_Iterable() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); // when List<File> thumbnails = Thumbnails.of(f1) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); outFile1.deleteOnExit(); assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_File_asBufferedImage() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.of(f1) .size(50, 50) .asBufferedImage(); // then assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_File_asBufferedImages() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.of(f1) .size(50, 50) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); BufferedImage thumbnail = thumbnails.get(0); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>toOutputStream()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_File_toOutputStream() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(f1) .size(50, 50) .toOutputStream(os); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_File_toOutputStreams() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(f1) .size(50, 50) .toOutputStreams(Arrays.asList(os)); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_File_iterableBufferedImages() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(f1) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } @Test(expected=IllegalArgumentException.class) public void of_Files_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); try { // when Thumbnails.of(f, f) .size(50, 50) .toFile(outFile); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_Files_toFiles_Rename() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when Thumbnails.of(f1, f2) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_Files_asFiles_Rename() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when List<File> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_Files_toFiles_Iterable() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when Thumbnails.of(f1, f2) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); File outFile2 = new File("test-resources/Thumbnailator/temp-1.png.JPEG"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_Files_asFiles_Iterable() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when List<File> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); thumbnails.get(1).deleteOnExit(); } @Test(expected=IllegalArgumentException.class) public void of_Files_asBufferedImage() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.of(f, f) .size(50, 50) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and returned as BufferedImages in a List</li> * </ol> * @throws IOException */ @Test public void of_Files_asBufferedImages() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when List<BufferedImage> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); BufferedImage thumbnail1 = thumbnails.get(0); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = thumbnails.get(1); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); } @Test(expected=IllegalArgumentException.class) public void of_Files_toOutputStream() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); OutputStream os = mock(OutputStream.class); try { // when Thumbnails.of(f, f) .size(50, 50) .toOutputStream(os); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to a single OutputStream.", e.getMessage()); verifyZeroInteractions(os); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing will be successful.</li> * </ol> * @throws IOException */ @Test public void of_Files_toOutputStreams() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); ByteArrayOutputStream os2 = new ByteArrayOutputStream(); // when Thumbnails.of(f, f) .size(50, 50) .toOutputStreams(Arrays.asList(os1, os2)); //then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os1.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os1.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); thumbnail = ImageIO.read(new ByteArrayInputStream(os2.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os2.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(File, File)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and an Iterable which can iterate over the * two BufferedImages is returned.</li> * </ol> * @throws IOException */ @Test public void of_Files_iterableBufferedImages() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail1 = iter.next(); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = iter.next(); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles([File])</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void fromFiles_Single_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFiles(Arrays.asList(f)) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromFiles_Multiple_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFiles(Arrays.asList(f, f)) .size(50, 50) .toFile(outFile); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles([File])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFiles_Single_toFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.fromFiles(Arrays.asList(f1)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles([File, File])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFiles_Multiple_toFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when Thumbnails.fromFiles(Arrays.asList(f1, f2)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles([File])</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFiles_Single_asFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.fromFiles(Arrays.asList(f1)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles([File, File])</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFiles_Multiple_asFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when List<File> thumbnails = Thumbnails.fromFiles(Arrays.asList(f1, f2)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles(Iterable[File])</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void fromFilesIterable_Single_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f)) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromFilesIterable_Multiple_toFile() throws IOException { // given File f = new File("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f, f)) .size(50, 50) .toFile(outFile); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles(Iterable[File])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilesIterable_Single_toFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f1)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles(Iterable[File, File])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilesIterable_Multiple_toFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f1, f2)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles(Iterable[File])</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilesIterable_Single_asFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f1)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFiles(Iterable[File, File])</li> * <li>asFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilesIterable_Multiple_asFiles() throws IOException { // given File f1 = new File("test-resources/Thumbnailator/grid.png"); File f2 = new File("test-resources/Thumbnailator/grid.jpg"); // when List<File> thumbnails = Thumbnails.fromFiles((Iterable<File>)Arrays.asList(f1, f2)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(String)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void of_String_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(f) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalArgumentException.class) public void of_Strings_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(f, f) .size(50, 50) .toFile(outFile); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(String)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_String_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.of(f1) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(String, String)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_Strings_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when Thumbnails.of(f1, f2) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(String)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_String_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.of(f1) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(String, String)</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void of_Strings_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when List<File> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames([String])</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void fromFilenames_Single_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFilenames(Arrays.asList(f)) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromFilenames_Multiple_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFilenames(Arrays.asList(f, f)) .size(50, 50) .toFile(outFile); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames([String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenames_Single_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.fromFilenames(Arrays.asList(f1)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames([String, String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenames_Multiple_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when Thumbnails.fromFilenames(Arrays.asList(f1, f2)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames([String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenames_Single_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.fromFilenames(Arrays.asList(f1)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames([String, String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenames_Multiple_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when List<File> thumbnails = Thumbnails.fromFilenames(Arrays.asList(f1, f2)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames(Iterable[String])</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void fromFilenamesIterable_Single_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f)) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromFilenamesIterable_Multiple_toFile() throws IOException { // given String f = "test-resources/Thumbnailator/grid.png"; File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f, f)) .size(50, 50) .toFile(outFile); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames(Iterable[String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenamesIterable_Single_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f1)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames(Iterable[String, String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenamesIterable_Multiple_toFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f1, f2)) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames(Iterable[String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenamesIterable_Single_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); // when List<File> thumbnails = Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f1)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromFilenames(Iterable[String, String])</li> * <li>toFiles(Rename)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Rename object.</li> * </ol> * @throws IOException */ @Test public void fromFilenamesIterable_Multiple_asFiles() throws IOException { // given String f1 = "test-resources/Thumbnailator/grid.png"; String f2 = "test-resources/Thumbnailator/grid.jpg"; // when List<File> thumbnails = Thumbnails.fromFilenames((Iterable<String>)Arrays.asList(f1, f2)) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); // then File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); File outFile2 = new File("test-resources/Thumbnailator/thumbnail.grid.jpg"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(outFile1); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void of_URL_toFile() throws IOException { // given URL f = new File("test-resources/Thumbnailator/grid.png").toURL(); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(f) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalStateException.class) public void of_URL_toFiles_Rename() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); try { // when Thumbnails.of(f1) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_URL_asFiles_Rename() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); try { // when Thumbnails.of(f1) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_URL_toFiles_Iterable() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); // when Thumbnails.of(f1) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_URL_asFiles_Iterable() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<File> thumbnails = Thumbnails.of(f1) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); outFile1.deleteOnExit(); assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_URL_asBufferedImage() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); // when BufferedImage thumbnail = Thumbnails.of(f1) .size(50, 50) .asBufferedImage(); // then assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_URL_asBufferedImages() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.of(f1) .size(50, 50) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); BufferedImage thumbnail = thumbnails.get(0); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>toOutputStream()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_URL_toOutputStream() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(f1) .size(50, 50) .toOutputStream(os); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_URL_toOutputStreams() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(f1) .size(50, 50) .toOutputStreams(Arrays.asList(os)); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_URL_iterableBufferedImages() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(f1) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } @Test(expected=IllegalArgumentException.class) public void of_URLs_toFile() throws IOException { // given URL f = new File("test-resources/Thumbnailator/grid.png").toURL(); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); try { // when Thumbnails.of(f, f) .size(50, 50) .toFile(outFile); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_URLs_toFiles_Rename() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); try { // when Thumbnails.of(f1, f2) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_URLs_asFiles_Rename() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); try { // when Thumbnails.of(f1, f2) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL, URL)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_URLs_toFiles_Iterable() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); // when Thumbnails.of(f1, f2) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); File outFile2 = new File("test-resources/Thumbnailator/temp-1.png.JPEG"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL, URL)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_URLs_asFiles_Iterable() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); // when List<File> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); thumbnails.get(1).deleteOnExit(); } @Test(expected=IllegalArgumentException.class) public void of_URLs_asBufferedImage() throws IOException { // given URL f = new File("test-resources/Thumbnailator/grid.png").toURL(); try { // when Thumbnails.of(f, f) .size(50, 50) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL, URL)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and returned as BufferedImages in a List</li> * </ol> * @throws IOException */ @Test public void of_URLs_asBufferedImages() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); BufferedImage thumbnail1 = thumbnails.get(0); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = thumbnails.get(1); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); } @Test(expected=IllegalArgumentException.class) public void of_URLs_toOutputStream() throws IOException { // given URL f = new File("test-resources/Thumbnailator/grid.png").toURL(); OutputStream os = mock(OutputStream.class); try { // when Thumbnails.of(f, f) .size(50, 50) .toOutputStream(os); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to a single OutputStream.", e.getMessage()); verifyZeroInteractions(os); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL, URL)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing will be successful.</li> * </ol> * @throws IOException */ @Test public void of_URLs_toOutputStreams() throws IOException { // given URL f = new File("test-resources/Thumbnailator/grid.png").toURL(); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); ByteArrayOutputStream os2 = new ByteArrayOutputStream(); // when Thumbnails.of(f, f) .size(50, 50) .toOutputStreams(Arrays.asList(os1, os2)); //then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os1.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os1.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); thumbnail = ImageIO.read(new ByteArrayInputStream(os2.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os2.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(URL, URL)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and an Iterable which can iterate over the * two BufferedImages is returned.</li> * </ol> * @throws IOException */ @Test public void of_URLs_iterableBufferedImages() throws IOException { // given URL f1 = new File("test-resources/Thumbnailator/grid.png").toURL(); URL f2 = new File("test-resources/Thumbnailator/grid.jpg").toURL(); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(f1, f2) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail1 = iter.next(); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = iter.next(); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages([URL])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromURLs_Single_asBufferedImage() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when BufferedImage thumbnail = Thumbnails.fromURLs(Arrays.asList(url)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromURLs_Multiple_asBufferedImage() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); try { // when Thumbnails.fromURLs(Arrays.asList(url, url)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromURLs_Single_asBufferedImages() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.fromURLs(Arrays.asList(url)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromURLs_Multiple_asBufferedImages() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.fromURLs(Arrays.asList(url, url)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages(Iterable[URL])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromURLsIterable_Single_asBufferedImage() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when BufferedImage thumbnail = Thumbnails.fromURLs((Iterable<URL>)Arrays.asList(url)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromURLsIterable_Multiple_asBufferedImage() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); try { // when Thumbnails.fromURLs((Iterable<URL>)Arrays.asList(url, url)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromURLsIterable_Single_asBufferedImages() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.fromURLs((Iterable<URL>)Arrays.asList(url)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromURLsIterable_Multiple_asBufferedImages() throws IOException { // given URL url = new File("test-resources/Thumbnailator/grid.png").toURL(); // when List<BufferedImage> thumbnails = Thumbnails.fromURLs((Iterable<URL>)Arrays.asList(url, url)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_toFile() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(is) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } @Test(expected=IllegalStateException.class) public void of_InputStream_toFiles_Rename() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); try { // when Thumbnails.of(is) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_InputStream_asFiles_Rename() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); File outFile1 = new File("test-resources/Thumbnailator/thumbnail.grid.png"); outFile1.deleteOnExit(); try { // when Thumbnails.of(is) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_toFiles_Iterable() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when Thumbnails.of(is) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile = new File("test-resources/Thumbnailator/temp-0.png"); outFile.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is generated and written to a file whose name is generated * from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_asFiles_Iterable() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<File> thumbnails = Thumbnails.of(is) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); outFile1.deleteOnExit(); assertEquals(1, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.of(is) .size(50, 50) .asBufferedImage(); // then assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_asBufferedImages() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.of(is) .size(50, 50) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); BufferedImage thumbnail = thumbnails.get(0); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>toOutputStream()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_toOutputStream() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(is) .size(50, 50) .toOutputStream(os); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_toOutputStreams() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os = new ByteArrayOutputStream(); // when Thumbnails.of(is) .size(50, 50) .toOutputStreams(Arrays.asList(os)); // then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing completes successfully.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_iterableBufferedImages() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(is) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail = iter.next(); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertFalse(iter.hasNext()); } @Test(expected=IllegalArgumentException.class) public void of_InputStreams_toFile() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); try { // when Thumbnails.of(is, is) .size(50, 50) .toFile(outFile); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to one file.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_InputStreams_toFiles_Rename() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); try { // when Thumbnails.of(is1, is2) .size(50, 50) .toFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } @Test(expected=IllegalStateException.class) public void of_InputStreams_asFiles_Rename() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); try { // when Thumbnails.of(is1, is2) .size(50, 50) .asFiles(Rename.PREFIX_DOT_THUMBNAIL); } catch (IllegalStateException e) { // then assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream, InputStream)</li> * <li>toFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_InputStreams_toFiles_Iterable() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); // when Thumbnails.of(is1, is2) .size(50, 50) .toFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then File outFile1 = new File("test-resources/Thumbnailator/temp-0.png"); File outFile2 = new File("test-resources/Thumbnailator/temp-1.png.JPEG"); outFile1.deleteOnExit(); outFile2.deleteOnExit(); BufferedImage fromFileImage1 = ImageIO.read(outFile1); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(outFile2); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream, InputStream)</li> * <li>asFiles(Iterable<File>)</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and written to a file whose name is * generated from the Iterable<File> object.</li> * </ol> * @throws IOException */ @Test public void of_InputStreams_asFiles_Iterable() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); // when List<File> thumbnails = Thumbnails.of(is1, is2) .size(50, 50) .asFiles(new ConsecutivelyNumberedFilenames(new File("test-resources/Thumbnailator"), "temp-%d.png")); // then assertEquals(2, thumbnails.size()); BufferedImage fromFileImage1 = ImageIO.read(thumbnails.get(0)); assertEquals(50, fromFileImage1.getWidth()); assertEquals(50, fromFileImage1.getHeight()); BufferedImage fromFileImage2 = ImageIO.read(thumbnails.get(1)); assertEquals(50, fromFileImage2.getWidth()); assertEquals(50, fromFileImage2.getHeight()); // clean up thumbnails.get(0).deleteOnExit(); thumbnails.get(1).deleteOnExit(); } @Test(expected=IllegalArgumentException.class) public void of_InputStreams_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.of(is, is) .size(50, 50) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream, InputStream)</li> * <li>asBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and returned as BufferedImages in a List</li> * </ol> * @throws IOException */ @Test public void of_InputStreams_asBufferedImages() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); // when List<BufferedImage> thumbnails = Thumbnails.of(is1, is2) .size(50, 50) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); BufferedImage thumbnail1 = thumbnails.get(0); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = thumbnails.get(1); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); } @Test(expected=IllegalArgumentException.class) public void of_InputStreams_toOutputStream() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); OutputStream os = mock(OutputStream.class); try { // when Thumbnails.of(is, is) .size(50, 50) .toOutputStream(os); } catch (IllegalArgumentException e) { // then assertEquals("Cannot output multiple thumbnails to a single OutputStream.", e.getMessage()); verifyZeroInteractions(os); throw e; } } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream, InputStream)</li> * <li>toOutputStreams()</li> * </ol> * and the expected outcome is, * <ol> * <li>Processing will be successful.</li> * </ol> * @throws IOException */ @Test public void of_InputStreams_toOutputStreams() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.png"); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); ByteArrayOutputStream os2 = new ByteArrayOutputStream(); // when Thumbnails.of(is1, is2) .size(50, 50) .toOutputStreams(Arrays.asList(os1, os2)); //then BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream(os1.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os1.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); thumbnail = ImageIO.read(new ByteArrayInputStream(os2.toByteArray())); assertEquals("png", getFormatName(new ByteArrayInputStream(os2.toByteArray()))); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream, InputStream)</li> * <li>iterableBufferedImages()</li> * </ol> * and the expected outcome is, * <ol> * <li>Two images are generated and an Iterable which can iterate over the * two BufferedImages is returned.</li> * </ol> * @throws IOException */ @Test public void of_InputStreams_iterableBufferedImages() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.jpg"); // when Iterable<BufferedImage> thumbnails = Thumbnails.of(is1, is2) .size(50, 50) .iterableBufferedImages(); // then Iterator<BufferedImage> iter = thumbnails.iterator(); BufferedImage thumbnail1 = iter.next(); assertEquals(50, thumbnail1.getWidth()); assertEquals(50, thumbnail1.getHeight()); BufferedImage thumbnail2 = iter.next(); assertEquals(50, thumbnail2.getWidth()); assertEquals(50, thumbnail2.getHeight()); assertFalse(iter.hasNext()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages([InputStream])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromInputStreams_Single_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.fromInputStreams(Arrays.asList(is)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromInputStreams_Multiple_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.fromInputStreams(Arrays.asList(is, is)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromInputStreams_Single_asBufferedImages() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams(Arrays.asList(is)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromInputStreams_Multiple_asBufferedImages() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams(Arrays.asList(is1, is2)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages([FileInputStream])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromInputStreams_Single_FileInputStream_asBufferedImage() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.fromInputStreams(Arrays.asList(is)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromInputStreams_Multiple_FileInputStream_asBufferedImage() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.fromInputStreams(Arrays.asList(is, is)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromInputStreams_Single_FileInputStream_asBufferedImages() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams(Arrays.asList(is)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromInputStream_Multiple_FileInputStream_asBufferedImages() throws IOException { // given FileInputStream fis1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); FileInputStream fis2 = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams(Arrays.asList(fis1, fis2)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.of(InputStream)</li> * <li>InputStream is a FileInputStream</li> * <li>toFile(File)</li> * </ol> * and the expected outcome is, * <ol> * <li>An image is written to the specified file.</li> * </ol> * @throws IOException */ @Test public void of_InputStream_FileInputStream_toFile() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); File outFile = new File("test-resources/Thumbnailator/grid.tmp.png"); outFile.deleteOnExit(); // when Thumbnails.of(is) .size(50, 50) .toFile(outFile); // then BufferedImage fromFileImage = ImageIO.read(outFile); assertEquals(50, fromFileImage.getWidth()); assertEquals(50, fromFileImage.getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages(Iterable[InputStream])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromInputStreamsIterable_Single_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.fromInputStreams((Iterable<InputStream>)Arrays.asList(is)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromInputStreamsIterable_Multiple_asBufferedImage() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.fromInputStreams((Iterable<InputStream>)Arrays.asList(is, is)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromInputStreamsIterable_Single_asBufferedImages() throws IOException { // given InputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams((Iterable<InputStream>)Arrays.asList(is)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromInputStreamsIterable_Multiple_asBufferedImages() throws IOException { // given InputStream is1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); InputStream is2 = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams((Iterable<InputStream>)Arrays.asList(is1, is2)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Test for the {@link Thumbnails.Builder} class where, * <ol> * <li>Thumbnails.fromImages(Iterable[FileInputStream])</li> * <li>asBufferedImage()</li> * </ol> * and the expected outcome is, * <ol> * <li>A BufferedImage is returned</li> * </ol> */ @Test public void fromInputStreamsIterable_Single_FileInputStream_asBufferedImage() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when BufferedImage thumbnail = Thumbnails.fromInputStreams((Iterable<FileInputStream>)Arrays.asList(is)) .size(100, 100) .asBufferedImage(); // then assertEquals(100, thumbnail.getWidth()); assertEquals(100, thumbnail.getHeight()); } @Test(expected=IllegalArgumentException.class) public void fromInputStreamsIterable_Multiple_FileInputStream_asBufferedImage() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); try { // when Thumbnails.fromInputStreams((Iterable<FileInputStream>)Arrays.asList(is, is)) .size(100, 100) .asBufferedImage(); } catch (IllegalArgumentException e) { // then assertEquals("Cannot create one thumbnail from multiple original images.", e.getMessage()); throw e; } } @Test public void fromInputStreamsIterable_Single_FileInputStream_asBufferedImages() throws IOException { // given FileInputStream is = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams((Iterable<FileInputStream>)Arrays.asList(is)) .size(100, 100) .asBufferedImages(); // then assertEquals(1, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); } @Test public void fromInputStreamIterable_Multiple_FileInputStream_asBufferedImages() throws IOException { // given FileInputStream fis1 = new FileInputStream("test-resources/Thumbnailator/grid.png"); FileInputStream fis2 = new FileInputStream("test-resources/Thumbnailator/grid.png"); // when List<BufferedImage> thumbnails = Thumbnails.fromInputStreams((Iterable<FileInputStream>)Arrays.asList(fis1, fis2)) .size(100, 100) .asBufferedImages(); // then assertEquals(2, thumbnails.size()); assertEquals(100, thumbnails.get(0).getWidth()); assertEquals(100, thumbnails.get(0).getHeight()); assertEquals(100, thumbnails.get(1).getWidth()); assertEquals(100, thumbnails.get(1).getHeight()); } /** * Returns the format of an image which is read through the {@link InputStream}. * * @param is The {@link InputStream} to an image. * @return File format of the image. * @throws IOException */ private static String getFormatName(InputStream is) throws IOException { return ImageIO.getImageReaders( ImageIO.createImageInputStream(is) ).next().getFormatName(); } }
package de.boxxit.stasis.spring; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import de.boxxit.stasis.AuthenticationMissmatchException; import de.boxxit.stasis.AuthenticationResult; import de.boxxit.stasis.SerializableException; import de.boxxit.stasis.StasisConstants; import de.boxxit.stasis.StasisUtils; import de.boxxit.stasis.security.LoginService; import de.boxxit.stasis.security.LoginStatus; import de.boxxit.stasis.serializer.ArraysListSerializer; import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool.ObjectPool; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.StackObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * User: Christian Fruth */ public class StasisController implements Controller { private static final String LOGIN_FUNCTION = "login"; private static final Logger LOGGER = LoggerFactory.getLogger(StasisController.class); private static class InOut { public Input input; public Output output; public Kryo kryo; } private Map<String, Object> services; private List<Registration> registeredSerializers; private LoginService loginService; private ObjectPool<InOut> ioPool; private Class<? extends Serializer> defaultSerializer = null; private int serverVersion; // Ich bin noch ein Kommentar public StasisController() { final PoolableObjectFactory<InOut> poolableObjectFactory = new BasePoolableObjectFactory<InOut>() { @Override public InOut makeObject() throws Exception { InOut io = new InOut(); io.input = new Input(4096); io.output = new Output(4096); io.kryo = new Kryo(); io.kryo.addDefaultSerializer(Arrays.asList().getClass(), ArraysListSerializer.class); if (defaultSerializer != null) { io.kryo.setDefaultSerializer(defaultSerializer); } if (registeredSerializers != null) { for (Registration registration : registeredSerializers) { Serializer<?> serializer = registration.getSerializer(); if ((serializer == null) && (registration.getSerializerClass() != null)) { serializer = registration.getSerializerClass().newInstance(); } if (registration.getId() == null) { assert (serializer != null); io.kryo.register(registration.getType(), serializer); } else if (serializer == null) { io.kryo.register(registration.getType(), registration.getId()); } else { io.kryo.register(registration.getType(), serializer, registration.getId()); } } } return io; } @Override public void passivateObject(InOut io) throws Exception { io.input.setInputStream(null); io.output.setOutputStream(null); super.passivateObject(io); } }; ioPool = new StackObjectPool<InOut>(poolableObjectFactory); } public void setServerVersion(int serverVersion) { this.serverVersion = serverVersion; } public void setLoginService(LoginService loginService) { this.loginService = loginService; } public void setServices(Map<String, Object> services) { this.services = services; } public void setRegisteredSerializers(List<Registration> registeredSerializers) { this.registeredSerializers = registeredSerializers; } public void setDefaultSerializer(Class<? extends Serializer> defaultSerializer) { this.defaultSerializer = defaultSerializer; } @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { InOut io = ioPool.borrowObject(); try { boolean gzipRequested = StasisUtils.isUsingGzipEncoding(request.getHeaders(StasisUtils.ACCEPT_ENCODING_KEY)); boolean gzipUsed = StasisUtils.isUsingGzipEncoding(request.getHeaders(StasisUtils.CONTENT_ENCODING_KEY)); InputStream inputStream = request.getInputStream(); OutputStream outputStream = response.getOutputStream(); if (gzipUsed) { inputStream = new GZIPInputStream(inputStream); } if (gzipRequested) { response.setHeader(StasisUtils.CONTENT_ENCODING_KEY, StasisUtils.GZIP_ENCODING); outputStream = new GZIPOutputStream(outputStream); } response.setContentType(StasisConstants.CONTENT_TYPE); io.input.setInputStream(inputStream); io.output.setOutputStream(outputStream); handleIO(io.kryo, io.input, io.output); //io.output.close(); outputStream.close(); } finally { ioPool.returnObject(io); } return null; } protected void handleIO(Kryo kryo, Input input, Output output) throws AuthenticationMissmatchException { // Funktionsnamen lesen long startTimeMillis = System.currentTimeMillis(); String functionName; boolean assumeAuthenticated; Object[] args; Object[] result = null; try { functionName = kryo.readObject(input, String.class); assumeAuthenticated = kryo.readObject(input, boolean.class); args = kryo.readObject(input, Object[].class); } catch (Exception ex) { LOGGER.error("Call failed because function name or arguments can't be read"); throw ex; } try { if (LOGIN_FUNCTION.equals(functionName)) { result = handleLogin(args); } else { result = handleServiceFunction(functionName, assumeAuthenticated, args); } } catch (AuthenticationMissmatchException ex) { if (LOGGER.isErrorEnabled()) { long stopTimeMillis = System.currentTimeMillis(); LOGGER.error(String.format("Call failed (name = %s, arguments = %s, duration = %dms)", functionName, formatArray(args), stopTimeMillis - startTimeMillis)); } result = new Object[] { ex }; } catch (SerializableException ex) { if (LOGGER.isErrorEnabled()) { long stopTimeMillis = System.currentTimeMillis(); LOGGER.error(String.format("Call failed (name = %s, arguments = %s, duration = %dms)", functionName, formatArray(args), stopTimeMillis - startTimeMillis), ex); } result = new Object[] { ex }; } catch (Throwable ex) { if (LOGGER.isErrorEnabled()) { long stopTimeMillis = System.currentTimeMillis(); LOGGER.error(String.format("Call failed (name = %s, arguments = %s, duration = %dms)", functionName, formatArray(args), stopTimeMillis - startTimeMillis), ex); } result = new Object[] { new SerializableException(ex) }; } try { kryo.writeObject(output, result); output.flush(); if (LOGGER.isDebugEnabled()) { long stopTimeMillis = System.currentTimeMillis(); LOGGER.debug(String.format("Call succeeded (name = %s, arguments = %s, result = %s, duration = %dms)", functionName, formatArray(args), formatArray(result), stopTimeMillis - startTimeMillis)); } } catch (Exception ex) { if (LOGGER.isErrorEnabled()) { long stopTimeMillis = System.currentTimeMillis(); LOGGER.error(String.format("Call failed because result can't be written back to client (name = %s, arguments = %s, result = %s, duration = %dms)", functionName, formatArray(args), formatArray(result), stopTimeMillis - startTimeMillis), ex); } } } private Object[] handleLogin(Object[] args) { AuthenticationResult authenticationResult; if (args == null) { throw new IllegalArgumentException("No arguments supplied for login"); } if (args.length != 3) { throw new IllegalArgumentException("3 arguments for login expected"); } String userName = (String)args[0]; String password = (String)args[1]; int clientVersion = (Integer)args[2]; if (clientVersion != serverVersion) { authenticationResult = AuthenticationResult.VersionMissmatch; } else { LoginStatus loginStatus = loginService.login(userName, password); authenticationResult = loginStatus.isAuthenticated() ? AuthenticationResult.Authenticated : AuthenticationResult.Unauthenticated; } return new Object[] { authenticationResult }; } private Object[] handleServiceFunction(String functionName, boolean assumeAuthenticated, Object[] args) throws Throwable { Method foundMethod = null; LoginStatus loginStatus = loginService.getStatus(); if (loginStatus.isAuthenticated() != assumeAuthenticated) { throw new AuthenticationMissmatchException(loginStatus.isAuthenticated()); } int index = functionName.indexOf('.'); String serviceName = functionName.substring(0, index); Object service = services.get(serviceName); if (service == null) { throw new SerializableException("serviceMissing", "Can't find matching service"); } Class<?> serviceClass = service.getClass(); String serviceMethod = functionName.substring(index + 1); for (Method method : serviceClass.getMethods()) { if (method.getName().equals(serviceMethod)) { foundMethod = method; break; } } if (foundMethod == null) { throw new SerializableException("serviceFunctionMissing", "Can't find matching service function"); } try { Class<?> returnType = foundMethod.getReturnType(); if (void.class.equals(returnType)) { foundMethod.invoke(service, args); return new Object[0]; } Object returnValue = foundMethod.invoke(service, args); return new Object[] { returnValue }; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } private CharSequence formatArray(Object[] array) { if (array == null) { return "null"; } StringBuilder str = new StringBuilder("{ "); int length = Math.min(10, array.length); for (int i = 0; i < length; ++i) { if (i != 0) { str.append(", "); } str.append(array[i]); } if (length < array.length) { str.append(", and "); str.append(array.length - length); str.append("more"); } str.append(" }"); return str; } }
package org.epics.graphene; import java.util.GregorianCalendar; import java.util.List; import org.epics.util.array.ListDouble; import org.epics.util.time.TimeDuration; import org.epics.util.time.TimeInterval; import org.epics.util.time.Timestamp; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.epics.graphene.TimeScales.TimePeriod; import static java.util.GregorianCalendar.*; /** * * @author carcassi */ public class TimeScalesTest { @Test public void nextUp1() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 1)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 2))); } @Test public void nextUp2() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 2)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 5))); } @Test public void nextUp3() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 5)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 10))); } @Test public void nextUp4() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 10)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 15))); } @Test public void nextUp5() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 15)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 30))); } @Test public void roundSeconds1() { TimeScales.TimePeriod period = TimeScales.roundSeconds(30.0); assertThat(period, equalTo(new TimePeriod(SECOND, 30.0))); } @Test public void roundSeconds2() { TimeScales.TimePeriod period = TimeScales.roundSeconds(61.0); assertThat(period, equalTo(new TimePeriod(MINUTE, 61.0/60.0))); } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CaNanoLabSecurityException; import gov.nih.nci.calab.exception.InvalidSessionException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.calab.service.particle.NanoparticleService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.particle.InitParticleSetup; import gov.nih.nci.calab.ui.protocol.InitProtocolSetup; import gov.nih.nci.calab.ui.security.InitSecuritySetup; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected ActionForward prepareCreate(ActionMapping mapping, HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ActionMessages msgs = new ActionMessages(); // validate that characterization file/derived data can't be empty for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getType().length() == 0 && derivedDataFileBean.getCategories().length == 0 && derivedDataFileBean.getDisplayName().length() == 0 && derivedDataFileBean.getDatumList().size() == 0) { ActionMessage msg = new ActionMessage( "error.emptyCharacterizationFile"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return mapping.getInputForward(); } } for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>(); for (DatumBean datumBean : derivedDataFileBean.getDatumList()) { // validate that neither name nor value can be empty if (datumBean.getName().length() == 0 || datumBean.getValue().length() == 0) { ActionMessage msg = new ActionMessage( "error.emptyDerivedDatum"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return mapping.getInputForward(); } if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) { if (!datumBean.getValue().equalsIgnoreCase("true") && !datumBean.getValue().equalsIgnoreCase("false") && !datumBean.getValue().equalsIgnoreCase("yes") && !datumBean.getValue().equalsIgnoreCase("no")) { ActionMessage msg = new ActionMessage( "error.booleanDerivedDatum"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return mapping.getInputForward(); } } else { if (!StringUtils.isDouble(datumBean.getValue()) && !StringUtils.isInteger(datumBean.getValue())) { ActionMessage msg = new ActionMessage( "error.derivedDatumFormat"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return mapping.getInputForward(); } } // validate derived data has unique name, statistics type and // category String uniqueStr = datumBean.getName() + ":" + datumBean.getStatisticsType() + ":" + datumBean.getCategory(); if (uniqueDatumMap.get(uniqueStr) != null) { ActionMessage msg = new ActionMessage( "error.uniqueDerivedDatum"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return mapping.getInputForward(); } else { uniqueDatumMap.put(uniqueStr, 1); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); ParticleBean particle = (ParticleBean) theForm.get("particle"); charBean.setParticle(particle); return null; } protected ActionForward postCreate(HttpServletRequest request, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // save new lookup up types in the database definition tables. NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.addNewCharacterizationDataDropdowns(charBean, charBean .getName()); UserBean user = (UserBean) request.getSession().getAttribute("user"); service.setCharacterizationUserVisiblity(charBean, user); request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); request.setAttribute("theParticle", particle); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getName()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return mapping.findForward("success"); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; NanoparticleService service = new NanoparticleService(); int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); // overwrite particle ParticleBean otherParticle = service.getParticleBy(particleName); newCharBean.setParticle(otherParticle); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace(particle .getSampleName(), particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } private void setParticleInForm(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { UserBean user = (UserBean) request.getSession().getAttribute("user"); // set up particle String particleId = request.getParameter("particleId"); NanoparticleService particleService = new NanoparticleService(); ParticleBean particle = particleService.getParticleInfo(particleId, user); theForm.set("particle", particle); request.setAttribute("theParticle", particle); // set up other particles from the same source SortedSet<String> allOtherParticleNames = particleService .getOtherParticles(particle.getSampleSource(), particle .getSampleName(), user); request.getSession().setAttribute("allOtherParticleNames", allOtherParticleNames); InitParticleSetup.getInstance() .setSideParticleMenu(request, particleId); } private void setCharacterizationInForm(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String characterizationId = request.getParameter("characterizationId"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set createdBy and createdDate for the characterization UserBean user = (UserBean) request.getSession().getAttribute("user"); if (characterizationId != null) { NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService(); charBean = charService.getCharacterizationBy(characterizationId, user); if (charBean == null) { throw new InvalidSessionException( "This characterization no longer exists in the database. Please log in again to refresh."); } theForm.set("achar", charBean); } else { String submitType = (String) request.getParameter("submitType"); // set characterization name to be the same as submit type if (submitType != null) { charBean.setName(submitType); } } // set characterization type whether physical or in vitro String charType = InitParticleSetup.getInstance().getCharType( request.getSession(), charBean.getName()); charBean.setCharacterizationType(charType); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); InitParticleSetup.getInstance() .setAllCharacterizationDropdowns(session); setParticleInForm(request, theForm); setCharacterizationInForm(request, theForm); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); InitParticleSetup.getInstance() .setAllCharacterizationMeasureUnitsTypes(session, submitType); InitParticleSetup.getInstance().setDerivedDatumNames(session, charBean.getName()); InitProtocolSetup.getInstance().setProtocolFilesByCharType(session, charBean.getCharacterizationType()); InitSessionSetup.getInstance().setApplicationOwner(session); InitParticleSetup.getInstance().setAllInstruments(session); InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session); } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; HttpSession session = request.getSession(); // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String charNameOneWord = StringUtils .getOneWordLowerCaseFirstLetter(achar.getName()); String setupPage = charNameOneWord + "Setup"; if (achar.getName().equals(Characterization.PHYSICAL_SHAPE)) { ShapeBean shape = (ShapeBean) theForm.get("shape"); updateShapeEditable(session, shape); } else if (achar.getName().equals(Characterization.PHYSICAL_MORPHOLOGY)) { MorphologyBean morphology = (MorphologyBean) theForm .get("morphology"); updateMorphologyEditable(session, morphology); } else if (achar.getName().equals(Characterization.PHYSICAL_SOLUBILITY)) { SolubilityBean solubility = (SolubilityBean) theForm .get("solubility"); updateSolubilityEditable(session, solubility); } else if (achar.getName().equals(Characterization.PHYSICAL_SURFACE)) { } else if (achar.getName().equals( Characterization.CYTOTOXICITY_CELL_VIABILITY) || achar.getName().equals( Characterization.CYTOTOXICITY_CASPASE3_ACTIVIATION)) { CytotoxicityBean cyto = (CytotoxicityBean) theForm .get("cytotoxicity"); updateCytotoxicityEditable(session, cyto); setupPage = "cytotoxicitySetup"; } else { setupPage = "setup"; } updateAllCharEditables(session, achar); // updateSurfaceEditable(session, surface); return mapping.findForward(setupPage); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set characterizations with additional information if (charBean instanceof ShapeBean) { theForm.set("shape", charBean); } else if (charBean instanceof MorphologyBean) { theForm.set("morphology", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof SurfaceBean) { theForm.set("surface", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof CytotoxicityBean) { theForm.set("cytotoxicity", charBean); } return input(mapping, form, request, response); } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String particleId = request.getParameter("particleId"); String characterizationId = request.getParameter("characterizationId"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printDetailView&particleId=" + particleId + "&characterizationId=" + characterizationId + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); return mapping.findForward("detailView"); } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); UserBean user = (UserBean) request.getSession().getAttribute("user"); ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileName = service.getExportFileName(particle, achar, "detail"); response.setContentType("application/vnd.ms-execel"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls"); OutputStream out = response.getOutputStream(); HSSFWorkbook wb = new HSSFWorkbook(); service.exportDetailService(particle, achar, wb, user); wb.write(out); if (out != null) { out.flush(); out.close(); } return null; } public ActionForward exportSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; setSummaryView(form, request); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); List<CharacterizationSummaryBean> summaryBeans = new ArrayList<CharacterizationSummaryBean>( (List<? extends CharacterizationSummaryBean>) request .getAttribute("summaryViewBeans")); SortedSet<String> datumLabels = new TreeSet<String>( (SortedSet<? extends String>) request .getAttribute("datumLabels")); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); String fileName = service.getExportFileName(particle, charBean, "summary"); response.setContentType("application/vnd.ms-execel"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls"); OutputStream out = response.getOutputStream(); service.exportSummaryService(datumLabels, summaryBeans, particle, out); return null; } public ActionForward exportFullSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; setSummaryView(form, request); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> summaryBeans = new ArrayList<CharacterizationSummaryBean>( (List<? extends CharacterizationSummaryBean>) request .getAttribute("summaryViewBeans")); SortedSet<String> datumLabels = new TreeSet<String>( (SortedSet<? extends String>) request .getAttribute("datumLabels")); List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>( (List<? extends CharacterizationBean>) request .getAttribute("summaryViewCharBeans")); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String fileName = service.getExportFileName(particle, charBean, "full_summary"); response.setContentType("application/vnd.ms-execel"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls"); OutputStream out = response.getOutputStream(); UserBean user = (UserBean) request.getSession().getAttribute("user"); service.exportFullSummaryService(charBeans, datumLabels, user, summaryBeans, particle, out); return null; } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.findForward("detailPrintView"); } private void setSummaryView(ActionForm form, HttpServletRequest request) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); UserBean user = (UserBean) request.getSession().getAttribute("user"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> charSummaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId(), user); if (charSummaryBeans == null) { throw new InvalidSessionException( "These characterizations no longer exist in the database. Please log in again to refresh"); } List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>(); SortedSet<String> datumLabels = new TreeSet<String>(); for (CharacterizationSummaryBean summaryBean : charSummaryBeans) { Map<String, String> datumMap = summaryBean.getDatumMap(); if (datumMap != null && !datumMap.isEmpty()) { datumLabels.addAll(datumMap.keySet()); } if (!charBeans.contains(summaryBean.getCharBean())) { charBeans.add(summaryBean.getCharBean()); } } request.setAttribute("summaryViewBeans", charSummaryBeans); request.setAttribute("summaryViewCharBeans", charBeans); request.setAttribute("datumLabels", datumLabels); } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; String printAllLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printFullSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); request.setAttribute("printAllLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward printSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintView"); } public ActionForward printFullSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintAllView"); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); derivedBioAssayDataBean.setParticleName(particle.getSampleName()); derivedBioAssayDataBean.setCharacterizationName(achar.getName()); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.getFile(fileId, user); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage( "error.noCharacterizationFile"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); return mapping.findForward("particleMessage"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("childCompInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.deleteCharacterizations(new String[] { charBean.getId() }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return mapping.findForward("particleMessage"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package org.quartz.ui.web.action.schedule; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobListener; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.impl.StdSchedulerFactory; import org.quartz.ui.web.form.ChooseSchedulerForm; import org.quartz.ui.web.form.JobDetailForm; import org.quartz.ui.web.form.ListenerForm; import org.quartz.ui.web.form.SchedulerDTO; /** * Process scheduler command, and populate schedule summary information * */ public class ScheduleControler extends ScheduleBase { String command=""; String newSchedulerName=""; ChooseSchedulerForm scheduleInfo=new ChooseSchedulerForm(); public String execute() { if (LOG.isDebugEnabled()) { LOG.debug("command=" + command); } if (hasErrors() && 1 ==2) { LOG.info("this thing has errors"); LOG.info(this.getActionErrors().toString()); return INPUT; } else { Scheduler chosenScheduler = null; try { chosenScheduler = getScheduler(); if (command.equals("start")) { chosenScheduler.start(); } else if (command.equals("stop")) { chosenScheduler.shutdown(); } else if (command.equals("pause")) { chosenScheduler.pause(); } else if (command.equals("waitAndStopScheduler")) { chosenScheduler.shutdown(true); } else if (command.equals("pauseAll")) { chosenScheduler.pauseAll(); } else if (command.equals("resumeAll")) { chosenScheduler.resumeAll(); } this.populateSchedulerForm(chosenScheduler, scheduleInfo); } catch (SchedulerException e) { LOG.error("error in Scheduler Controller, command=:" + command, e); } catch (Exception e) { LOG.error("error in Scheduler Controller, command=:" + command, e); } } return SUCCESS; } /** * @return * @throws SchedulerException */ private Scheduler getScheduler() throws SchedulerException { Scheduler chosenScheduler; if (newSchedulerName != null && newSchedulerName.length() > 0) chosenScheduler = new StdSchedulerFactory().getScheduler(newSchedulerName); else { chosenScheduler = StdSchedulerFactory.getDefaultScheduler(); } return chosenScheduler; } /** * populate DTO with scheduler information summary. * @param chosenScheduler * @param form * @throws Exception */ private void populateSchedulerForm(Scheduler chosenScheduler, ChooseSchedulerForm form) throws Exception { Collection scheduleCollection = new StdSchedulerFactory().getAllSchedulers(); Iterator itr = scheduleCollection.iterator(); form.setSchedulers(new ArrayList()); try { form.setChoosenSchedulerName(chosenScheduler.getSchedulerName()); while (itr.hasNext()) { Scheduler scheduler = (Scheduler) itr.next(); form.getSchedulers().add(scheduler); } } catch (SchedulerException e) { throw new Exception(e); } SchedulerDTO schedForm = new SchedulerDTO(); schedForm.setSchedulerName(chosenScheduler.getSchedulerName()); schedForm.setNumJobsExecuted(String.valueOf(chosenScheduler.getMetaData().numJobsExecuted())); if (chosenScheduler.getMetaData().jobStoreSupportsPersistence()) { schedForm.setPersistenceType("value.scheduler.persiststenceType.database"); } else { schedForm.setPersistenceType("value.scheduler.persiststenceType.memory"); // mp possible bugfix } schedForm.setRunningSince(String.valueOf(chosenScheduler.getMetaData().runningSince())); if (chosenScheduler.isShutdown()) { schedForm.setState("value.scheduler.state.stopped"); } else if (chosenScheduler.isPaused()) { schedForm.setState("value.scheduler.state.paused"); } else { schedForm.setState("value.scheduler.state.started"); } schedForm.setThreadPoolSize(String.valueOf(chosenScheduler.getMetaData().getThreadPoolSize())); schedForm.setVersion(chosenScheduler.getMetaData().getVersion()); schedForm.setSummary(chosenScheduler.getMetaData().getSummary()); List jobDetails = chosenScheduler.getCurrentlyExecutingJobs(); for (Iterator iter = jobDetails.iterator(); iter.hasNext();) { JobExecutionContext job = (JobExecutionContext) iter.next(); JobDetail jobDetail = job.getJobDetail(); JobDetailForm jobForm = new JobDetailForm(); jobForm.setGroupName(jobDetail.getGroup()); jobForm.setName(jobDetail.getName()); jobForm.setDescription(jobDetail.getDescription()); jobForm.setJobClass(jobDetail.getJobClass().getName()); form.getExecutingJobs().add(jobForm); } String calendars[]; if (!chosenScheduler.isShutdown()) calendars = chosenScheduler.getCalendarNames(); List jobListeners = chosenScheduler.getGlobalJobListeners(); for (Iterator iter = jobListeners.iterator(); iter.hasNext();) { JobListener jobListener = (JobListener) iter.next(); ListenerForm listenerForm = new ListenerForm(); listenerForm.setListenerName(jobListener.getName()); listenerForm.setListenerClass(jobListener.getClass().getName()); schedForm.getGlobalJobListeners().add(listenerForm); } // The section commented out below is not currently used, but may be used to show triggers that have been // added to jobs /* List triggerListeners = chosenScheduler.getGlobalTriggerListeners(); for (Iterator iter = triggerListeners.iterator(); iter.hasNext();) { TriggerListener triggerListener = (TriggerListener) iter.next(); ListenerForm listenerForm = new ListenerForm(); listenerForm.setListenerName(triggerListener.getName()); listenerForm.setListenerClass(triggerListener.getClass().getName()); schedForm.getGlobalJobListeners().add(listenerForm); } Set jobListenerNames = chosenScheduler.getJobListenerNames(); for (Iterator iter = jobListenerNames.iterator(); iter.hasNext();) { JobListener jobListener = chosenScheduler.getJobListener((String) iter.next()); ListenerForm listenerForm = new ListenerForm(); listenerForm.setListenerName(jobListener.getName()); listenerForm.setListenerClass(jobListener.getClass().getName()); schedForm.getRegisteredJobListeners().add(listenerForm); } Set triggerListenerNames = chosenScheduler.getTriggerListenerNames(); for (Iterator iter = triggerListenerNames.iterator(); iter.hasNext();) { TriggerListener triggerListener = chosenScheduler.getTriggerListener((String) iter.next()); ListenerForm listenerForm = new ListenerForm(); listenerForm.setListenerName(triggerListener.getName()); listenerForm.setListenerClass(triggerListener.getClass().getName()); schedForm.getRegisteredTriggerListeners().add(listenerForm); } List schedulerListeners = chosenScheduler.getSchedulerListeners(); for (Iterator iter = schedulerListeners.iterator(); iter.hasNext();) { SchedulerListener schedulerListener = (SchedulerListener) iter.next(); ListenerForm listenerForm = new ListenerForm(); listenerForm.setListenerClass(schedulerListener.getClass().getName()); schedForm.getSchedulerListeners().add(listenerForm); } */ //TODO fix this form.setScheduler(schedForm); } /** * @return Returns the command. */ public String getCommand() { return command; } /** * @param command The command to set. */ public void setCommand(String command) { this.command = command; } /** * @return Returns the newSchedulerName. */ public String getNewSchedulerName() { return newSchedulerName; } /** * @param newSchedulerName The newSchedulerName to set. */ public void setNewSchedulerName(String newSchedulerName) { this.newSchedulerName = newSchedulerName; } /** * @return Returns the scheduleInfo. */ public ChooseSchedulerForm getScheduleInfo() { return scheduleInfo; } } /* * need to populate the following * * schedulerName scheduleState runningSince numJobsExecuted persistenceType threadPoolSize version lists Schedulers-name chooseScheduler - executing jobs groupName name description jobClass chooseScheduler.summary */
package org.bouncycastle.asn1.test; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.x509.qualified.Iso4217CurrencyCode; import org.bouncycastle.util.test.SimpleTest; public class Iso4217CurrencyCodeUnitTest extends SimpleTest { private static final String ALPHABETIC_CURRENCY_CODE = "AUD"; private static final int NUMERIC_CURRENCY_CODE = 1; public String getName() { return "Iso4217CurrencyCode"; } public void performTest() throws Exception { // alphabetic Iso4217CurrencyCode cc = new Iso4217CurrencyCode(ALPHABETIC_CURRENCY_CODE); checkNumeric(cc, ALPHABETIC_CURRENCY_CODE); cc = Iso4217CurrencyCode.getInstance(cc); checkNumeric(cc, ALPHABETIC_CURRENCY_CODE); ASN1Primitive obj = cc.toASN1Object(); cc = Iso4217CurrencyCode.getInstance(obj); checkNumeric(cc, ALPHABETIC_CURRENCY_CODE); // numeric cc = new Iso4217CurrencyCode(NUMERIC_CURRENCY_CODE); checkNumeric(cc, NUMERIC_CURRENCY_CODE); cc = Iso4217CurrencyCode.getInstance(cc); checkNumeric(cc, NUMERIC_CURRENCY_CODE); obj = cc.toASN1Object(); cc = Iso4217CurrencyCode.getInstance(obj); checkNumeric(cc, NUMERIC_CURRENCY_CODE); cc = Iso4217CurrencyCode.getInstance(null); if (cc != null) { fail("null getInstance() failed."); } try { Iso4217CurrencyCode.getInstance(new Object()); fail("getInstance() failed to detect bad object."); } catch (IllegalArgumentException e) { // expected } try { new Iso4217CurrencyCode("ABCD"); fail("constructor failed to detect out of range currencycode."); } catch (IllegalArgumentException e) { // expected } try { new Iso4217CurrencyCode(0); fail("constructor failed to detect out of range small numeric code."); } catch (IllegalArgumentException e) { // expected } try { new Iso4217CurrencyCode(1000); fail("constructor failed to detect out of range large numeric code."); } catch (IllegalArgumentException e) { // expected } } private void checkNumeric( Iso4217CurrencyCode cc, String code) { if (!cc.isAlphabetic()) { fail("non-alphabetic code found when one expected."); } if (!cc.getAlphabetic().equals(code)) { fail("string codes don't match."); } } private void checkNumeric( Iso4217CurrencyCode cc, int code) { if (cc.isAlphabetic()) { fail("alphabetic code found when one not expected."); } if (cc.getNumeric() != code) { fail("numeric codes don't match."); } } public static void main( String[] args) { runTest(new Iso4217CurrencyCodeUnitTest()); } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CaNanoLabSecurityException; import gov.nih.nci.calab.exception.FileException; import gov.nih.nci.calab.exception.ParticleCharacterizationException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.calab.service.particle.NanoparticleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.particle.InitParticleSetup; import gov.nih.nci.calab.ui.protocol.InitProtocolSetup; import gov.nih.nci.calab.ui.security.InitSecuritySetup; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected CharacterizationBean prepareCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // validate that characterization file/derived data can't be empty for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getType().length() == 0 && derivedDataFileBean.getCategories().length == 0 && derivedDataFileBean.getDisplayName().length() == 0 && derivedDataFileBean.getDatumList().size() == 0) { throw new ParticleCharacterizationException( "has an empty section for characterization file/derived data. Please remove it prior to saving."); } } for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>(); for (DatumBean datumBean : derivedDataFileBean.getDatumList()) { // validate that neither name nor value can be empty if (datumBean.getName().length() == 0 || datumBean.getValue().length() == 0) { throw new ParticleCharacterizationException( "Derived data name and value can't be empty."); } if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) { if (!datumBean.getValue().equalsIgnoreCase("true") && !datumBean.getValue().equalsIgnoreCase("false") && !datumBean.getValue().equalsIgnoreCase("yes") && !datumBean.getValue().equalsIgnoreCase("no")) { throw new ParticleCharacterizationException( "The datum value for boolean type should be 'True'/'False' or 'Yes'/'No'."); } } else { if (!StringUtils.isDouble(datumBean.getValue()) && !StringUtils.isInteger(datumBean.getValue())) { throw new ParticleCharacterizationException( "The datum value should be a number."); } } // validate derived data has unique name, statistics type and // category String uniqueStr = datumBean.getName() + ":" + datumBean.getStatisticsType() + ":" + datumBean.getCategory(); if (uniqueDatumMap.get(uniqueStr) != null) { throw new ParticleCharacterizationException( "no two derived data can have the same name, statistics type and category."); } else { uniqueDatumMap.put(uniqueStr, 1); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); ParticleBean particle = (ParticleBean) theForm.get("particle"); charBean.setParticle(particle); return charBean; } protected ActionForward postCreate(HttpServletRequest request, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // save new lookup up types in the database definition tables. NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.addNewCharacterizationDataDropdowns(charBean, charBean .getName()); request.getSession().setAttribute("newCharacterizationCreated", "true"); request.getSession().setAttribute("newCharacterizationSourceCreated", "true"); request.getSession().setAttribute("newInstrumentCreated", "true"); request.getSession().setAttribute("newCharacterizationFileTypeCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); request.setAttribute("theParticle", particle); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getName()); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; NanoparticleService service = new NanoparticleService(); int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); // overwrite particle and particle type; newCharBean.getParticle().setSampleName(particleName); ParticleBean otherParticle = service.getParticleBy(particleName); newCharBean.getParticle().setSampleType( otherParticle.getSampleType()); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace(particle .getSampleName(), particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitParticleSetup.getInstance() .setAllCharacterizationDropdowns(session); // set up particle String particleId = request.getParameter("particleId"); if (particleId != null) { NanoparticleService particleService = new NanoparticleService(); ParticleBean particle = particleService.getParticleInfo(particleId, user); theForm.set("particle", particle); request.setAttribute("theParticle", particle); // set up other particles from the same source SortedSet<String> allOtherParticleNames = particleService .getOtherParticles(particle.getSampleSource(), particle .getSampleName(), user); session .setAttribute("allOtherParticleNames", allOtherParticleNames); InitParticleSetup.getInstance().setSideParticleMenu(request, particleId); } else { throw new ParticleCharacterizationException( "Particle ID is required."); } InitSessionSetup.getInstance().setApplicationOwner(session); InitParticleSetup.getInstance().setAllInstruments(session); InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session); InitParticleSetup.getInstance().setAllPhysicalDropdowns(session); InitParticleSetup.getInstance().setAllInvitroDropdowns(session); // set characterization String submitType = (String) request.getParameter("submitType"); String characterizationId = request.getParameter("characterizationId"); if (characterizationId != null) { NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService(); CharacterizationBean charBean = charService .getCharacterizationBy(characterizationId); if (charBean == null) { throw new ParticleCharacterizationException( "This characterization no longer exists in the database. Please log in again to refresh."); } theForm.set("achar", charBean); } CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); if (achar != null && submitType != null) { achar.setName(submitType); InitParticleSetup.getInstance() .setAllCharacterizationMeasureUnitsTypes(session, submitType); InitParticleSetup.getInstance().setDerivedDatumNames(session, achar.getName()); InitProtocolSetup.getInstance().setProtocolFilesByCharName(session, achar.getName()); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); // set up characterization files visibility, and whether file is an // image for (DerivedBioAssayDataBean fileBean : achar .getDerivedBioAssayDataList()) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); fileBean.setImage(imageStatus); } } // set up protocol file visibility ProtocolFileBean protocolFileBean = achar.getProtocolFileBean(); if (protocolFileBean != null) { boolean status = false; if (protocolFileBean.getId() != null) { status = userService.checkReadPermission(user, protocolFileBean.getId()); } if (status) { protocolFileBean.setHidden(false); } else { protocolFileBean.setHidden(true); } } } } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); ShapeBean shape = (ShapeBean) theForm.get("shape"); MorphologyBean morphology = (MorphologyBean) theForm.get("morphology"); CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity"); SolubilityBean solubility = (SolubilityBean) theForm.get("solubility"); HttpSession session = request.getSession(); updateAllCharEditables(session, achar); updateShapeEditable(session, shape); updateMorphologyEditable(session, morphology); updateCytotoxicityEditable(session, cyto); updateSolubilityEditable(session, solubility); // updateSurfaceEditable(session, surface); return mapping.findForward("setup"); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set characterizations with additional information if (charBean instanceof ShapeBean) { theForm.set("shape", charBean); } else if (charBean instanceof MorphologyBean) { theForm.set("morphology", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof SurfaceBean) { theForm.set("surface", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof CytotoxicityBean) { theForm.set("cytotoxicity", charBean); } return mapping.findForward("setup"); } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String particleId = request.getParameter("particleId"); String characterizationId = request.getParameter("characterizationId"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printDetailView&particleId=" + particleId + "&characterizationId=" + characterizationId + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); return mapping.findForward("detailView"); } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); // response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + "_" + charBean.getViewTitle() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); service.exportDetailService(theForm, out, user); return null; } public ActionForward exportSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); // response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); List<CharacterizationSummaryBean> summaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId()); SortedSet<String> datumLabels = service.setDataLabelsAndFileVisibility( user, summaryBeans); service.exportSummaryService(datumLabels, summaryBeans, submitType, theForm, out, user); return mapping.findForward("summaryView"); } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.findForward("detailPrintView"); } private void setSummaryView(ActionForm form, HttpServletRequest request) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> charSummaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId()); if (charSummaryBeans == null) { throw new Exception( "There are no such characterizations in the database."); } // set data labels and file visibility, and whether file is an image UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); UserBean user = (UserBean) request.getSession().getAttribute("user"); List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>(); SortedSet<String> datumLabels = new TreeSet<String>(); for (CharacterizationSummaryBean summaryBean : charSummaryBeans) { Map<String, String> datumMap = summaryBean.getDatumMap(); if (datumMap != null && !datumMap.isEmpty()) { datumLabels.addAll(datumMap.keySet()); } DerivedBioAssayDataBean fileBean = summaryBean.getCharFile(); if (fileBean != null) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); } fileBean.setImage(imageStatus); } if (!charBeans.contains(summaryBean.getCharBean())) { charBeans.add(summaryBean.getCharBean()); } } request.setAttribute("summaryViewBeans", charSummaryBeans); request.setAttribute("summaryViewCharBeans", charBeans); request.setAttribute("datumLabels", datumLabels); } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; String printAllLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printFullSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); request.setAttribute("printAllLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward printSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintView"); } public ActionForward printFullSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintAllView"); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); derivedBioAssayDataBean.setParticleName(particle.getSampleName()); derivedBioAssayDataBean.setCharacterizationName(achar.getName()); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.getFile(fileId, user); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new FileException( "File to download doesn't exist on the server"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("childCompInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); ParticleBean particle = (ParticleBean) theForm.get("particle"); String charId = request.getParameter("characterizationId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.deleteCharacterizations(new String[] { charId }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package org.haxe.duell; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; // import android.system.Os; // import android.system.OsConstants; import android.system.ErrnoException; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import org.haxe.HXCPP; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; public class DuellActivity extends Activity { private static WeakReference<DuellActivity> activity = new WeakReference<DuellActivity>(null); private final Handler mainJavaThreadHandler; private MainHaxeThreadHandler mainHaxeThreadHandler; /** Exposes the parent so that it can be used to set the content view instead */ public FrameLayout parent; public boolean defaultOnBack; /// libraries that initialize a view, may choose to set this, so that other libraries can act upon this public WeakReference<View> mainView; private final List<Extension> extensions; public DuellActivity() { DuellActivity.activity = new WeakReference<DuellActivity>(this); mainView = new WeakReference<View>(null); mainJavaThreadHandler = new Handler(); // default handler mainHaxeThreadHandler = new MainHaxeThreadHandler() { @Override public void queueRunnableOnMainHaxeThread(Runnable runObj) { mainJavaThreadHandler.post(runObj); } }; defaultOnBack = true; extensions = new ArrayList<Extension>(); ::foreach PLATFORM.ACTIVITY_EXTENSIONS::; extensions.add(new ::__current__:: ());::end:: } public static DuellActivity getInstance() { return activity.get(); } protected void onCreate(Bundle state) { super.onCreate(state); requestWindowFeature(Window.FEATURE_NO_TITLE); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) // /// MAKE SURE WE ALWAYS HAVE CRASHLOGS // /// Only available for Lolipop and above // try // Os.prctl(OsConstants.PR_SET_DUMPABLE, 1, 0, 0, 0); // catch(ErrnoException exception) // Log.d("DUELL", "prctl error:" + exception.getMessage()); ::if PLATFORM.FULLSCREEN:: ::if (PLATFORM.TARGET_SDK_VERSION < 19):: getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ::end:: ::end:: ::foreach NDLLS:: System.loadLibrary("::NAME::");::end:: ;parent = new FrameLayout(this); super.setContentView(parent); HXCPP.run("HaxeApplication"); for (Extension extension : extensions) { extension.onCreate(state); } } ::if (PLATFORM.FULLSCREEN):: ::if (PLATFORM.TARGET_SDK_VERSION >= 19):: // IMMERSIVE MODE SUPPORT @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { hideSystemUi(); } } private void hideSystemUi() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } ::end:: ::end:: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { for (Extension extension : extensions) { if (!extension.onActivityResult(requestCode, resultCode, data)) { return; } } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onDestroy() { for (Extension extension : extensions) { extension.onDestroy(); } activity = new WeakReference<DuellActivity>(null); super.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); for (Extension extension : extensions) { extension.onLowMemory(); } } @Override protected void onNewIntent(final Intent intent) { for (Extension extension : extensions) { extension.onNewIntent(intent); } super.onNewIntent(intent); } @Override protected void onPause() { super.onPause(); for (Extension extension : extensions) { extension.onPause(); } } @Override protected void onRestart() { super.onRestart(); for (Extension extension : extensions) { extension.onRestart(); } } @Override protected void onResume() { super.onResume(); for (Extension extension : extensions) { extension.onResume(); } } @Override protected void onStart() { super.onStart(); ::if PLATFORM.FULLSCREEN::::if (PLATFORM.ANDROID_TARGET_SDK_VERSION >= 16):: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN); } ::end::::end:: for (Extension extension : extensions) { extension.onStart(); } } @Override protected void onStop() { super.onStop(); for (Extension extension : extensions) { extension.onStop(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); for (Extension extension : extensions) { extension.onSaveInstanceState(outState); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { for (Extension extension : extensions) { extension.onKeyDown(keyCode, event); } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { for (Extension extension : extensions) { extension.onKeyUp(keyCode, event); } return super.onKeyUp(keyCode, event); } ::if (PLATFORM.TARGET_SDK_VERSION >= 14):: @Override public void onTrimMemory(int level) { super.onTrimMemory(level); for (Extension extension : extensions) { extension.onTrimMemory(level); } } ::end:: public void registerExtension(Extension extension) { if (extensions.indexOf(extension) == -1) { extensions.add(extension); } } /// post to this queue any java to haxe communication on the main thread. /// may be set by extension to be something else, for example, the opengl library can setMainThreadHandler /// to be processed in the gl thread because it is generally preferable to communicate with haxe by that. /// defaults to itself public void queueOnHaxeThread(Runnable run) { mainHaxeThreadHandler.queueRunnableOnMainHaxeThread(run); } /// if you want to force some callback to be executed on the main thread public void queueOnMainThread(Runnable run) { mainJavaThreadHandler.post(run); } public void setMainHaxeThreadHandler(MainHaxeThreadHandler handler) { mainHaxeThreadHandler = handler; } @Override public void setContentView(View view) { throw new IllegalStateException("Callers should interact with the parent FrameLayout instead of with the view directly"); } @Override public void onBackPressed() { for (Extension extension : extensions) { extension.onBackPressed(); } if (defaultOnBack) { super.onBackPressed(); } } }
package org.knowm.xchange.currency; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * A Currency class roughly modeled after {@link java.util.Currency}. * </p> * Each object retains the code it was acquired with -- so {@link #getInstance}("BTC").{@link #getCurrencyCode}() will always be "BTC", even though * the proposed ISO 4217 code is "XBT" */ public class Currency implements Comparable<Currency>, Serializable { private static final Map<String, Currency> currencies = new HashMap<>(); /** * Global currency codes */ // TODO: Load from json resource public static final Currency AED = createCurrency("AED", "United Arab Emirates Dirham", null); public static final Currency AFN = createCurrency("AFN", "Afghan Afghani", null); public static final Currency ALL = createCurrency("ALL", "Albanian Lek", null); public static final Currency AMD = createCurrency("AMD", "Armenian Dram", null); public static final Currency ANC = createCurrency("ANC", "Anoncoin", null); public static final Currency ANG = createCurrency("ANG", "Netherlands Antillean Guilder", null); public static final Currency AOA = createCurrency("AOA", "Angolan Kwanza", null); public static final Currency ARN = createCurrency("ARN", "Aeron", null); public static final Currency ARS = createCurrency("ARS", "Argentine Peso", null); public static final Currency AUD = createCurrency("AUD", "Australian Dollar", null); public static final Currency AUR = createCurrency("AUR", "Auroracoin", null); public static final Currency AWG = createCurrency("AWG", "Aruban Florin", null); public static final Currency AZN = createCurrency("AZN", "Azerbaijani Manat", null); public static final Currency BAM = createCurrency("BAM", "Bosnia-Herzegovina Convertible Mark", null); public static final Currency BAT = createCurrency("BAT", "Basic Attention Token", null); public static final Currency BBD = createCurrency("BBD", "Barbadian Dollar", null); public static final Currency BC = createCurrency("BC", "BlackCoin", null, "BLK"); public static final Currency BCC = createCurrency("BCC", "BitConnect", null); public static final Currency BCH = createCurrency("BCH", "BitcoinCash", null); public static final Currency BLK = getInstance("BLK"); public static final Currency BDT = createCurrency("BDT", "Bangladeshi Taka", null); public static final Currency BGC = createCurrency("BGC", "Aten 'Black Gold' Coin", null); public static final Currency BGN = createCurrency("BGN", "Bulgarian Lev", null); public static final Currency BHD = createCurrency("BHD", "Bahraini Dinar", null); public static final Currency BIF = createCurrency("BIF", "Burundian Franc", null); public static final Currency BMD = createCurrency("BMD", "Bermudan Dollar", null); public static final Currency BND = createCurrency("BND", "Brunei Dollar", null); public static final Currency BOB = createCurrency("BOB", "Bolivian Boliviano", null); public static final Currency BRL = createCurrency("BRL", "Brazilian Real", "R$"); public static final Currency BSD = createCurrency("BSD", "Bahamian Dollar", null); public static final Currency BTC = createCurrency("BTC", "Bitcoin", null, "XBT"); public static final Currency BTG = createCurrency("BTG", "Bitcoin Gold", null); public static final Currency XBT = getInstance("XBT"); public static final Currency BTN = createCurrency("BTN", "Bhutanese Ngultrum", null); public static final Currency BWP = createCurrency("BWP", "Botswanan Pula", null); public static final Currency BYR = createCurrency("BYR", "Belarusian Ruble", null); public static final Currency BZD = createCurrency("BZD", "Belize Dollar", null); public static final Currency CAD = createCurrency("CAD", "Canadian Dollar", null); public static final Currency CDF = createCurrency("CDF", "Congolese Franc", null); public static final Currency CHF = createCurrency("CHF", "Swiss Franc", null); public static final Currency CLF = createCurrency("CLF", "Chilean Unit of Account (UF)", null); public static final Currency CLP = createCurrency("CLP", "Chilean Peso", null); public static final Currency CNC = createCurrency("CNC", "Chinacoin", null); public static final Currency CNY = createCurrency("CNY", "Chinese Yuan", null); public static final Currency COP = createCurrency("COP", "Colombian Peso", null); public static final Currency CRC = createCurrency("CRC", "Costa Rican Colón", null); public static final Currency CUP = createCurrency("CUP", "Cuban Peso", null); public static final Currency CVE = createCurrency("CVE", "Cape Verdean Escudo", null); public static final Currency CZK = createCurrency("CZK", "Czech Republic Koruna", null); public static final Currency DASH = createCurrency("DASH", "Dash", null); public static final Currency DCR = createCurrency("DCR", "Decred", null); public static final Currency DGB = createCurrency("DGB", "DigiByte", null); public static final Currency DJF = createCurrency("DJF", "Djiboutian Franc", null); public static final Currency DKK = createCurrency("DKK", "Danish Krone", null); public static final Currency DOGE = createCurrency("DOGE", "Dogecoin", null, "XDC", "XDG"); public static final Currency XDC = getInstance("XDC"); public static final Currency XDG = getInstance("XDG"); public static final Currency DOP = createCurrency("DOP", "Dominican Peso", null); public static final Currency DGC = createCurrency("DGC", "Digitalcoin", null); public static final Currency DVC = createCurrency("DVC", "Devcoin", null); public static final Currency DRK = createCurrency("DRK", "Darkcoin", null); public static final Currency DZD = createCurrency("DZD", "Algerian Dinar", null); public static final Currency EEK = createCurrency("EEK", "Estonian Kroon", null); public static final Currency EGD = createCurrency("EGD", "egoldcoin", null); public static final Currency EGP = createCurrency("EGP", "Egyptian Pound", null); public static final Currency EOS = createCurrency("EOS", "EOS", null); public static final Currency ETB = createCurrency("ETB", "Ethiopian Birr", null); public static final Currency ETC = createCurrency("ETC", "Ether Classic", null); public static final Currency ETH = createCurrency("ETH", "Ether", null); public static final Currency EUR = createCurrency("EUR", "Euro", null); public static final Currency FJD = createCurrency("FJD", "Fijian Dollar", null); public static final Currency _1ST = createCurrency("1ST", "First Blood", null); public static final Currency FKP = createCurrency("FKP", "Falkland Islands Pound", null); public static final Currency FTC = createCurrency("FTC", "Feathercoin", null); public static final Currency GBP = createCurrency("GBP", "British Pound Sterling", null); public static final Currency GEL = createCurrency("GEL", "Georgian Lari", null); public static final Currency GHS = createCurrency("GHS", "Ghanaian Cedi", null); public static final Currency GHs = createCurrency("GHS", "Gigahashes per second", null); public static final Currency GIP = createCurrency("GIP", "Gibraltar Pound", null); public static final Currency GMD = createCurrency("GMD", "Gambian Dalasi", null); public static final Currency GNF = createCurrency("GNF", "Guinean Franc", null); public static final Currency GNO = createCurrency("GNO", "Gnosis", null); public static final Currency GTQ = createCurrency("GTQ", "Guatemalan Quetzal", null); public static final Currency GYD = createCurrency("GYD", "Guyanaese Dollar", null); public static final Currency HKD = createCurrency("HKD", "Hong Kong Dollar", null); public static final Currency HVN = createCurrency("HVN", "Hive", null); public static final Currency HNL = createCurrency("HNL", "Honduran Lempira", null); public static final Currency HRK = createCurrency("HRK", "Croatian Kuna", null); public static final Currency HTG = createCurrency("HTG", "Haitian Gourde", null); public static final Currency HUF = createCurrency("HUF", "Hungarian Forint", null); public static final Currency ICN = createCurrency("ICN", "Iconomi", null); public static final Currency IDR = createCurrency("IDR", "Indonesian Rupiah", null); public static final Currency ILS = createCurrency("ILS", "Israeli New Sheqel", null); public static final Currency INR = createCurrency("INR", "Indian Rupee", null); public static final Currency IOC = createCurrency("IOC", "I/OCoin", null); public static final Currency IOT = createCurrency("IOT", "IOTA", null); public static final Currency IQD = createCurrency("IQD", "Iraqi Dinar", null); public static final Currency IRR = createCurrency("IRR", "Iranian Rial", null); public static final Currency ISK = createCurrency("ISK", "Icelandic Króna", null); public static final Currency IXC = createCurrency("IXC", "iXcoin", null); public static final Currency JEP = createCurrency("JEP", "Jersey Pound", null); public static final Currency JMD = createCurrency("JMD", "Jamaican Dollar", null); public static final Currency JOD = createCurrency("JOD", "Jordanian Dinar", null); public static final Currency JPY = createCurrency("JPY", "Japanese Yen", null); public static final Currency KES = createCurrency("KES", "Kenyan Shilling", null); public static final Currency KGS = createCurrency("KGS", "Kyrgystani Som", null); public static final Currency KHR = createCurrency("KHR", "Cambodian Riel", null); public static final Currency KICK = createCurrency("KICK", "KickCoin", null); public static final Currency KMF = createCurrency("KMF", "Comorian Franc", null); public static final Currency KPW = createCurrency("KPW", "North Korean Won", null); public static final Currency KRW = createCurrency("KRW", "South Korean Won", null); public static final Currency KWD = createCurrency("KWD", "Kuwaiti Dinar", null); public static final Currency KYD = createCurrency("KYD", "Cayman Islands Dollar", null); public static final Currency KZT = createCurrency("KZT", "Kazakhstani Tenge", null); public static final Currency LAK = createCurrency("LAK", "Laotian Kip", null); public static final Currency LBP = createCurrency("LBP", "Lebanese Pound", null); public static final Currency LKR = createCurrency("LKR", "Sri Lankan Rupee", null); public static final Currency LRD = createCurrency("LRD", "Liberian Dollar", null); public static final Currency LSL = createCurrency("LSL", "Lesotho Loti", null); public static final Currency LTC = createCurrency("LTC", "Litecoin", "XLT"); public static final Currency XLT = getInstance("XLT"); public static final Currency LTL = createCurrency("LTL", "Lithuanian Litas", null); public static final Currency LVL = createCurrency("LVL", "Latvian Lats", null); public static final Currency LYD = createCurrency("LYD", "Libyan Dinar", null); public static final Currency MAD = createCurrency("MAD", "Moroccan Dirham", null); public static final Currency MDL = createCurrency("MDL", "Moldovan Leu", null); public static final Currency MEC = createCurrency("MEC", "MegaCoin", null); public static final Currency MGA = createCurrency("MGA", "Malagasy Ariary", null); public static final Currency MKD = createCurrency("MKD", "Macedonian Denar", null); public static final Currency MLN = createCurrency("MLN", "Melonport", null); public static final Currency MMK = createCurrency("MMK", "Myanma Kyat", null); public static final Currency MNT = createCurrency("MNT", "Mongolian Tugrik", null); public static final Currency MOP = createCurrency("MOP", "Macanese Pataca", null); public static final Currency MRO = createCurrency("MRO", "Mauritanian Ouguiya", null); public static final Currency MSC = createCurrency("MSC", "Mason Coin", null); public static final Currency MUR = createCurrency("MUR", "Mauritian Rupee", null); public static final Currency MVR = createCurrency("MVR", "Maldivian Rufiyaa", null); public static final Currency MWK = createCurrency("MWK", "Malawian Kwacha", null); public static final Currency MXN = createCurrency("MXN", "Mexican Peso", null); public static final Currency MYR = createCurrency("MYR", "Malaysian Ringgit", null); public static final Currency MZN = createCurrency("MZN", "Mozambican Metical", null); public static final Currency NAD = createCurrency("NAD", "Namibian Dollar", null); public static final Currency NEO = createCurrency("NEO", "NEO", null); public static final Currency NGN = createCurrency("NGN", "Nigerian Naira", null); public static final Currency NIO = createCurrency("NIO", "Nicaraguan Córdoba", null); public static final Currency NMC = createCurrency("NMC", "Namecoin", null); public static final Currency NOK = createCurrency("NOK", "Norwegian Krone", null); public static final Currency NPR = createCurrency("NPR", "Nepalese Rupee", null); public static final Currency NVC = createCurrency("NVC", "Novacoin", null); public static final Currency NXT = createCurrency("NXT", "Nextcoin", null); public static final Currency NZD = createCurrency("NZD", "New Zealand Dollar", null); public static final Currency OMG = createCurrency("OMG", "OmiseGO", null); public static final Currency OMR = createCurrency("OMR", "Omani Rial", null); public static final Currency PAB = createCurrency("PAB", "Panamanian Balboa", null); public static final Currency PEN = createCurrency("PEN", "Peruvian Nuevo Sol", null); public static final Currency PGK = createCurrency("PGK", "Papua New Guinean Kina", null); public static final Currency PHP = createCurrency("PHP", "Philippine Peso", null); public static final Currency PKR = createCurrency("PKR", "Pakistani Rupee", null); public static final Currency PLN = createCurrency("PLN", "Polish Zloty", null); public static final Currency POT = createCurrency("POT", "PotCoin", null); public static final Currency PPC = createCurrency("PPC", "Peercoin", null); public static final Currency PYG = createCurrency("PYG", "Paraguayan Guarani", null); public static final Currency QAR = createCurrency("QAR", "Qatari Rial", null); public static final Currency QRK = createCurrency("QRK", "QuarkCoin", null); public static final Currency QTUM = createCurrency("QTUM", "Qtum", null); public static final Currency REP = createCurrency("REP", "Augur", null); public static final Currency RON = createCurrency("RON", "Romanian Leu", null); public static final Currency RSD = createCurrency("RSD", "Serbian Dinar", null); public static final Currency RUB = createCurrency("RUB", "Russian Ruble", null); public static final Currency RUR = createCurrency("RUR", "Old Russian Ruble", null); public static final Currency RWF = createCurrency("RWF", "Rwandan Franc", null); public static final Currency SAR = createCurrency("SAR", "Saudi Riyal", null); public static final Currency SBC = createCurrency("SBC", "Stablecoin", null); public static final Currency SBD = createCurrency("SBD", "Solomon Islands Dollar", null); public static final Currency SC = createCurrency("SC", "Siacoin", null); public static final Currency SCR = createCurrency("SCR", "Seychellois Rupee", null); public static final Currency SDG = createCurrency("SDG", "Sudanese Pound", null); public static final Currency SEK = createCurrency("SEK", "Swedish Krona", null); public static final Currency SGD = createCurrency("SGD", "Singapore Dollar", null); public static final Currency SHP = createCurrency("SHP", "Saint Helena Pound", null); public static final Currency SLL = createCurrency("SLL", "Sierra Leonean Leone", null); public static final Currency SOS = createCurrency("SOS", "Somali Shilling", null); public static final Currency SRD = createCurrency("SRD", "Surinamese Dollar", null); public static final Currency START = createCurrency("START", "startcoin", null); public static final Currency STD = createCurrency("STD", "São Tomé and Príncipe Dobra", null); public static final Currency STR = createCurrency("STR", "Stellar", null); public static final Currency SVC = createCurrency("SVC", "Salvadoran Colón", null); public static final Currency SYP = createCurrency("SYP", "Syrian Pound", null); public static final Currency SZL = createCurrency("SZL", "Swazi Lilangeni", null); public static final Currency THB = createCurrency("THB", "Thai Baht", null); public static final Currency TJS = createCurrency("TJS", "Tajikistani Somoni", null); public static final Currency TMT = createCurrency("TMT", "Turkmenistani Manat", null); public static final Currency TND = createCurrency("TND", "Tunisian Dinar", null); public static final Currency TOP = createCurrency("TOP", "Tongan Paʻanga", null); public static final Currency TRC = createCurrency("TRC", "Terracoin", null); public static final Currency TRY = createCurrency("TRY", "Turkish Lira", null); public static final Currency TTD = createCurrency("TTD", "Trinidad and Tobago Dollar", null); public static final Currency TWD = createCurrency("TWD", "New Taiwan Dollar", null); public static final Currency TZS = createCurrency("TZS", "Tanzanian Shilling", null); public static final Currency UAH = createCurrency("UAH", "Ukrainian Hryvnia", null); public static final Currency UGX = createCurrency("UGX", "Ugandan Shilling", null); public static final Currency USD = createCurrency("USD", "United States Dollar", null); public static final Currency USDT = createCurrency("USDT", "Tether USD Anchor", null); public static final Currency USDE = createCurrency("USDE", "Unitary Status Dollar eCoin", null); public static final Currency UTC = createCurrency("UTC", "Ultracoin", null); public static final Currency UYU = createCurrency("UYU", "Uruguayan Peso", null); public static final Currency UZS = createCurrency("UZS", "Uzbekistan Som", null); public static final Currency VEF = createCurrency("VEF", "Venezuelan Bolívar", null); public static final Currency VEN = createCurrency("VEN", "Hub Culture's Ven", null, "XVN"); public static final Currency XVN = getInstance("XVN"); public static final Currency VIB = createCurrency("VIB", "Viberate", null); public static final Currency VND = createCurrency("VND", "Vietnamese Dong", null); public static final Currency VUV = createCurrency("VUV", "Vanuatu Vatu", null); public static final Currency WDC = createCurrency("WDC", "WorldCoin", null); public static final Currency WST = createCurrency("WST", "Samoan Tala", null); public static final Currency XAF = createCurrency("XAF", "CFA Franc BEAC", null); public static final Currency XAUR = createCurrency("XAUR", "Xaurum", null); public static final Currency XCD = createCurrency("XCD", "East Caribbean Dollar", null); public static final Currency XDR = createCurrency("XDR", "Special Drawing Rights", null); public static final Currency XLM = createCurrency("XLM", "Stellar Lumen", null); public static final Currency XMR = createCurrency("XMR", "Monero", null); public static final Currency XRB = createCurrency("XRB", "Rai Blocks", null); public static final Currency XOF = createCurrency("XOF", "CFA Franc BCEAO", null); public static final Currency XPF = createCurrency("XPF", "CFP Franc", null); public static final Currency XPM = createCurrency("XPM", "Primecoin", null); public static final Currency XRP = createCurrency("XRP", "Ripple", null); public static final Currency YBC = createCurrency("YBC", "YbCoin", null); public static final Currency YER = createCurrency("YER", "Yemeni Rial", null); public static final Currency ZAR = createCurrency("ZAR", "South African Rand", null); public static final Currency ZEC = createCurrency("ZEC", "Zcash", null); public static final Currency ZMK = createCurrency("ZMK", "Zambian Kwacha", null); public static final Currency ZRC = createCurrency("ZRC", "ziftrCOIN", null); public static final Currency ZWL = createCurrency("ZWL", "Zimbabwean Dollar", null); //Cryptos public static final Currency BNB = createCurrency("BNB", "Binance Coin", null); public static final Currency QSP = createCurrency("QSP", "Quantstamp", null); public static final Currency IOTA = createCurrency("IOTA", "Iota", null); public static final Currency YOYO = createCurrency("YOYO", "Yoyow", null); public static final Currency BTS = createCurrency("BTS", "Bitshare", null); public static final Currency ICX = createCurrency("ICX", "Icon", null); public static final Currency MCO = createCurrency("MCO", "Monaco", null); public static final Currency CND = createCurrency("CND", "Cindicator", null); public static final Currency XVG = createCurrency("XVG", "Verge", null); public static final Currency POE = createCurrency("POE", "Po.et", null); public static final Currency TRX = createCurrency("TRX", "Tron", null); public static final Currency ADA = createCurrency("ADA", "Cardano", null); public static final Currency FUN = createCurrency("FUN", "FunFair", null); public static final Currency HSR = createCurrency("HSR", "Hshare", null); public static final Currency LEND = createCurrency("LEND", "ETHLend", null); public static final Currency ELF = createCurrency("ELF", "aelf", null); public static final Currency STORJ = createCurrency("STORJ", "Storj", null); public static final Currency MOD = createCurrency("MOD", "Modum", null); /** * Gets the set of available currencies. */ public static SortedSet<Currency> getAvailableCurrencies() { return new TreeSet<>(currencies.values()); } /** * Gets the set of available currency codes. */ public static SortedSet<String> getAvailableCurrencyCodes() { return new TreeSet<>(currencies.keySet()); } private final String code; private final CurrencyAttributes attributes; /** * Returns a Currency instance for the given currency code. */ public static Currency getInstance(String currencyCode) { Currency currency = getInstanceNoCreate(currencyCode.toUpperCase()); if (currency == null) { return createCurrency(currencyCode.toUpperCase(), null, null); } else { return currency; } } /** * Returns the Currency instance for the given currency code only if one already exists. */ public static Currency getInstanceNoCreate(String currencyCode) { return currencies.get(currencyCode.toUpperCase()); } /** * Public constructor. Links to an existing currency. */ public Currency(String code) { this.code = code; this.attributes = getInstance(code).attributes; } /** * Gets the currency code originally used to acquire this object. */ public String getCurrencyCode() { return code; } public Currency getCodeCurrency(String code) { if (code.equals(this.code)) return this; Currency currency = getInstance(code); if (currency.equals(this)) return currency; if (!attributes.codes.contains(code)) throw new IllegalArgumentException("Code not listed for this currency"); return new Currency(code, attributes); } /** * Gets the equivalent object with an ISO 4217 code, or if none a code which looks ISO compatible (starts with an X), or the constructed currency * code if neither exist. */ public Currency getIso4217Currency() { if (attributes.isoCode == null) return this; // The logic for setting isoCode is in CurrencyAttributes return getCodeCurrency(attributes.isoCode); } /** * Gets the equivalent object that was created with the "commonly used" code. */ public Currency getCommonlyUsedCurrency() { return getCodeCurrency(attributes.commonCode); } /** * Gets the set of all currency codes associated with this currency. */ public Set<String> getCurrencyCodes() { return attributes.codes; } /** * Gets the unicode symbol of this currency. */ public String getSymbol() { return attributes.unicode; } /** * Gets the name that is suitable for displaying this currency. */ public String getDisplayName() { return attributes.name; } private static Currency createCurrency(String commonCode, String name, String unicode, String... alternativeCodes) { CurrencyAttributes attributes = new CurrencyAttributes(commonCode, name, unicode, alternativeCodes); Currency currency = new Currency(commonCode, attributes); for (String code : attributes.codes) { if (commonCode.equals(code)) { // common code will always be part of the currencies map currencies.put(code, currency); } else if (!currencies.containsKey(code)) { // alternative codes will never overwrite common codes currencies.put(code, new Currency(code, attributes)); } } return currency; } private Currency(String alternativeCode, CurrencyAttributes attributes) { this.code = alternativeCode; this.attributes = attributes; } @Override public String toString() { return code; } @Override public int hashCode() { return attributes.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Currency other = (Currency) obj; return attributes.equals(other.attributes); } @Override public int compareTo(Currency o) { if (attributes.equals(o.attributes)) return 0; int comparison = code.compareTo(o.code); if (comparison == 0) comparison = getDisplayName().compareTo(o.getDisplayName()); if (comparison == 0) comparison = hashCode() - o.hashCode(); return comparison; } private static class CurrencyAttributes implements Serializable { public final Set<String> codes; public final String isoCode; public final String commonCode; public final String name; public final String unicode; public CurrencyAttributes(String commonCode, String name, String unicode, String... alternativeCodes) { if (alternativeCodes.length > 0) { this.codes = new TreeSet<>(Arrays.asList(alternativeCodes)); this.codes.add(commonCode); } else { this.codes = Collections.singleton(commonCode); } String possibleIsoProposalCryptoCode = null; java.util.Currency javaCurrency = null; for (String code : this.codes) { if (javaCurrency == null) { try { javaCurrency = java.util.Currency.getInstance(code); } catch (IllegalArgumentException e) { } } if (code.startsWith("X")) { possibleIsoProposalCryptoCode = code; } } if (javaCurrency != null) { this.isoCode = javaCurrency.getCurrencyCode(); } else { this.isoCode = possibleIsoProposalCryptoCode; } this.commonCode = commonCode; if (name != null) { this.name = name; } else if (javaCurrency != null) { this.name = javaCurrency.getDisplayName(); } else { this.name = commonCode; } if (unicode != null) { this.unicode = unicode; } else if (javaCurrency != null) { this.unicode = javaCurrency.getSymbol(); } else { this.unicode = commonCode; } } @Override public int hashCode() { return commonCode.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CurrencyAttributes other = (CurrencyAttributes) obj; if (commonCode == null) { if (other.commonCode != null) return false; } else if (!commonCode.equals(other.commonCode)) return false; return true; } } }
package com.squareup.wire; /** * Superclass for protocol buffer messages. */ public abstract class Message { private static final UnknownFieldMap EMPTY_UNKNOWN_FIELD_MAP = new UnknownFieldMap(); /** Use EMPTY_UNKNOWN_FIELD_MAP until a field is added. */ transient UnknownFieldMap unknownFieldMap = EMPTY_UNKNOWN_FIELD_MAP; /** If non-zero, the hash code of this message. */ protected transient int hashCode = 0; /** If >= 0, the serialized size of this message. */ transient int cachedSerializedSize = -1; /** * Constructs a Message, initialized with any unknown field data stored in the given * {@code Builder}. */ protected Message(Builder builder) { if (builder.unknownFieldMap != EMPTY_UNKNOWN_FIELD_MAP) { unknownFieldMap = new UnknownFieldMap(builder.unknownFieldMap); } } @Override public String toString() { return Wire.toString(this); } /** * Superclass for protocol buffer message builders. */ public abstract static class Builder<T extends Message> { UnknownFieldMap unknownFieldMap = EMPTY_UNKNOWN_FIELD_MAP; /** * Constructs a Builder with no unknown field data. */ public Builder() { } /** * Constructs a Builder with unknown field data initialized to a copy of any unknown * field data in the given {@link Message}. */ public Builder(Message message) { if (message != null && !message.unknownFieldMap.isEmpty()) { this.unknownFieldMap = new UnknownFieldMap(message.unknownFieldMap); } } /** * Adds a {@code varint} value to the unknown field set with the given tag number. */ public void addVarint(int tag, long value) { ensureUnknownFieldMap().addVarint(tag, value); } /** * Adds a {@code fixed32} value to the unknown field set with the given tag number. */ public void addFixed32(int tag, int value) { ensureUnknownFieldMap().addFixed32(tag, value); } /** * Adds a {@code fixed64} value to the unknown field set with the given tag number. */ public void addFixed64(int tag, long value) { ensureUnknownFieldMap().addFixed64(tag, value); } /** * Adds a length delimited value to the unknown field set with the given tag number. */ public void addLengthDelimited(int tag, ByteString value) { ensureUnknownFieldMap().addLengthDelimited(tag, value); } /** * Adds a group value to the unknown field set with the given tag number. */ public void addGroup(int tag, ByteString value) { ensureUnknownFieldMap().addGroup(tag, value); } private UnknownFieldMap ensureUnknownFieldMap() { if (unknownFieldMap == EMPTY_UNKNOWN_FIELD_MAP) { unknownFieldMap = new UnknownFieldMap(); } return unknownFieldMap; } /** * Returns true if all required fields have been set. The default implementation returns * true. */ public boolean isInitialized() { return true; } /** * Returns an immutable {@link com.squareup.wire.Message} based on the fields that have been set * in this builder. */ public abstract T build(); } }
package org.knowm.xchange.gdax; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.marketdata.Trades.TradeSortType; import org.knowm.xchange.dto.meta.CurrencyMetaData; import org.knowm.xchange.dto.meta.CurrencyPairMetaData; import org.knowm.xchange.dto.meta.ExchangeMetaData; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.gdax.dto.account.GDAXAccount; import org.knowm.xchange.gdax.dto.marketdata.GDAXProduct; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductBook; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductBookEntry; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductStats; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker; import org.knowm.xchange.gdax.dto.marketdata.GDAXTrade; import org.knowm.xchange.gdax.dto.trade.GDAXFill; import org.knowm.xchange.gdax.dto.trade.GDAXOrder; public class GDAXAdapters { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); static { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } private GDAXAdapters() { } private static Date parseDate(String rawDate) { // System.out.println("before: " + rawDate); try { if (rawDate.length() == 20 && rawDate.endsWith("Z")) { rawDate = rawDate.substring(0, 19) + ".000Z"; } else if (rawDate.length() == 21) { rawDate = rawDate.substring(0, 20) + "000"; } else if (rawDate.length() == 22) { rawDate = rawDate.substring(0, 21) + "00"; } else if (rawDate.length() == 23) { rawDate = rawDate.substring(0, 22) + "0"; } else { rawDate = rawDate.substring(0, rawDate.length() < 23 ? rawDate.length() : 23); } // System.out.println("after: " + rawDate); // System.out.println(""); return dateFormat.parse(rawDate); } catch (ParseException e) { System.err.println("rawDate: " + rawDate); e.printStackTrace(); return null; } } public static Ticker adaptTicker(GDAXProductTicker ticker, GDAXProductStats stats, CurrencyPair currencyPair) { BigDecimal last = ticker.getPrice(); BigDecimal high = stats.getHigh(); BigDecimal low = stats.getLow(); BigDecimal buy = ticker.getBid(); BigDecimal sell = ticker.getAsk(); BigDecimal volume = ticker.getVolume(); Date date = parseDate(ticker.getTime()); return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).bid(buy).ask(sell).volume(volume).timestamp(date).build(); } public static OrderBook adaptOrderBook(GDAXProductBook book, CurrencyPair currencyPair) { List<LimitOrder> asks = toLimitOrderList(book.getAsks(), OrderType.ASK, currencyPair); List<LimitOrder> bids = toLimitOrderList(book.getBids(), OrderType.BID, currencyPair); return new OrderBook(null, asks, bids); } private static List<LimitOrder> toLimitOrderList(GDAXProductBookEntry[] levels, OrderType orderType, CurrencyPair currencyPair) { List<LimitOrder> allLevels = new ArrayList<LimitOrder>(levels.length); for (int i = 0; i < levels.length; i++) { GDAXProductBookEntry ask = levels[i]; allLevels.add(new LimitOrder(orderType, ask.getVolume(), currencyPair, "0", null, ask.getPrice())); } return allLevels; } public static Wallet adaptAccountInfo(GDAXAccount[] coinbaseExAccountInfo) { List<Balance> balances = new ArrayList<Balance>(coinbaseExAccountInfo.length); for (int i = 0; i < coinbaseExAccountInfo.length; i++) { GDAXAccount account = coinbaseExAccountInfo[i]; balances.add(new Balance(Currency.getInstance(account.getCurrency()), account.getBalance(), account.getAvailable(), account.getHold())); } return new Wallet(coinbaseExAccountInfo[0].getProfile_id(), balances); } public static OpenOrders adaptOpenOrders(GDAXOrder[] coinbaseExOpenOrders) { List<LimitOrder> orders = new ArrayList<LimitOrder>(coinbaseExOpenOrders.length); for (int i = 0; i < coinbaseExOpenOrders.length; i++) { GDAXOrder order = coinbaseExOpenOrders[i]; OrderType type = order.getSide().equals("buy") ? OrderType.BID : OrderType.ASK; CurrencyPair currencyPair = new CurrencyPair(order.getProductId().replace("-", "/")); Date createdAt = parseDate(order.getCreatedAt()); orders.add(new LimitOrder(type, order.getSize(), currencyPair, order.getId(), createdAt, order.getPrice())); } return new OpenOrders(orders); } public static UserTrades adaptTradeHistory(GDAXFill[] coinbaseExFills) { List<UserTrade> trades = new ArrayList<UserTrade>(coinbaseExFills.length); for (int i = 0; i < coinbaseExFills.length; i++) { GDAXFill fill = coinbaseExFills[i]; OrderType type = fill.getSide().equals("sell") ? OrderType.ASK : OrderType.BID; CurrencyPair currencyPair = new CurrencyPair(fill.getProductId().replace("-", "/")); // ToDo add fee amount UserTrade t = new UserTrade(type, fill.getSize(), currencyPair, fill.getPrice(), parseDate(fill.getCreatedAt()), String.valueOf(fill.getTradeId()), fill.getOrderId(), null, (Currency) null); trades.add(t); } return new UserTrades(trades, TradeSortType.SortByID); } public static Trades adaptTrades(GDAXTrade[] coinbaseExTrades, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<Trade>(coinbaseExTrades.length); for (int i = 0; i < coinbaseExTrades.length; i++) { GDAXTrade trade = coinbaseExTrades[i]; OrderType type = trade.getSide().equals("sell") ? OrderType.ASK : OrderType.BID; Trade t = new Trade(type, trade.getSize(), currencyPair, trade.getPrice(), parseDate(trade.getTimestamp()), String.valueOf(trade.getTradeId())); trades.add(t); } return new Trades(trades, coinbaseExTrades[0].getTradeId(), TradeSortType.SortByID); } public static CurrencyPair adaptCurrencyPair(GDAXProduct product) { return new CurrencyPair(product.getBaseCurrency(), product.getTargetCurrency()); } public static ExchangeMetaData adaptToExchangeMetaData(ExchangeMetaData exchangeMetaData, List<GDAXProduct> products) { Map<CurrencyPair, CurrencyPairMetaData> currencyPairs = new HashMap<>(); Map<Currency, CurrencyMetaData> currencies = new HashMap<>(); for (GDAXProduct product : products) { BigDecimal minSize = product.getBaseMinSize().setScale(product.getQuoteIncrement().scale(), BigDecimal.ROUND_UNNECESSARY); BigDecimal maxSize = product.getBaseMaxSize().setScale(product.getQuoteIncrement().scale(), BigDecimal.ROUND_UNNECESSARY); CurrencyPairMetaData cpmd = new CurrencyPairMetaData(null, minSize, maxSize, 8); // TODO 8 is a wild guess CurrencyPair pair = adaptCurrencyPair(product); currencyPairs.put(pair, cpmd); currencies.put(pair.base, null); currencies.put(pair.counter, null); } return new ExchangeMetaData(currencyPairs, currencies, exchangeMetaData.getPublicRateLimits(), exchangeMetaData.getPrivateRateLimits(), true); } }
package roart.component; import java.util.List; import java.util.Map; import roart.config.ConfigConstants; import roart.config.MyMyConfig; import roart.model.IncDecItem; import roart.model.MemoryItem; import roart.service.ControlService; public abstract class Component { public abstract void enable(MyMyConfig conf); public abstract void disable(MyMyConfig conf); public static void disabler(MyMyConfig conf) { conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE); conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE); conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.FALSE); } public abstract void handle(ControlService srv, MyMyConfig conf, Map<String, Map<String, Object>> maps, List<Integer> positions, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap, Map<Object[], List<MemoryItem>> okListMap, Map<String, String> nameMap); public abstract void improve(MyMyConfig conf, Map<String, Map<String, Object>> maps, List<Integer> positions, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap, Map<Object[], List<MemoryItem>> okListMap, Map<String, String> nameMap); }
package com.worth.ifs; import com.worth.ifs.application.builder.QuestionBuilder; import com.worth.ifs.application.builder.SectionBuilder; import com.worth.ifs.application.constant.ApplicationStatusConstants; import com.worth.ifs.application.domain.Application; import com.worth.ifs.application.domain.*; import com.worth.ifs.application.finance.service.CostService; import com.worth.ifs.application.finance.service.FinanceService; import com.worth.ifs.application.model.UserApplicationRole; import com.worth.ifs.application.model.UserRole; import com.worth.ifs.application.resource.ApplicationResource; import com.worth.ifs.application.resource.ApplicationStatusResource; import com.worth.ifs.application.service.*; import com.worth.ifs.assessment.domain.Assessment; import com.worth.ifs.assessment.domain.AssessmentStates; import com.worth.ifs.assessment.service.AssessmentRestService; import com.worth.ifs.commons.security.TokenAuthenticationService; import com.worth.ifs.commons.security.UserAuthentication; import com.worth.ifs.commons.security.UserAuthenticationService; import com.worth.ifs.competition.domain.Competition; import com.worth.ifs.competition.service.CompetitionsRestService; import com.worth.ifs.exception.ErrorController; import com.worth.ifs.finance.resource.ApplicationFinanceResource; import com.worth.ifs.finance.service.ApplicationFinanceRestService; import com.worth.ifs.finance.service.CostRestService; import com.worth.ifs.form.domain.FormInput; import com.worth.ifs.form.domain.FormInputResponse; import com.worth.ifs.form.service.FormInputResponseService; import com.worth.ifs.form.service.FormInputService; import com.worth.ifs.user.domain.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver; import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod; import org.springframework.web.servlet.view.InternalResourceViewResolver; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import static com.worth.ifs.BuilderAmendFunctions.*; import static com.worth.ifs.application.builder.ApplicationBuilder.newApplication; import static com.worth.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static com.worth.ifs.application.builder.ApplicationStatusBuilder.newApplicationStatus; import static com.worth.ifs.application.builder.ApplicationStatusResourceBuilder.newApplicationStatusResource; import static com.worth.ifs.application.builder.QuestionBuilder.newQuestion; import static com.worth.ifs.application.builder.SectionBuilder.newSection; import static com.worth.ifs.commons.rest.RestResult.restSuccess; import static com.worth.ifs.competition.builder.CompetitionBuilder.newCompetition; import static com.worth.ifs.form.builder.FormInputBuilder.newFormInput; import static com.worth.ifs.form.builder.FormInputResponseBuilder.newFormInputResponse; import static com.worth.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.when; public class BaseUnitTest { public MockMvc mockMvc; public User loggedInUser; public User assessor; public User applicant; public UserAuthentication loggedInUserAuthentication; protected final Log log = LogFactory.getLog(getClass()); @Mock public ApplicationFinanceRestService applicationFinanceRestService; @Mock public UserAuthenticationService userAuthenticationService; @Mock public ResponseService responseService; @Mock public FormInputResponseService formInputResponseService; @Mock public FormInputService formInputService; @Mock public ApplicationService applicationService; @Mock public ApplicationStatusRestService applicationStatusService; @Mock public CompetitionsRestService competitionRestService; @Mock public AssessmentRestService assessmentRestService; @Mock public ProcessRoleService processRoleService; @Mock public UserService userService; @Mock public FinanceService financeService; @Mock public CostService costService; @Mock public CostRestService costRestService; @Mock public ApplicationRestService applicationRestService; @Mock public QuestionService questionService; @Mock public OrganisationService organisationService; @Mock public SectionService sectionService; @Mock public CompetitionService competitionService; @Mock public TokenAuthenticationService tokenAuthenticationService; public List<ApplicationResource> applications; public List<Section> sections; public Map<Long, Question> questions; public Map<Long, FormInputResponse> formInputsToFormInputResponses; public List<Competition> competitions; public Competition competition; public List<User> users; public List<Organisation> organisations; TreeSet<Organisation> organisationSet; public List<Assessment> assessments; public List<ProcessRole> assessorProcessRoles; public List<Assessment> submittedAssessments; public ApplicationFinanceResource applicationFinanceResource; public ApplicationStatusResource submittedApplicationStatus; public ApplicationStatusResource createdApplicationStatus; public ApplicationStatusResource approvedApplicationStatus; public ApplicationStatusResource rejectedApplicationStatus; public List<ProcessRole> processRoles; private Random randomGenerator; public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/resources"); viewResolver.setSuffix(".html"); return viewResolver; } public <T> T attributeFromMvcResultModel(MvcResult result, String key){ return (T)result.getModelAndView().getModel().entrySet().stream() .filter(entry -> entry.getKey().equals(key)) .map(entry -> entry.getValue()) .findFirst().orElse(null); } public void setup(){ loggedInUser = new User(1L, "Nico Bijl", "email@email.nl", "test", "tokenABC", "image", new ArrayList()); applicant = loggedInUser; User user2 = new User(2L, "Brent de Kok", "email@email.nl", "test", "tokenBCD", "image", new ArrayList()); assessor = new User(3L, "Assessor", "email@assessor.nl", "test", "tokenDEF", "image", new ArrayList<>()); users = asList(loggedInUser, user2); loggedInUserAuthentication = new UserAuthentication(loggedInUser); applications = new ArrayList<>(); sections = new ArrayList<>(); questions = new HashMap<>(); organisations = new ArrayList<>(); randomGenerator = new Random(); } public void loginDefaultUser(){ when(userAuthenticationService.getAuthentication(any(HttpServletRequest.class))).thenReturn(loggedInUserAuthentication); when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(loggedInUser); } public void loginUser(User user){ UserAuthentication userAuthentication = new UserAuthentication(user); when(userAuthenticationService.getAuthentication(any(HttpServletRequest.class))).thenReturn(userAuthentication); when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(user); } public void setupCompetition(){ competition = newCompetition().with(id(1L)).with(name("Competition x")).with(description("Description afds")). withStartDate(LocalDateTime.now().minusDays(2)).withEndDate(LocalDateTime.now().plusDays(5)). build(); QuestionBuilder questionBuilder = newQuestion().with(competition(competition)); SectionBuilder sectionBuilder = newSection().with(competition(competition)); Question q01 = questionBuilder.with(id(1L)).with(name("Application details")). withFormInputs(newFormInput().with(incrementingIds(1)).build(3)). build(); Section section1 = sectionBuilder. with(id(1L)). with(name("Application details")). withQuestions(singletonList(q01)). build(); Question q10 = questionBuilder.with(id(10L)).with(name("How does your project align with the scope of this competition?")). build(); Section section2 = sectionBuilder. with(id(2L)). with(name("Scope (Gateway question)")). withQuestions(singletonList(q10)). build(); Question q20 = questionBuilder.with(id(20L)).with(name("1. What is the business opportunity that this project addresses?")). build(); Question q21 = questionBuilder.with(id(21L)).with(name("2. What is the size of the market opportunity that this project might open up?")).build(); Question q22 = questionBuilder.with(id(22L)).with(name("3. How will the results of the project be exploited and disseminated?")).build(); Question q23 = questionBuilder.with(id(23L)).with(name("4. What economic, social and environmental benefits is the project expected to deliver?")).build(); Section section3 = sectionBuilder. with(id(3L)). with(name("Business proposition (Q1 - Q4)")). withQuestions(asList(q20, q21, q22, q23)). build(); Question q30 = questionBuilder.with(id(30L)).with(name("5. What technical approach will be adopted and how will the project be managed?")).build(); Question q31 = questionBuilder.with(id(31L)).with(name("6. What is innovative about this project?")).build(); Question q32 = questionBuilder.with(id(32L)).with(name("7. What are the risks (technical, commercial and environmental) to project success? What is the project's risk management strategy?")).build(); Question q33 = questionBuilder.with(id(33L)).with(name("8. Does the project team have the right skills and experience and access to facilities to deliver the identified benefits?")).build(); Section section4 = sectionBuilder. with(id(4L)). with(name("Project approach (Q5 - Q8)")). withQuestions(asList(q30, q31, q32, q33)). build(); Section section5 = sectionBuilder.with(id(5L)).with(name("Funding (Q9 - Q10)")).build(); Section section6 = sectionBuilder.with(id(6L)).with(name("Finances")).build(); sections = asList(section1, section2, section3, section4, section5, section6); ArrayList<Question> questionList = new ArrayList<>(); for (Section section : sections) { List<Question> sectionQuestions = section.getQuestions(); if(sectionQuestions != null){ Map<Long, Question> questionsMap = sectionQuestions.stream().collect(toMap(Question::getId, identity())); questionList.addAll(sectionQuestions); questions.putAll(questionsMap); } } competitions = singletonList(competition); when(questionService.findByCompetition(competition.getId())).thenReturn(questionList); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(competitionRestService.getAll()).thenReturn(restSuccess(competitions)); when(competitionService.getById(any(Long.class))).thenReturn(competition); } public void setupUserRoles() { Role assessorRole = new Role(3L, UserRole.ASSESSOR.getRoleName(), null); Role applicantRole = new Role(4L, UserRole.APPLICANT.getRoleName(), null); loggedInUser.setRoles(singletonList(applicantRole)); assessor.setRoles(singletonList(assessorRole)); } public void setupApplicationWithRoles(){ createdApplicationStatus = newApplicationStatusResource().with(status -> status.setId(ApplicationStatusConstants.CREATED.getId())).withName(ApplicationStatusConstants.CREATED.getName()).build(); submittedApplicationStatus = newApplicationStatusResource().with(status -> status.setId(ApplicationStatusConstants.SUBMITTED.getId())).withName(ApplicationStatusConstants.SUBMITTED.getName()).build(); approvedApplicationStatus = newApplicationStatusResource().with(status -> status.setId(ApplicationStatusConstants.APPROVED.getId())).withName(ApplicationStatusConstants.APPROVED.getName()).build(); rejectedApplicationStatus = newApplicationStatusResource().with(status -> status.setId(ApplicationStatusConstants.REJECTED.getId())).withName(ApplicationStatusConstants.REJECTED.getName()).build(); ApplicationStatus createdApplicationStatus2 = newApplicationStatus().with(status -> status.setId(ApplicationStatusConstants.CREATED.getId())).withName(ApplicationStatusConstants.CREATED.getName()).build(); ApplicationStatus submittedApplicationStatus2 = newApplicationStatus().with(status -> status.setId(ApplicationStatusConstants.SUBMITTED.getId())).withName(ApplicationStatusConstants.SUBMITTED.getName()).build(); ApplicationStatus approvedApplicationStatus2 = newApplicationStatus().with(status -> status.setId(ApplicationStatusConstants.APPROVED.getId())).withName(ApplicationStatusConstants.APPROVED.getName()).build(); ApplicationStatus rejectedApplicationStatus2 = newApplicationStatus().with(status -> status.setId(ApplicationStatusConstants.REJECTED.getId())).withName(ApplicationStatusConstants.REJECTED.getName()).build(); // Build the backing applications. List<ApplicationResource> applicationResources = asList( newApplicationResource().with(id(1L)).with(name("Rovel Additive Manufacturing Process")).withStartDate(LocalDate.now().plusMonths(3)).withApplicationStatus(createdApplicationStatus).build(), newApplicationResource().with(id(2L)).with(name("Providing sustainable childcare")).withStartDate(LocalDate.now().plusMonths(4)).withApplicationStatus(submittedApplicationStatus).build(), newApplicationResource().with(id(3L)).with(name("Mobile Phone Data for Logistics Analytics")).withStartDate(LocalDate.now().plusMonths(5)).withApplicationStatus(approvedApplicationStatus).build(), newApplicationResource().with(id(4L)).with(name("Using natural gas to heat homes")).withStartDate(LocalDate.now().plusMonths(6)).withApplicationStatus(rejectedApplicationStatus).build() ); List<Application> applicationList = asList( newApplication().with(id(1L)).with(name("Rovel Additive Manufacturing Process")).withStartDate(LocalDate.now().plusMonths(3)).withApplicationStatus(createdApplicationStatus2).build(), newApplication().with(id(2L)).with(name("Providing sustainable childcare")).withStartDate(LocalDate.now().plusMonths(4)).withApplicationStatus(submittedApplicationStatus2).build(), newApplication().with(id(3L)).with(name("Mobile Phone Data for Logistics Analytics")).withStartDate(LocalDate.now().plusMonths(5)).withApplicationStatus(approvedApplicationStatus2).build(), newApplication().with(id(4L)).with(name("Using natural gas to heat homes")).withStartDate(LocalDate.now().plusMonths(6)).withApplicationStatus(rejectedApplicationStatus2).build() ); Map<Long, ApplicationResource> idsToApplicationResources = applicationResources.stream().collect(toMap(a -> a.getId(), a -> a)); Role role1 = new Role(1L, UserApplicationRole.LEAD_APPLICANT.getRoleName(), null); Role role2 = new Role(2L, UserApplicationRole.COLLABORATOR.getRoleName(), null); Role assessorRole = new Role(3L, UserRole.ASSESSOR.getRoleName(), null); Organisation organisation1 = new Organisation(1L, "Empire Ltd"); organisation1.setOrganisationType(new OrganisationType("Business", null)); Organisation organisation2 = new Organisation(2L, "Ludlow"); organisation2.setOrganisationType(new OrganisationType("Research", null)); organisations = asList(organisation1, organisation2); Comparator<Organisation> compareById = Comparator.comparingLong(Organisation::getId); organisationSet = new TreeSet<>(compareById); organisationSet.addAll(organisations); ProcessRole processRole1 = newProcessRole().with(id(1L)).withApplication(applicationList.get(0)).withUser(loggedInUser).withRole(role1).withOrganisation(organisation1).build(); ProcessRole processRole2 = newProcessRole().with(id(2L)).withApplication(applicationList.get(0)).withUser(loggedInUser).withRole(role1).withOrganisation(organisation1).build(); ProcessRole processRole3 = newProcessRole().with(id(3L)).withApplication(applicationList.get(2)).withUser(loggedInUser).withRole(role1).withOrganisation(organisation1).build(); ProcessRole processRole4 = newProcessRole().with(id(4L)).withApplication(applicationList.get(3)).withUser(loggedInUser).withRole(role1).withOrganisation(organisation1).build(); ProcessRole processRole5 = newProcessRole().with(id(5L)).withApplication(applicationList.get(0)).withUser(loggedInUser).withRole(role2).withOrganisation(organisation2).build(); ProcessRole processRole6 = newProcessRole().with(id(6L)).withApplication(applicationList.get(1)).withUser(assessor).withRole(assessorRole).withOrganisation(organisation1).build(); ProcessRole processRole7 = newProcessRole().with(id(7L)).withApplication(applicationList.get(2)).withUser(assessor).withRole(assessorRole).withOrganisation(organisation1).build(); ProcessRole processRole8 = newProcessRole().with(id(8L)).withApplication(applicationList.get(0)).withUser(assessor).withRole(assessorRole).withOrganisation(organisation1).build(); ProcessRole processRole9 = newProcessRole().with(id(9L)).withApplication(applicationList.get(3)).withUser(assessor).withRole(assessorRole).withOrganisation(organisation1).build(); assessorProcessRoles = asList(processRole6, processRole7, processRole8, processRole9); processRoles = asList(processRole1,processRole2, processRole3, processRole4, processRole5, processRole6, processRole7, processRole8, processRole9); organisation1.setProcessRoles(asList(processRole1, processRole2, processRole3, processRole4, processRole7, processRole8, processRole8)); organisation2.setProcessRoles(singletonList(processRole5)); applicationList.forEach(competition::addApplication); applicationList.get(0).setCompetition(competition); applicationList.get(0).setProcessRoles(asList(processRole1, processRole5)); applicationList.get(1).setCompetition(competition); applicationList.get(1).setProcessRoles(singletonList(processRole2)); applicationList.get(2).setCompetition(competition); applicationList.get(2).setProcessRoles(asList(processRole3, processRole7, processRole8)); applicationList.get(3).setCompetition(competition); applicationList.get(3).setProcessRoles(singletonList(processRole4)); applicationResources.get(0).setCompetition(competition.getId()); applicationResources.get(0).setProcessRoles(asList(processRole1.getId(), processRole5.getId())); applicationResources.get(1).setCompetition(competition.getId()); applicationResources.get(1).setProcessRoles(singletonList(processRole2.getId())); applicationResources.get(2).setCompetition(competition.getId()); applicationResources.get(2).setProcessRoles(asList(processRole3.getId(), processRole7.getId(), processRole8.getId())); applicationResources.get(3).setCompetition(competition.getId()); applicationResources.get(3).setProcessRoles(singletonList(processRole4.getId())); loggedInUser.addUserApplicationRole(processRole1, processRole2, processRole3, processRole4); users.get(0).addUserApplicationRole(processRole5); applications = applicationResources; when(sectionService.getParentSections(competition.getSections())).thenReturn(sections); when(sectionService.getCompleted(applicationList.get(0).getId(), organisation1.getId())).thenReturn(asList(1L, 2L)); when(sectionService.getInCompleted(applicationList.get(0).getId())).thenReturn(asList(3L, 4L)); when(processRoleService.findProcessRole(applicant.getId(), applicationList.get(0).getId())).thenReturn(processRole1); when(processRoleService.findProcessRole(applicant.getId(), applicationList.get(1).getId())).thenReturn(processRole2); when(processRoleService.findProcessRole(applicant.getId(), applicationList.get(2).getId())).thenReturn(processRole3); when(processRoleService.findProcessRole(applicant.getId(), applicationList.get(3).getId())).thenReturn(processRole4); when(processRoleService.findProcessRole(users.get(0).getId(), applicationList.get(0).getId())).thenReturn(processRole5); when(processRoleService.findProcessRole(assessor.getId(), applicationList.get(1).getId())).thenReturn(processRole6); when(processRoleService.findProcessRole(assessor.getId(), applicationList.get(2).getId())).thenReturn(processRole7); when(processRoleService.findProcessRole(assessor.getId(), applicationList.get(0).getId())).thenReturn(processRole8); when(processRoleService.findProcessRole(assessor.getId(), applicationList.get(3).getId())).thenReturn(processRole9); Map<Long, Set<Long>> completedMap = new HashMap<>(); completedMap.put(organisation1.getId(), new TreeSet<>()); completedMap.put(organisation2.getId(), new TreeSet<>()); when(sectionService.getCompletedSectionsByOrganisation(applicationList.get(0).getId())).thenReturn(completedMap); when(sectionService.getCompletedSectionsByOrganisation(applicationList.get(1).getId())).thenReturn(completedMap); when(sectionService.getCompletedSectionsByOrganisation(applicationList.get(2).getId())).thenReturn(completedMap); processRoles.forEach(pr -> when(applicationService.findByProcessRoleId(pr.getId())).thenReturn(restSuccess(idsToApplicationResources.get(pr.getApplication().getId())))); when(applicationRestService.getApplicationsByUserId(loggedInUser.getId())).thenReturn(applications); when(applicationService.getById(applications.get(0).getId())).thenReturn(applications.get(0)); when(applicationService.getById(applications.get(1).getId())).thenReturn(applications.get(1)); when(applicationService.getById(applications.get(2).getId())).thenReturn(applications.get(2)); when(applicationService.getById(applications.get(3).getId())).thenReturn(applications.get(3)); when(organisationService.getOrganisationById(organisationSet.first().getId())).thenReturn(organisationSet.first()); when(organisationService.getUserOrganisation(applications.get(0), loggedInUser.getId())).thenReturn(Optional.of(organisation1)); when(organisationService.getApplicationLeadOrganisation(applications.get(0))).thenReturn(Optional.of(organisation1)); when(organisationService.getApplicationOrganisations(applications.get(0))).thenReturn(organisationSet); when(organisationService.getApplicationOrganisations(applications.get(1))).thenReturn(organisationSet); when(organisationService.getApplicationOrganisations(applications.get(2))).thenReturn(organisationSet); when(organisationService.getApplicationOrganisations(applications.get(3))).thenReturn(organisationSet); when(userService.isLeadApplicant(loggedInUser.getId(),applications.get(0))).thenReturn(true); when(userService.getLeadApplicantProcessRoleOrNull(applications.get(0))).thenReturn(processRole1); when(userService.getLeadApplicantProcessRoleOrNull(applications.get(1))).thenReturn(processRole2); when(userService.getLeadApplicantProcessRoleOrNull(applications.get(2))).thenReturn(processRole3); when(userService.getLeadApplicantProcessRoleOrNull(applications.get(3))).thenReturn(processRole4); when(organisationService.getApplicationLeadOrganisation(applications.get(0))).thenReturn(Optional.of(organisation1)); when(organisationService.getApplicationLeadOrganisation(applications.get(1))).thenReturn(Optional.of(organisation1)); when(organisationService.getApplicationLeadOrganisation(applications.get(2))).thenReturn(Optional.of(organisation1)); processRoles.forEach(processRole -> when(processRoleService.getById(processRole.getId())).thenReturn(processRole)); } public void setupApplicationResponses(){ ApplicationResource application = applications.get(0); Application app = newApplication().build(); ProcessRole userApplicationRole = loggedInUser.getProcessRoles().get(0); Response response = new Response(1L, LocalDateTime.now(), userApplicationRole, questions.get(20L), app); Response response2 = new Response(2L, LocalDateTime.now(), userApplicationRole, questions.get(21L), app); List<Response> responses = asList(response, response2); userApplicationRole.setResponses(responses); questions.get(20L).setResponses(singletonList(response)); questions.get(21L).setResponses(singletonList(response2)); when(responseService.getByApplication(application.getId())).thenReturn(responses); ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class); when(formInputService.getOne(anyLong())).thenAnswer(invocation -> { Object[] args = invocation.getArguments(); return newFormInput().with(id((Long) args[0])).build(); }); List<FormInput> formInputs = questions.get(01L).getFormInputs(); List<FormInputResponse> formInputResponses = newFormInputResponse().withFormInputs(formInputs). with(idBasedValues("Value ")).build(formInputs.size()); when(formInputResponseService.getByApplication(application.getId())).thenReturn(formInputResponses); formInputResponses.stream().map(FormInputResponse::getFormInput).map(FormInput::getId).forEach(log::debug); formInputsToFormInputResponses = formInputResponses.stream().collect(toMap(formInputResponse -> formInputResponse.getFormInput().getId(), identity())); when(formInputResponseService.mapFormInputResponsesToFormInput(formInputResponses)).thenReturn(formInputsToFormInputResponses); } public void setupFinances() { ApplicationResource application = applications.get(0); applicationFinanceResource = new ApplicationFinanceResource(1L, application.getId(), organisations.get(0).getId(), OrganisationSize.LARGE); when(financeService.getApplicationFinanceDetails(application.getId(), loggedInUser.getId())).thenReturn(applicationFinanceResource); when(financeService.getApplicationFinance(loggedInUser.getId(), application.getId())).thenReturn(applicationFinanceResource); when(applicationFinanceRestService.getResearchParticipationPercentage(anyLong())).thenReturn(0.0); } public void setupAssessment(){ Role assessorRole = new Role(3L, UserRole.ASSESSOR.getRoleName(), null); Organisation organisation1 = organisations.get(0); Assessment assessment1 = new Assessment(assessorProcessRoles.get(2)); assessment1.setId(1L); Assessment assessment2 = new Assessment(assessorProcessRoles.get(0)); assessment2.setId(2L); Assessment assessment3 = new Assessment(assessorProcessRoles.get(1)); assessment3.setId(3L); Assessment assessment4 = new Assessment(assessorProcessRoles.get(3)); assessment4.setId(4L); when(assessmentRestService.getTotalAssignedByAssessorAndCompetition(assessor.getId(), competition.getId())).thenReturn(3); when(assessmentRestService.getTotalSubmittedByAssessorAndCompetition(assessor.getId(), competition.getId())).thenReturn(1); assessment1.setProcessStatus(AssessmentStates.REJECTED.getState()); assessment2.setProcessStatus(AssessmentStates.PENDING.getState()); assessment3.setProcessStatus(AssessmentStates.SUBMITTED.getState()); assessment4.setProcessStatus(AssessmentStates.ASSESSED.getState()); submittedAssessments = singletonList(assessment3); assessments = asList(assessment1, assessment2, assessment3, assessment4); when(assessmentRestService.getAllByAssessorAndCompetition(assessor.getId(), competition.getId())).thenReturn(assessments); when(assessmentRestService.getOneByProcessRole(assessment1.getProcessRole().getId())).thenReturn(assessment1); when(assessmentRestService.getOneByProcessRole(assessment1.getProcessRole().getId())).thenReturn(assessment2); when(assessmentRestService.getOneByProcessRole(assessment1.getProcessRole().getId())).thenReturn(assessment3); when(assessmentRestService.getOneByProcessRole(assessment1.getProcessRole().getId())).thenReturn(assessment4); when(organisationService.getUserOrganisation(applications.get(0), assessor.getId())).thenReturn(Optional.of(organisations.get(0))); when(organisationService.getUserOrganisation(applications.get(1), assessor.getId())).thenReturn(Optional.of(organisations.get(0))); when(organisationService.getUserOrganisation(applications.get(2), assessor.getId())).thenReturn(Optional.of(organisations.get(0))); } public ExceptionHandlerExceptionResolver createExceptionResolver() { ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() { protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) { Method method = new ExceptionHandlerMethodResolver(ErrorController.class).resolveMethod(exception); return new ServletInvocableHandlerMethod(new ErrorController(), method); } }; exceptionResolver.afterPropertiesSet(); return exceptionResolver; } }
package procesador; import java.io.File; import java.io.IOException; public class Procesador { public static GestorErrores errores; public static GestorTS tablaSimbolos; public static AnalizadorLexico lexico; public static void main(String[] args) { //Comprobaciones del archivo if(args.length < 1){ System.err.println("ERROR - El programa tiene que recibir como argumento" + " la ruta del archivo con el codigo fuente a procesar."); System.exit(1); } File source = new File(args[0]); if(!source.exists() || !source.canRead()){ System.err.println("No se ha podido leer el archivo: "+args[0]); System.exit(2); } //Creamos el analizador lexico lexico = new AnalizadorLexico(source); //Creamos la tabla de simbolos tablaSimbolos = new GestorTS(); //Creamos el gestor de errores errores = new GestorErrores(lexico); new AnalizadorSS(lexico); AnalizadorAsc analizador = new AnalizadorAsc(lexico); /* try { analizador.parse(); } catch (IOException e) { e.printStackTrace(); }*/ } public static GestorErrores getGestorErrores(){ return errores; } public static GestorTS getGestorTS(){ return tablaSimbolos; } }
package org.xins.common.service; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.util.NoSuchElementException; import java.util.zip.CRC32; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.xins.common.Log; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.ProgrammingError; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.HexConverter; /** * Descriptor for a single target service. A target descriptor defines a URL * that identifies the location of the service. Also, it may define 3 kinds of * time-outs: * * <dl> * <dt><em>total time-out</em> ({@link #getTotalTimeOut()})</dt> * <dd>the maximum duration of a call, including connection time, time used * to send the request, time used to receive the response, etc.</dd> * * <dt><em>connection time-out</em> ({@link #getConnectionTimeOut()})</dt> * <dd>the maximum time for attempting to establish a connection.</dd> * * <dt><em>socket time-out</em> ({@link #getSocketTimeOut()})</dt> * <dd>the maximum time for attempting to receive data on a socket.</dd> * </dl> * * @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 final class TargetDescriptor extends Descriptor { // Class fields /** * The fully-qualified name of this class. */ private static final String CLASSNAME = TargetDescriptor.class.getName(); /** * The number of instances of this class. Initially 0. */ private static int INSTANCE_COUNT; /** * The fully-qualified name of the inner class <code>Iterator</code>. */ private static final String ITERATOR_CLASSNAME = TargetDescriptor.Iterator.class.getName(); /** * The default time-out when no time-out is specified. */ private static final int DEFAULT_TIMEOUT = 5000; /** * Perl 5 pattern compiler. */ private static final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler(); /** * Pattern matcher. */ private static final Perl5Matcher PATTERN_MATCHER = new Perl5Matcher(); /** * The pattern for a URL, as a character string. */ private static final String PATTERN_STRING = "[a-zA-Z][a-zA-Z0-9]*:\\/\\/[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*(:[1-9][0-9]*)?(\\/([a-zA-Z0-9\\-_~\\.]*))*"; /** * The pattern for a URL. */ private static final Pattern PATTERN; // Class functions /** * Initializes this class. This function compiles {@link #PATTERN_STRING} * to a {@link Pattern} and then stores that in {@link #PATTERN}. */ static { try { PATTERN = PATTERN_COMPILER.compile(PATTERN_STRING, Perl5Compiler.READ_ONLY_MASK); } catch (MalformedPatternException mpe) { String message = "The pattern \"" + PATTERN_STRING + "\" is malformed."; Log.log_1050(CLASSNAME, "<clinit>()", message); throw new ProgrammingError(message, mpe); } } private static int computeCRC32(String s) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("s", s); // Compute the CRC-32 checksum CRC32 checksum = new CRC32(); byte[] bytes; final String ENCODING = "US-ASCII"; try { bytes = s.getBytes(ENCODING); } catch (UnsupportedEncodingException exception) { String message = "Encoding \"" + ENCODING + "\" is not supported by String.getBytes(String)."; Log.log_1050(CLASSNAME, "computeCRC32(String)", message); throw new ProgrammingError(message, exception); } checksum.update(bytes, 0, bytes.length); return (int) (checksum.getValue() & 0x00000000ffffffffL); } // Constructors public TargetDescriptor(String url) throws IllegalArgumentException, MalformedURLException { this(url, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT); } public TargetDescriptor(String url, int timeOut) throws IllegalArgumentException, MalformedURLException { this(url, timeOut, timeOut, timeOut); } public TargetDescriptor(String url, int timeOut, int connectionTimeOut) throws IllegalArgumentException, MalformedURLException { this(url, timeOut, connectionTimeOut, timeOut); } public TargetDescriptor(String url, int timeOut, int connectionTimeOut, int socketTimeOut) throws IllegalArgumentException, MalformedURLException { // Determine instance number first _instanceNumber = ++INSTANCE_COUNT; // TRACE: Enter constructor Log.log_1000(CLASSNAME, "#" + _instanceNumber); // Check preconditions MandatoryArgumentChecker.check("url", url); if (! PATTERN_MATCHER.matches(url, PATTERN)) { throw new MalformedURLException(url); } // Convert negative total time-out to 0 timeOut = (timeOut > 0) ? timeOut : 0; // If connection time-out or socket time-out is not set, then set it to // the total time-out connectionTimeOut = (connectionTimeOut > 0) ? connectionTimeOut : timeOut; socketTimeOut = (socketTimeOut > 0) ? socketTimeOut : timeOut; // If either connection or socket time-out is greater than total // time-out, then limit it to the total time-out connectionTimeOut = (connectionTimeOut < timeOut) ? connectionTimeOut : timeOut; socketTimeOut = (socketTimeOut < timeOut) ? socketTimeOut : timeOut; // Set fields _url = url; _timeOut = timeOut; _connectionTimeOut = connectionTimeOut; _socketTimeOut = socketTimeOut; _crc = computeCRC32(url); // Convert to a string // TODO: Lazily initialize _asString FastStringBuffer buffer = new FastStringBuffer(233, "TargetDescriptor buffer.append(_instanceNumber); buffer.append(" [url=\""); buffer.append(url); buffer.append("\"; crc=\""); buffer.append(HexConverter.toHexString(_crc)); buffer.append("\"; total time-out is "); if (_timeOut < 1) { buffer.append("disabled; connection time-out is "); } else { buffer.append(_timeOut); buffer.append(" ms; connection time-out is "); } if (_connectionTimeOut < 1) { buffer.append("disabled; socket time-out is "); } else { buffer.append(_connectionTimeOut); buffer.append(" ms; socket time-out is "); } if (_socketTimeOut < 1) { buffer.append("disabled]"); } else { buffer.append(_socketTimeOut); buffer.append(" ms]"); } _asString = buffer.toString(); // TRACE: Leave constructor Log.log_1002(CLASSNAME, "#" + _instanceNumber); } // Fields /** * The 1-based sequence number of this instance. Since this number is * 1-based, the first instance of this class will have instance number 1 * assigned to it. */ private final int _instanceNumber; /** * A textual representation of this object. Cannot be <code>null</code>. * The value of this field is returned by {@link #toString()}. */ private final String _asString; /** * The URL for the service. Cannot be <code>null</code>. */ private final String _url; /** * The total time-out for the service. Is set to a 0 if no total time-out * should be applied. */ private final int _timeOut; /** * The connection time-out for the service. Always greater than 0 and * smaller than or equal to the total time-out. */ private final int _connectionTimeOut; /** * The socket time-out for the service. Always greater than 0 and smaller * than or equal to the total time-out. */ private final int _socketTimeOut; /** * The CRC-32 checksum for the URL. See {@link #_url}. */ private final int _crc; // Methods /** * Checks if this descriptor denotes a group of descriptors. * * @return * <code>false</code>, since this descriptor does not denote a group. */ public boolean isGroup() { return false; } /** * Returns the URL for the service. * * @return * the URL for the service, not <code>null</code>. */ public String getURL() { return _url; } /** * Returns the total time-out for a call to the service. The value 0 * is returned if there is no total time-out. * * @return * the total time-out for the service, as a positive number, in * milli-seconds, or 0 if there is no total time-out. */ public int getTotalTimeOut() { return _timeOut; } /** * Returns the connection time-out for a call to the service. * * @return * the connection time-out for the service; always greater than 0 and * smaller than or equal to the total time-out. */ public int getConnectionTimeOut() { return _connectionTimeOut; } /** * Returns the socket time-out for a call to the service. * * @return * the socket time-out for the service; always greater than 0 and * smaller than or equal to the total time-out. */ public int getSocketTimeOut() { return _socketTimeOut; } /** * Returns the CRC-32 checksum for the URL of this function caller. * * @return * the CRC-32 checksum. */ public int getCRC() { return _crc; } /** * Iterates over all leaves, the target descriptors. * * <p>The returned {@link java.util.Iterator} will only return this target * descriptor. * * @return * iterator that returns this target descriptor, never * <code>null</code>. */ public java.util.Iterator iterateTargets() { return new Iterator(); } /** * Counts the total number of target descriptors in/under this descriptor. * * @return * the total number of target descriptors, always 1. */ public int getTargetCount() { return 1; } /** * Returns the <code>TargetDescriptor</code> that matches the specified * CRC-32 checksum. * * @param crc * the CRC-32 checksum. * * @return * the {@link TargetDescriptor} that matches the specified checksum, or * <code>null</code>, if none could be found in this descriptor. */ public TargetDescriptor getTargetByCRC(int crc) { return (_crc == crc) ? this : null; } public String toString() { return _asString; } // Inner classes /** * Iterator over this (single) target descriptor. Needed for the * implementation of {@link #iterateTargets()}. * * @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 */ private final class Iterator extends Object implements java.util.Iterator { // Constructors /** * Constructs a new <code>Iterator</code>. */ private Iterator() { // TRACE: Enter constructor Log.log_1000(ITERATOR_CLASSNAME, null); // empty // TRACE: Leave constructor Log.log_1002(ITERATOR_CLASSNAME, null); } // Fields /** * Flag that indicates if this iterator is already done iterating over * the single element. */ private boolean _done; // Methods /** * Checks if there is a next element. * * @return * <code>true</code> if there is a next element, <code>false</code> * if there is not. */ public boolean hasNext() { return ! _done; } /** * Returns the next element. * * @return * the next element, never <code>null</code>. * * @throws NoSuchElementException * if there is no new element. */ public Object next() throws NoSuchElementException { if (_done) { throw new NoSuchElementException(); } else { _done = true; return TargetDescriptor.this; } } /** * Removes the element last returned by <code>next()</code> (unsupported * operation). * * @throws UnsupportedOperationException * always thrown, since this operation is unsupported. */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } }
package com.opensymphony.workflow.loader; import com.opensymphony.workflow.InvalidWorkflowDescriptorException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.*; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.*; /** * The WorkflowLoader is responsible for creating a WorkflowDesciptor * by loading the XML from various sources. * * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody</a> */ public class WorkflowLoader { //~ Methods //////////////////////////////////////////////////////////////// /** * @deprecated please use {@link #load(java.io.InputStream, boolean)} instead. */ public static WorkflowDescriptor load(final InputStream is) throws SAXException, IOException, InvalidWorkflowDescriptorException { return load(is, null, true); } public static WorkflowDescriptor load(final InputStream is, boolean validate) throws SAXException, IOException, InvalidWorkflowDescriptorException { return load(is, null, validate); } /** * Load a workflow descriptor from a URL */ public static WorkflowDescriptor load(final URL url, boolean validate) throws SAXException, IOException, InvalidWorkflowDescriptorException { return load(url.openStream(), url, validate); } private static WorkflowDescriptor load(InputStream is, URL url, boolean validate) throws SAXException, IOException, InvalidWorkflowDescriptorException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(validate); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setEntityResolver(new DTDEntityResolver()); } catch (ParserConfigurationException e) { throw new SAXException("Error creating document builder", e); } db.setErrorHandler(new WorkflowErrorHandler(url)); Document doc = db.parse(is); Element root = (Element) doc.getElementsByTagName("workflow").item(0); WorkflowDescriptor descriptor = new WorkflowDescriptor(root); if (validate) { descriptor.validate(); } return descriptor; } //~ Inner Classes ////////////////////////////////////////////////////////// public static class AllExceptionsErrorHandler implements ErrorHandler { private final List exceptions = new ArrayList(); public List getExceptions() { return exceptions; } public void error(SAXParseException exception) { addMessage(exception); } public void fatalError(SAXParseException exception) { addMessage(exception); } public void warning(SAXParseException exception) { } private void addMessage(SAXParseException exception) { exceptions.add(exception.getMessage() + " (line:" + exception.getLineNumber() + ((exception.getColumnNumber() > -1) ? (" col:" + exception.getColumnNumber()) : "") + ')'); } } public static class WorkflowErrorHandler implements ErrorHandler { private URL url; public WorkflowErrorHandler(final URL url) { this.url = url; } public void error(SAXParseException exception) throws SAXException { throw new SAXException(getMessage(exception)); } public void fatalError(SAXParseException exception) throws SAXException { throw new SAXException(getMessage(exception)); } public void warning(SAXParseException exception) throws SAXException { } private String getMessage(SAXParseException exception) { return exception.getMessage() + " (" + ((url != null) ? (" url=" + url + ' ') : "") + "line:" + exception.getLineNumber() + ((exception.getColumnNumber() > -1) ? (" col:" + exception.getColumnNumber()) : "") + ')'; } } }
// $Id: DisplayMisoSceneImpl.java,v 1.29 2001/08/15 01:10:09 mdb Exp $ package com.threerings.miso.scene; import java.awt.Point; import java.io.*; import java.util.ArrayList; import com.samskivert.util.StringUtil; import com.threerings.whirled.data.Scene; import com.threerings.miso.Log; import com.threerings.miso.tile.Tile; import com.threerings.miso.tile.TileManager; import com.threerings.miso.scene.util.ClusterUtil; /** * A scene object represents the data model corresponding to a single * screen for game play. For instance, one scene might display a portion * of a street with several buildings scattered about on the periphery. */ public class MisoScene implements Scene { /** The base layer id. */ public static final int LAYER_BASE = 0; /** The fringe layer id. */ public static final int LAYER_FRINGE = 1; /** The object layer id. */ public static final int LAYER_OBJECT = 2; /** The total number of layers. */ public static final int NUM_LAYERS = 3; /** The latest scene file format version. */ public static final short VERSION = 1; /** The scene width in tiles. */ public static final int TILE_WIDTH = 22; /** The scene height in tiles. */ public static final int TILE_HEIGHT = 22; /** String translations of each tile layer name. */ public static final String[] XLATE_LAYERS = { "Base", "Fringe", "Object" }; /** Scene id to denote an unset or otherwise invalid scene id. */ public static final int SID_INVALID = -1; /** The tiles comprising the scene. */ public Tile tiles[][][]; /** * Construct a new miso scene object. The base layer tiles are * initialized to contain tiles of the specified default tileset and * tile id. * * @param tilemgr the tile manager. * @param deftsid the default tileset id. * @param deftid the default tile id. */ public MisoScene (TileManager tilemgr, int deftsid, int deftid) { _tilemgr = tilemgr; _sid = SID_INVALID; _name = DEF_SCENE_NAME; _locations = new ArrayList(); _clusters = new ArrayList(); _exits = new ArrayList(); tiles = new Tile[TILE_WIDTH][TILE_HEIGHT][NUM_LAYERS]; _deftile = _tilemgr.getTile(deftsid, deftid); for (int xx = 0; xx < TILE_WIDTH; xx++) { for (int yy = 0; yy < TILE_HEIGHT; yy++) { for (int ii = 0; ii < NUM_LAYERS; ii++) { if (ii == LAYER_BASE) { tiles[xx][yy][ii] = _deftile; } } } } } /** * Construct a new miso scene object with the given values. * * @param tilemgr the tile manager. * @param name the scene name. * @param locations the locations. * @param exits the exits. * @param tiles the tiles comprising the scene. */ public MisoScene ( TileManager tilemgr, String name, ArrayList locations, ArrayList clusters, ArrayList exits, Tile tiles[][][]) { _tilemgr = tilemgr; _sid = SID_INVALID; _name = name; _locations = locations; _clusters = clusters; _exits = exits; this.tiles = tiles; } /** * Return the cluster index number the given location is in, or -1 * if the location is not in any cluster. * * @param loc the location. */ public int getClusterIndex (Location loc) { return ClusterUtil.getClusterIndex(_clusters, loc); } /** * Update the specified location in the scene. If the cluster * index number is -1, the location will be removed from any * cluster it may reside in. * * @param loc the location. * @param clusteridx the cluster index number. */ public void updateLocation (Location loc, int clusteridx) { // add the location if it's not already present if (!_locations.contains(loc)) { _locations.add(loc); } // update the cluster contents ClusterUtil.regroup(_clusters, loc, clusteridx); } /** * Add the specified exit to the scene. Adds the exit to the * location list as well if it's not already present and removes * it from any cluster it may reside in. * * @param exit the exit. */ public void addExit (Exit exit) { // make sure it's in the location list and absent from any cluster updateLocation(exit, -1); // don't allow adding an exit more than once if (_exits.contains(exit)) { Log.warning("Attempt to add already-existing exit " + "[exit=" + exit + "]."); return; } // add it to the list _exits.add(exit); } /** * Return the location object at the given full coordinates, or * null if no location is currently present. * * @param x the full x-position coordinate. * @param y the full y-position coordinate. * * @return the location object. */ public Location getLocation (int x, int y) { int size = _locations.size(); for (int ii = 0; ii < size; ii++) { Location loc = (Location)_locations.get(ii); if (loc.x == x && loc.y == y) return loc; } return null; } /** * Remove the given location object from the location list, and * from any containing cluster. If the location is an exit, it * is removed from the exit list as well. * * @param loc the location object. */ public void removeLocation (Location loc) { // remove from the location list if (!_locations.remove(loc)) { // we didn't know about it, so it can't be in a cluster or // the exit list return; } // remove from any possible cluster ClusterUtil.remove(_clusters, loc); // remove from any possible existence on the exit list _exits.remove(loc); } /** * Return the scene name. */ public String getName () { return _name; } /** * Return the scene identifier. */ public int getId () { return _sid; } /** * Returns this scene's version number (which is incremented when it * is modified and stored into the scene repository). */ public int getVersion () { // fake it for now return 1; } /** * Returns the scene ids of the exits from this scene. */ public int[] getExitIds () { return null; } /** * Return the scene locations list. */ public ArrayList getLocations () { return _locations; } /** * Return the cluster list. */ public ArrayList getClusters () { return _clusters; } /** * Return the scene exits list. */ public ArrayList getExits () { return _exits; } /** * Return the number of clusters in the scene. */ public int getNumClusters () { return _clusters.size(); } /** * Return the number of actual (non-null) tiles present in the * specified tile layer for this scene. */ public int getNumLayerTiles (int lnum) { if (lnum == LAYER_BASE) return TILE_WIDTH * TILE_HEIGHT; int numTiles = 0; for (int xx = 0; xx < TILE_WIDTH; xx++) { for (int yy = 0; yy < TILE_HEIGHT; yy++) { if (tiles[xx][yy] != null) numTiles++; } } return numTiles; } /** * Return the default tile for the base layer of the scene. */ public Tile getDefaultTile () { return _deftile; } /** * Return a string representation of this Scene object. */ public String toString () { StringBuffer buf = new StringBuffer(); buf.append("[name=").append(_name); buf.append(", sid=").append(_sid); buf.append(", locations=").append(StringUtil.toString(_locations)); buf.append(", clusters=").append(StringUtil.toString(_clusters)); buf.append(", exits=").append(StringUtil.toString(_exits)); return buf.append("]").toString(); } /** The default scene name. */ protected static final String DEF_SCENE_NAME = "Untitled Scene"; /** The scene name. */ protected String _name; /** The unique scene id. */ protected int _sid; /** The locations within the scene. */ protected ArrayList _locations; /** The clusters within the scene. */ protected ArrayList _clusters; /** The exits to different scenes. */ protected ArrayList _exits; /** The default tile for the base layer in the scene. */ protected Tile _deftile; /** The tile manager. */ protected TileManager _tilemgr; }
package nl.b3p.viewer.admin.stripes; import java.util.*; import javax.servlet.http.HttpServletResponse; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.*; import nl.b3p.viewer.config.services.*; import org.hibernate.*; import org.hibernate.criterion.*; import org.json.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/attribute/{$event}") @StrictBinding public class AttributeActionBean implements ActionBean { private ActionBeanContext context; private static final String JSP = "/WEB-INF/jsp/services/attribute.jsp"; private static final String EDITJSP = "/WEB-INF/jsp/services/editattribute.jsp"; @Validate private int page; @Validate private int start; @Validate private int limit; @Validate private String sort; @Validate private String dir; @Validate private JSONArray filter; @Validate private String featureSourceId; @Validate private String simpleFeatureTypeId; private List featureSources; @Validate private AttributeDescriptor attribute; @Validate private String alias; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public AttributeDescriptor getAttribute() { return attribute; } public void setAttribute(AttributeDescriptor attribute) { this.attribute = attribute; } public List getFeatureSources() { return featureSources; } public void setFeatureSources(List featureSources) { this.featureSources = featureSources; } public String getSimpleFeatureTypeId() { return simpleFeatureTypeId; } public void setSimpleFeatureTypeId(String simpleFeatureTypeId) { this.simpleFeatureTypeId = simpleFeatureTypeId; } public String getFeatureSourceId() { return featureSourceId; } public void setFeatureSourceId(String featureSourceId) { this.featureSourceId = featureSourceId; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public JSONArray getFilter() { return filter; } public void setFilter(JSONArray filter) { this.filter = filter; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } //</editor-fold> @DefaultHandler public Resolution view() { return new ForwardResolution(JSP); } public Resolution edit() { return new ForwardResolution(EDITJSP); } public Resolution cancel() { return new ForwardResolution(EDITJSP); } public Resolution save() { attribute.setAlias(alias); Stripersist.getEntityManager().persist(attribute); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Attribuut is opgeslagen")); return new ForwardResolution(EDITJSP); } @Before(stages=LifecycleStage.BindingAndValidation) @SuppressWarnings("unchecked") public void load() { featureSources = Stripersist.getEntityManager().createQuery("from FeatureSource").getResultList(); } public Resolution selectBron() throws JSONException { return new ForwardResolution(JSP); } public Resolution getFeatureTypes() throws JSONException { final JSONArray simpleFeatureTypes = new JSONArray(); if(featureSourceId != null){ FeatureSource fc = (FeatureSource)Stripersist.getEntityManager().find(FeatureSource.class, featureSourceId); List<SimpleFeatureType> sftList = fc.getFeatureTypes(); for(Iterator it = sftList.iterator(); it.hasNext();){ SimpleFeatureType sft = (SimpleFeatureType)it.next(); JSONObject j = new JSONObject(); j.put("id", sft.getId()); j.put("name", sft.getTypeName()); simpleFeatureTypes.put(j); } } return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(simpleFeatureTypes.toString()); } }; } public Resolution getGridData() throws JSONException { JSONArray jsonData = new JSONArray(); String filterAlias = ""; String filterAttribuut = ""; boolean hasFilter= false; /* * FILTERING: filter is delivered by frontend as JSON array [{property, value}] * for demo purposes the value is now returned, ofcourse here should the DB * query be built to filter the right records */ if(this.getFilter() != null) { hasFilter = true; for(int k = 0; k < this.getFilter().length(); k++) { JSONObject j = this.getFilter().getJSONObject(k); String property = j.getString("property"); String value = j.getString("value"); if(property.equals("alias")) { filterAlias = value; } if(property.equals("attribute")) { filterAttribuut = value; } } } Session sess = (Session)Stripersist.getEntityManager().getDelegate(); Criteria c = sess.createCriteria(AttributeDescriptor.class); c.setMaxResults(limit); c.setFirstResult(start); /* Sorting is delivered by the frontend * as two variables: sort which holds the column name and dir which * holds the direction (ASC, DESC). */ if(sort != null && dir != null){ Order order = null; if(dir.equals("ASC")){ order = Order.asc(sort); }else{ order = Order.desc(sort); } order.ignoreCase(); c.addOrder(order); } if(filterAlias != null && filterAlias.length() > 0){ Criterion aliasCrit = Restrictions.ilike("alias", filterAlias, MatchMode.ANYWHERE); c.add(aliasCrit); } if(filterAttribuut != null && filterAttribuut.length() > 0){ Criterion attribuutCrit = Restrictions.ilike("name", filterAttribuut, MatchMode.ANYWHERE); c.add(attribuutCrit); } List attributes = c.list(); for(Iterator it = attributes.iterator(); it.hasNext();){ AttributeDescriptor attr = (AttributeDescriptor)it.next(); JSONObject j = this.getGridRow(attr.getId().intValue(), attr.getAlias(), attr.getName()); jsonData.put(j); } int rowCount; if(!hasFilter){ rowCount = Stripersist.getEntityManager().createQuery("from AttributeDescriptor").getResultList().size(); }else{ rowCount = attributes.size(); } final JSONObject grid = new JSONObject(); grid.put("totalCount", rowCount); grid.put("gridrows", jsonData); return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(grid.toString()); } }; } private JSONObject getGridRow(int i, String alias, String attribute) throws JSONException { JSONObject j = new JSONObject(); j.put("id", i); j.put("alias", alias); j.put("attribute", attribute); return j; } }
package edu.vu.isis.ammo.core.distributor; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.vu.isis.ammo.core.AmmoService; import edu.vu.isis.ammo.core.distributor.DistributorDataStore.ChannelStatus; import edu.vu.isis.ammo.core.distributor.DistributorDataStore.DisposalState; import edu.vu.isis.ammo.core.distributor.DistributorDataStore.DisposalTotalState; import edu.vu.isis.ammo.core.distributor.DistributorPolicy.Encoding; import edu.vu.isis.ammo.core.distributor.DistributorPolicy.Routing; /** * The dispersal vector is related to the distribution policy * and a particular request. * The particular request will have a topic which maps to the distribution policy. * When all of the clauses of a topic's policy have been * satisfied the total is true, otherwise it is false. * */ public class DistributorState { private static final Logger logger = LoggerFactory.getLogger("dist.state"); private final Map<String, DisposalState> stateMap; private boolean total; public final Routing policy; public final String channelFilter; private DistributorState(Routing policy, final String channelFilter) { this.stateMap = new HashMap<String, DisposalState>(); this.total = false; this.policy = policy; this.channelFilter = channelFilter; } static public DistributorState newInstance(Routing routing, final String channelFilter) { return new DistributorState(routing, channelFilter); } public boolean total() { return this.total; } public DistributorState total(boolean state) { this.total = state; return this; } public DisposalState put(String key, DisposalState value) { return stateMap.put(key, value); } public DisposalState get(String key) { return stateMap.get(key); } public boolean containsKey(String key) { return stateMap.containsKey(key); } public Set<Entry<String, DisposalState>> entrySet() { return stateMap.entrySet(); } public int size() { return stateMap.size(); } public DistributorState and(boolean clause) { this.total &= clause; return this; } @Override public String toString() { final StringBuilder sb = new StringBuilder() .append("type: ").append(this.type).append(" ") .append("status:"); for( final Map.Entry<String,DisposalState> entry : this.stateMap.entrySet()) { sb.append('\n').append(entry.getKey()).append(" : ").append(entry.getValue()); } return sb.toString(); } /** * Attempt to satisfy the distribution policy for this message's topic. * * The policies are processed in "short circuit" disjunctive normal form. * Each clause is evaluated there results are 'anded' together, hence disjunction. * Within a clause each literal is handled in order until one matches * its prescribed condition, effecting a short circuit conjunction. * (It is short circuit as only the first literal to be true is evaluated.) * * In order for a topic to evaluate to success all of its clauses must evaluate true. * In order for a clause to be true at least (exactly) one of its literals must succeed. * A literal is true if the condition of the term matches the * 'condition' attribute for the term. * * @see scripts/tests/distribution_policy.xml for an example. * * Given the presence of a channel filter... * - skip any attempt at delivery unless the forced channel matches the term * - mark the clause true if it doesn't contain the forced channel */ public DistributorState multiplexRequest(AmmoService that, RequestSerializer serializer) { logger.trace("::multiplex request"); if (this.policy == null) { logger.error("no matching routing topic"); final ChannelStatus channelStatus = that.checkChannel(DistributorPolicy.DEFAULT); final DisposalState actualCondition; switch (channelStatus) { case READY: actualCondition = serializer.act(that,Encoding.getDefault(),DistributorPolicy.DEFAULT); break; default: actualCondition = channelStatus.inferDisposal(); } this.put(DistributorPolicy.DEFAULT, actualCondition); return this; } // evaluate rule this.total(true); for (final DistributorPolicy.Clause clause : this.policy.clauses) { boolean clauseSuccess = false; // evaluate clause status based on previous attempts boolean haschannelFilter = false; for (DistributorPolicy.Literal literal : clause.literals) { final String term = literal.term; if (this.channelFilter != null && ! term.equals(this.channelFilter)) { haschannelFilter = true; } final boolean goalCondition = literal.condition; final DisposalState priorCondition = (this.containsKey(term)) ? this.get(term) : DisposalState.PENDING; logger.debug("prior {} {} {}", new Object[]{term, priorCondition, goalCondition}); if (priorCondition.goalReached(goalCondition)) { clauseSuccess = true; logger.trace("clause previously satisfied {} {}", this, clause); break; } } if (this.channelFilter != null && ! haschannelFilter) { logger.info("clause is practically successful due to forced channel=[{}], clause type=[{}]", this.channelFilter, this.type); continue; } if (clauseSuccess) continue; // evaluate clause based on for (DistributorPolicy.Literal literal : clause.literals) { final String term = literal.term; if (this.channelFilter != null && ! term.equals(this.channelFilter)) continue; final boolean goalCondition = literal.condition; final DisposalState priorCondition = (this.containsKey(term)) ? this.get(term) : DisposalState.PENDING; DisposalState actualCondition; switch (priorCondition) { case PENDING: final ChannelStatus channelStatus = that.checkChannel(term); switch (channelStatus) { case READY: actualCondition = serializer.act(that,literal.encoding,term); break; default: actualCondition = channelStatus.inferDisposal(); } this.put(term, actualCondition); logger.trace("attempting message over {}", term); break; default: actualCondition = priorCondition; } if (actualCondition.goalReached(goalCondition)) { clauseSuccess = true; logger.trace("clause satisfied {} {}", this, clause); break; } } this.and(clauseSuccess); } return this; } /** * examine the states of each channel and generate an aggregate status. * @return */ public DisposalTotalState aggregate() { if (this.total) return DisposalTotalState.COMPLETE; int aggregated = 0x0000; for (final Entry<String,DisposalState> entry : this.stateMap.entrySet()) { aggregated |= entry.getValue().o; } if (0 < (aggregated & (DisposalState.REJECTED.o | DisposalState.BUSY.o) )) return DisposalTotalState.INCOMPLETE; if (0 < (aggregated & (DisposalState.PENDING.o | DisposalState.NEW.o) )) return DisposalTotalState.DISTRIBUTE; if (0 < (aggregated & (DisposalState.SENT.o | DisposalState.TOLD.o | DisposalState.DELIVERED.o) )) return DisposalTotalState.COMPLETE; if (0 < (aggregated & (DisposalState.BAD.o) )) return DisposalTotalState.FAILED; return DisposalTotalState.DISTRIBUTE; } private String type; public DistributorState setType(String type) { this.type = type; return this; } }
package marcelocf.janusgraph; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; public class Timeline { private static final Logger LOGGER = LoggerFactory.getLogger(Timeline.class); public static void main(String argv[]) throws Exception { JanusGraph graph = JanusGraphFactory.open(Schema.CONFIG_FILE); HadoopQueryRunner q = new HadoopQueryRunner(graph.traversal(), "testUser1"); for(int i =0; i< 10; i++) { LOGGER.info("Previous Timeline"); q.printTimeline(q.getTimeline2(10)); LOGGER.info("New Timeline"); q.printTimeline(q.getTimeline3(10)); } q.close(); graph.close(); } }
package org.apache.commons.lang.builder; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.ObjectUtils; public class ToStringBuilder { /** * The default style of output to use. */ private static ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; /** * <p>Gets the default <code>ToStringStyle</code> to use.</p> * * <p>This could allow the <code>ToStringStyle</code> to be * controlled for an entire application with one call.</p> * * <p>This might be used to have a verbose * <code>ToStringStyle</code> during development and a compact * <code>ToStringStyle</code> in production.</p> * * @return the default <code>ToStringStyle</code> */ public static ToStringStyle getDefaultStyle() { return defaultStyle; } /** * <p>Forwards to <code>ReflectionToStringBuilder</code>.</p> * * @see ReflectionToStringBuilder#toString(Object) */ public static String reflectionToString(Object object) { return ReflectionToStringBuilder.toString(object); } /** * <p>Forwards to <code>ReflectionToStringBuilder</code>.</p> * * @see ReflectionToStringBuilder#toString(Object,ToStringStyle) */ public static String reflectionToString(Object object, ToStringStyle style) { return ReflectionToStringBuilder.toString(object, style); } /** * <p>Forwards to <code>ReflectionToStringBuilder</code>.</p> * * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean) */ public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) { return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null); } /** * <p>Forwards to <code>ReflectionToStringBuilder</code>.</p> * * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,Class) * @since 2.0 */ public static String reflectionToString( Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) { return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass); } public static void setDefaultStyle(ToStringStyle style) { if (style == null) { throw new IllegalArgumentException("The style must not be null"); } defaultStyle = style; } /** * Current toString buffer. */ private final StringBuffer buffer; /** * The object being output. */ private final Object object; /** * The style of output to use. */ private final ToStringStyle style; public ToStringBuilder(Object object) { this(object, getDefaultStyle(), null); } public ToStringBuilder(Object object, ToStringStyle style) { this(object, style, null); } public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { super(); if (object == null) { throw new IllegalArgumentException("The object to create a toString for must not be null"); } if (style == null) { style = getDefaultStyle(); } if (buffer == null) { buffer = new StringBuffer(512); } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object object) { style.append(buffer, null, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, boolean value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, boolean[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>byte</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, byte value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, byte[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, char value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, char[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, double value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, double[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>float</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, float value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, float[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, int value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, int[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, long value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, long[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object object) { style.append(buffer, fieldName, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, * <code>false</code> for summary info * @return this */ public ToStringBuilder append(String fieldName, Object object, boolean fullDetail) { style.append(buffer, fieldName, object, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> an <code>short</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, short value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, short[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** * <p>Appends with the same format as the default <code>Object toString() * </code> method. Appends the class name followed by * {@link System#identityHashCode(java.lang.Object)}.</p> * * @param object the <code>Object</code> whose class name and id to output * @return this * @since 2.0 */ public ToStringBuilder appendAsObjectToString(Object object) { ObjectUtils.appendIdentityToString(this.getStringBuffer(), object); return this; } /** * <p>Append the <code>toString</code> from the superclass.</p> * * <p>This method assumes that the superclass uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If <code>superToString</code> is <code>null</code>, no change is made.</p> * * @param superToString the result of <code>super.toString()</code> * @return this * @since 2.0 */ public ToStringBuilder appendSuper(String superToString) { if (superToString != null) { style.appendSuper(buffer, superToString); } return this; } /** * <p>Append the <code>toString</code> from another object.</p> * * <p>This method is useful where a class delegates most of the implementation of * its properties to another class. You can then call <code>toString()</code> on * the other class and pass the result into this method.</p> * * <pre> * private AnotherObject delegate; * private String fieldInThisClass; * * public String toString() { * return new ToStringBuilder(this). * appendToString(delegate.toString()). * append(fieldInThisClass). * toString(); * }</pre> * * <p>This method assumes that the other object uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>toString</code> is <code>null</code>, no change is made.</p> * * @param toString the result of <code>toString()</code> on another object * @return this * @since 2.0 */ public ToStringBuilder appendToString(String toString) { if (toString != null) { style.appendToString(buffer, toString); } return this; } /** * <p>Returns the <code>Object</code> being output.</p> * * @return The object being output. * @since 2.0 */ public Object getObject() { return object; } /** * <p>Gets the <code>StringBuffer</code> being populated.</p> * * @return the <code>StringBuffer</code> being populated */ public StringBuffer getStringBuffer() { return buffer; } /** * <p>Gets the <code>ToStringStyle</code> being used.</p> * * @return the <code>ToStringStyle</code> being used * @since 2.0 */ public ToStringStyle getStyle() { return style; } /** * <p>Returns the built <code>toString</code>.</p> * * <p>This method appends the end of data indicator, and can only be called once. * Use {@link #getStringBuffer} to get the current string state.</p> * * @return the String <code>toString</code> */ public String toString() { style.appendEnd(buffer, object); return buffer.toString(); } }
package org.jdesktop.swingx.plaf.basic; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.SortedSet; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.KeyStroke; import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import org.jdesktop.swingx.DateSelectionListener; import org.jdesktop.swingx.DateSelectionModel; import org.jdesktop.swingx.calendar.DateUtils; import org.jdesktop.swingx.calendar.JXMonthView; import org.jdesktop.swingx.calendar.JXMonthView.SelectionMode; import org.jdesktop.swingx.event.DateSelectionEvent; import org.jdesktop.swingx.plaf.MonthViewUI; /** * Base implementation of the <code>JXMonthView</code> UI. * * @author dmouse * @author rbair * @author rah003 */ public class BasicMonthViewUI extends MonthViewUI { private static final int LEADING_DAY_OFFSET = 1; private static final int NO_OFFSET = 0; private static final int TRAILING_DAY_OFFSET = -1; private static final int WEEKS_IN_MONTH = 6; private static final int CALENDAR_SPACING = 10; private static final Point NO_SUCH_CALENDAR = new Point(-1, -1); /** Formatter used to format the day of the week to a numerical value. */ protected static final SimpleDateFormat dayOfMonthFormatter = new SimpleDateFormat("d"); private static String[] monthsOfTheYear; protected JXMonthView monthView; protected long firstDisplayedDate; protected int firstDisplayedMonth; protected int firstDisplayedYear; protected long lastDisplayedDate; protected long today; protected SortedSet<Date> selection; /** Used as the font for flagged days. */ protected Font derivedFont; private boolean usingKeyboard = false; /** For interval selections we need to record the date we pivot around. */ private long pivotDate = -1; protected boolean isLeftToRight; private int arrowPaddingX = 3; private int arrowPaddingY = 3; private int fullMonthBoxHeight; private int fullBoxWidth; private int fullBoxHeight; private int startX; private int startY; private Dimension dim = new Dimension(); private PropertyChangeListener propertyChangeListener; private MouseListener mouseListener; private MouseMotionListener mouseMotionListener; private Handler handler; protected Icon monthUpImage; protected Icon monthDownImage; private Rectangle dirtyRect = new Rectangle(); private Rectangle bounds = new Rectangle(); private Color weekOfTheYearForeground; private Color unselectableDayForeground; private Color leadingDayForeground; private Color trailingDayForeground; /** * Date span used by the keyboard actions to track the original selection. */ private SortedSet<Date> originalDateSpan; private int calendarWidth; private int monthBoxHeight; private int boxWidth; private int boxHeight; private int calendarHeight; /** The number of calendars able to be displayed horizontally. */ private int numCalRows = 1; /** The number of calendars able to be displayed vertically. */ private int numCalCols = 1; private Rectangle[] monthStringBounds = new Rectangle[12]; private Rectangle[] yearStringBounds = new Rectangle[12]; @SuppressWarnings({"UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new BasicMonthViewUI(); } public void installUI(JComponent c) { monthView = (JXMonthView)c; monthView.setLayout(createLayoutManager()); isLeftToRight = monthView.getComponentOrientation().isLeftToRight(); LookAndFeel.installProperty(monthView, "opaque", Boolean.TRUE); // Get string representation of the months of the year. monthsOfTheYear = new DateFormatSymbols().getMonths(); installComponents(); installDefaults(); installKeyboardActions(); installListeners(); if (monthView.getCalendar() != null) { firstDisplayedDate = monthView.getCalendar().getTimeInMillis(); firstDisplayedMonth = monthView.getCalendar().get(Calendar.MONTH); firstDisplayedYear = monthView.getCalendar().get(Calendar.YEAR); } selection = monthView.getSelection(); } public void uninstallUI(JComponent c) { uninstallListeners(); uninstallKeyboardActions(); uninstallDefaults(); uninstallComponents(); monthView.setLayout(null); monthView = null; } protected void installComponents() {} protected void uninstallComponents() {} protected void installDefaults() { String[] daysOfTheWeek = (String[])UIManager.get("JXMonthView.daysOfTheWeek"); if (daysOfTheWeek == null) { String[] dateFormatSymbols = new DateFormatSymbols().getShortWeekdays(); daysOfTheWeek = new String[JXMonthView.DAYS_IN_WEEK]; for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { daysOfTheWeek[i - 1] = dateFormatSymbols[i]; } } Color background = monthView.getBackground(); if (background == null || background instanceof UIResource) { monthView.setBackground(UIManager.getColor("JXMonthView.background")); } monthView.setDaysOfTheWeek(daysOfTheWeek); monthView.setBoxPaddingX((Integer)UIManager.get("JXMonthView.boxPaddingX")); monthView.setBoxPaddingY((Integer)UIManager.get("JXMonthView.boxPaddingY")); monthView.setMonthStringBackground(UIManager.getColor("JXMonthView.monthStringBackground")); monthView.setMonthStringForeground(UIManager.getColor("JXMonthView.monthStringForeground")); monthView.setDaysOfTheWeekForeground(UIManager.getColor("JXMonthView.daysOfTheWeekForeground")); monthView.setSelectedBackground(UIManager.getColor("JXMonthView.selectedBackground")); monthView.setFlaggedDayForeground(UIManager.getColor("JXMonthView.flaggedDayForeground")); Font f = monthView.getFont(); if (f == null || f instanceof UIResource) { monthView.setFont(UIManager.getFont("JXMonthView.font")); } monthDownImage = new ImageIcon( JXMonthView.class.getResource(UIManager.getString("JXMonthView.monthDownFileName"))); monthUpImage = new ImageIcon( JXMonthView.class.getResource(UIManager.getString("JXMonthView.monthUpFileName"))); weekOfTheYearForeground = UIManager.getColor("JXMonthView.weekOfTheYearForeground"); leadingDayForeground = UIManager.getColor("JXMonthView.leadingDayForeground"); trailingDayForeground = UIManager.getColor("JXMonthView.trailingDayForeground"); unselectableDayForeground = UIManager.getColor("JXMonthView.unselectableDayForeground"); derivedFont = createDerivedFont(); } protected void uninstallDefaults() {} protected void installKeyboardActions() { // Setup the keyboard handler. InputMap inputMap = monthView.getInputMap(JComponent.WHEN_FOCUSED); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "acceptSelection"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "cancelSelection"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "selectPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "selectNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "selectDayInPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "selectDayInNextWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_MASK, false), "addPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.SHIFT_MASK, false), "addNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK, false), "addToPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.SHIFT_MASK, false), "addToNextWeek"); // Needed to allow for keyboard control in popups. inputMap = monthView.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "acceptSelection"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "cancelSelection"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "selectPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "selectNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "selectDayInPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "selectDayInNextWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_MASK, false), "adjustSelectionPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.SHIFT_MASK, false), "adjustSelectionNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK, false), "adjustSelectionPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.SHIFT_MASK, false), "adjustSelectionNextWeek"); ActionMap actionMap = monthView.getActionMap(); actionMap.put("acceptSelection", new KeyboardAction(KeyboardAction.ACCEPT_SELECTION)); actionMap.put("cancelSelection", new KeyboardAction(KeyboardAction.CANCEL_SELECTION)); actionMap.put("selectPreviousDay", new KeyboardAction(KeyboardAction.SELECT_PREVIOUS_DAY)); actionMap.put("selectNextDay", new KeyboardAction(KeyboardAction.SELECT_NEXT_DAY)); actionMap.put("selectDayInPreviousWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_PREVIOUS_WEEK)); actionMap.put("selectDayInNextWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_NEXT_WEEK)); actionMap.put("adjustSelectionPreviousDay", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_PREVIOUS_DAY)); actionMap.put("adjustSelectionNextDay", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_NEXT_DAY)); actionMap.put("adjustSelectionPreviousWeek", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_PREVIOUS_WEEK)); actionMap.put("adjustSelectionNextWeek", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_NEXT_WEEK)); } protected void uninstallKeyboardActions() {} protected void installListeners() { propertyChangeListener = createPropertyChangeListener(); mouseListener = createMouseListener(); mouseMotionListener = createMouseMotionListener(); monthView.addPropertyChangeListener(propertyChangeListener); monthView.addMouseListener(mouseListener); monthView.addMouseMotionListener(mouseMotionListener); monthView.getSelectionModel().addDateSelectionListener(getHandler()); } protected void uninstallListeners() { monthView.getSelectionModel().removeDateSelectionListener(getHandler()); monthView.removeMouseMotionListener(mouseMotionListener); monthView.removeMouseListener(mouseListener); monthView.removePropertyChangeListener(propertyChangeListener); mouseMotionListener = null; mouseListener = null; propertyChangeListener = null; } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } protected LayoutManager createLayoutManager() { return getHandler(); } protected MouseListener createMouseListener() { return getHandler(); } protected MouseMotionListener createMouseMotionListener() { return getHandler(); } /** * Create a derived font used to when painting various pieces of the * month view component. This method will be called whenever * the font on the component is set so a new derived font can be created. */ protected Font createDerivedFont() { return monthView.getFont().deriveFont(Font.BOLD); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } public boolean isUsingKeyboard() { return usingKeyboard; } public void setUsingKeyboard(boolean val) { usingKeyboard = val; } /** * Returns true if the date passed in is the same as today. * * @param date long representing the date you want to compare to today. * @return true if the date passed is the same as today. */ protected boolean isToday(long date) { return date == today; } public long getDayAt(int x, int y) { Point rowCol = getCalRowColAt(x, y); if (NO_SUCH_CALENDAR.equals(rowCol)) { return -1; } if (rowCol.x > numCalRows - 1 || rowCol.y > numCalCols - 1) { return -1; } // Determine what row (week) in the selected month we're in. int row = 1; int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); row += (((y - startY) - (rowCol.x * (calendarHeight + CALENDAR_SPACING))) - (boxPaddingY + monthBoxHeight + boxPaddingY)) / (boxPaddingY + boxHeight + boxPaddingY); // The first two lines in the calendar are the month and the days // of the week. Ignore them. row -= 2; if (row < 0 || row > 5) { return -1; } // Determine which column in the selected month we're in. int col = ((isLeftToRight ? (x - startX) : (startX - x)) - (rowCol.y * (calendarWidth + CALENDAR_SPACING))) / (boxPaddingX + boxWidth + boxPaddingX); // If we're showing week numbers we need to reduce the selected // col index by one. if (monthView.isShowingWeekNumber()) { col } // Make sure the selected column matches up with a day of the week. if (col < 0 || col > JXMonthView.DAYS_IN_WEEK - 1) { return -1; } // Use the first day of the month as a key point for determining the // date of our click. // The week index of the first day will always be 0. Calendar cal = monthView.getCalendar(); cal.setTimeInMillis(firstDisplayedDate); //_cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.MONTH, rowCol.y + (rowCol.x * numCalCols)); int firstDayViewIndex = getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK)); int daysToAdd = (row * JXMonthView.DAYS_IN_WEEK) + (col - firstDayViewIndex); if (daysToAdd < 0 || daysToAdd > (cal.getActualMaximum(Calendar.DAY_OF_MONTH) - 1)) { return -1; } cal.add(Calendar.DAY_OF_MONTH, daysToAdd); long selected = cal.getTimeInMillis(); // Restore the time. cal.setTimeInMillis(firstDisplayedDate); return selected; } /** * Convenience method so subclasses can get the currently painted day's day of the * week. It is assumed the calendar, _cal, is already set to the correct day. * * @see java.util.Calendar * @return day of the week (Calendar.SATURDAY, Calendar.SUNDAY, ...) */ protected int getDayOfTheWeek() { return monthView.getCalendar().get(Calendar.DAY_OF_WEEK); } /** * Get the view index for the specified day of the week. This value will range * from 0 to DAYS_IN_WEEK - 1. For example if the first day of the week was set * to Calendar.MONDAY and we requested the view index for Calendar.TUESDAY the result * would be 1. * * @param dayOfWeek day of the week to calculate view index for, acceptable values are * <code>Calendar.MONDAY</code> - <code>Calendar.SUNDAY</code> * @return view index for the specified day of the week */ private int getDayOfWeekViewIndex(int dayOfWeek) { int result = dayOfWeek - monthView.getFirstDayOfWeek(); if (result < 0) { result += JXMonthView.DAYS_IN_WEEK; } return result; } /** * Returns an index defining which, if any, of the buttons for * traversing the month was pressed. This method should only be * called when <code>setTraversable</code> is set to true. * * @param x x position of the pointer * @param y y position of the pointer * @return MONTH_UP, MONTH_DOWN or -1 when no button is selected. */ protected int getTraversableButtonAt(int x, int y) { Point rowCol = getCalRowColAt(x, y); if (NO_SUCH_CALENDAR.equals(rowCol)) { return -1; } // See if we're in the month string area. y = ((y - startY) - (rowCol.x * (calendarHeight + CALENDAR_SPACING))) - monthView.getBoxPaddingY(); if (y < arrowPaddingY || y > (monthBoxHeight - arrowPaddingY)) { return -1; } x = ((isLeftToRight ? (x - startX) : (startX - x)) - (rowCol.y * (calendarWidth + CALENDAR_SPACING))); if (x > arrowPaddingX && x < (arrowPaddingX + monthDownImage.getIconWidth() + arrowPaddingX)) { return JXMonthView.MONTH_DOWN; } if (x > (calendarWidth - arrowPaddingX * 2 - monthUpImage.getIconWidth()) && x < (calendarWidth - arrowPaddingX)) { return JXMonthView.MONTH_UP; } return -1; } /** * Get the row and column for the calendar at the specified coordinates * * @param x x location * @param y y location * @return a new <code>Point</code> object containing the row as the x value * and column as the y value */ protected Point getCalRowColAt(int x, int y) { if (isLeftToRight ? (startX > x) : (startX < x) || startY > y) { return NO_SUCH_CALENDAR; } Point result = new Point(); // Determine which row of calendars we're in. result.x = (y - startY) / (calendarHeight + CALENDAR_SPACING); // Determine which column of calendars we're in. result.y = (isLeftToRight ? (x - startX) : (startX - x)) / (calendarWidth + CALENDAR_SPACING); // Make sure the row and column of calendars calculated is being // managed. if (result.x > numCalRows - 1 || result.y > numCalCols -1) { result = NO_SUCH_CALENDAR; } return result; } /** * Calculates the startX/startY position for centering the calendars * within the available space. */ private void calculateStartPosition() { // Calculate offset in x-axis for centering calendars. int width = monthView.getWidth(); startX = (width - ((calendarWidth * numCalCols) + (CALENDAR_SPACING * (numCalCols - 1)))) / 2; if (!isLeftToRight) { startX = width - startX; } // Calculate offset in y-axis for centering calendars. startY = (monthView.getHeight() - ((calendarHeight * numCalRows) + (CALENDAR_SPACING * (numCalRows - 1 )))) / 2; } /** * Calculates the numCalCols/numCalRows that determine the number of * calendars that can be displayed. */ private void calculateNumDisplayedCals() { int oldNumCalCols = numCalCols; int oldNumCalRows = numCalRows; // Determine how many columns of calendars we want to paint. numCalCols = 1; numCalCols += (monthView.getWidth() - calendarWidth) / (calendarWidth + CALENDAR_SPACING); // Determine how many rows of calendars we want to paint. numCalRows = 1; numCalRows += (monthView.getHeight() - calendarHeight) / (calendarHeight + CALENDAR_SPACING); if (oldNumCalCols != numCalCols || oldNumCalRows != numCalRows) { calculateLastDisplayedDate(); } } public long calculateLastDisplayedDate() { Calendar cal = monthView.getCalendar(); cal.setTimeInMillis(firstDisplayedDate); // Figure out the last displayed date. cal.add(Calendar.MONTH, ((numCalCols * numCalRows) - 1)); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); lastDisplayedDate = cal.getTimeInMillis(); return lastDisplayedDate; } private void calculateDirtyRectForSelection() { if (selection == null || selection.isEmpty()) { dirtyRect.x = 0; dirtyRect.y = 0; dirtyRect.width = 0; dirtyRect.height = 0; } else { Calendar cal = monthView.getCalendar(); cal.setTime(selection.first()); calculateBoundsForDay(dirtyRect, NO_OFFSET); cal.add(Calendar.DAY_OF_MONTH, 1); Rectangle tmpRect; while (cal.getTimeInMillis() <= selection.last().getTime()) { calculateBoundsForDay(bounds, NO_OFFSET); tmpRect = dirtyRect.union(bounds); dirtyRect.x = tmpRect.x; dirtyRect.y = tmpRect.y; dirtyRect.width = tmpRect.width; dirtyRect.height = tmpRect.height; cal.add(Calendar.DAY_OF_MONTH, 1); } // Restore the time. cal.setTimeInMillis(firstDisplayedDate); } } /** * Calculate the bounding box for drawing a date. It is assumed that the * calendar, _cal, is already set to the date you want to find the offset * for. * * @param bounds Bounds of the date to draw in. * @param monthOffset Used to help calculate bounds for leading/trailing dates. */ private void calculateBoundsForDay(Rectangle bounds, int monthOffset) { Calendar cal = monthView.getCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); // If we are calculating the bounds for a leading/trailing day we need to // adjust the month we are in to calculate the bounds correctly. month += monthOffset; // If we're showing leading days the week in month needs to be 1 to make the bounds // calculate correctly. if (LEADING_DAY_OFFSET == monthOffset) { weekOfMonth = 1; } if (TRAILING_DAY_OFFSET == monthOffset) { // Find which week the last day in the month is. int day = cal.get(Calendar.DAY_OF_MONTH); int weekOffset = cal.get(Calendar.WEEK_OF_MONTH) - 1; cal.add(Calendar.DAY_OF_MONTH, -day); int lastWeekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); int lastDay = getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK)); if (lastDay == (JXMonthView.DAYS_IN_WEEK - 1)) { weekOffset++; } // Move back to our current day. cal.add(Calendar.DAY_OF_MONTH, day); weekOfMonth = lastWeekOfMonth + weekOffset; } // Determine what row/column we are in. int diffMonths = month - firstDisplayedMonth + ((year - firstDisplayedYear) * JXMonthView.MONTHS_IN_YEAR); int calRowIndex = diffMonths / numCalCols; int calColIndex = diffMonths - (calRowIndex * numCalCols); // Modify the index relative to the first day of the week. bounds.x = getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK)); // Offset for location of the day in the week. int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); // If we're showing week numbers then increase the bounds.x // by one more boxPaddingX boxWidth boxPaddingX. if (monthView.isShowingWeekNumber()) { bounds.x++; } // Calculate the x location. bounds.x = isLeftToRight ? bounds.x * (boxPaddingX + boxWidth + boxPaddingX) : (bounds.x + 1) * (boxPaddingX + boxWidth + boxPaddingX); // Offset for the column the calendar is displayed in. bounds.x += calColIndex * (calendarWidth + CALENDAR_SPACING); // Adjust by centering value. bounds.x = isLeftToRight ? startX + bounds.x : startX - bounds.x; // Initial offset for Month and Days of the Week display. bounds.y = boxPaddingY + monthBoxHeight + boxPaddingY + + boxPaddingY + boxHeight + boxPaddingY; // Offset for centering and row the calendar is displayed in. bounds.y += startY + calRowIndex * (calendarHeight + CALENDAR_SPACING); // Offset for Week of the Month. bounds.y += (weekOfMonth - 1) * (boxPaddingY + boxHeight + boxPaddingY); bounds.width = boxPaddingX + boxWidth + boxPaddingX; bounds.height = boxPaddingY + boxHeight + boxPaddingY; } @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); Object oldAAValue = null; Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D)g : null; if (g2 != null && monthView.isAntialiased()) { oldAAValue = g2.getRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } Rectangle clip = g.getClipBounds(); Graphics tmp = g.create(); paintBackground(clip, tmp); tmp.dispose(); g.setColor(monthView.getForeground()); // Reset the calendar. Calendar cal = monthView.getCalendar(); cal.setTimeInMillis(firstDisplayedDate); // Center the calendars horizontally/vertically in the available space. for (int row = 0; row < numCalRows; row++) { // Check if this row falls in the clip region. bounds.x = 0; bounds.y = startY + row * (calendarHeight + CALENDAR_SPACING); bounds.width = monthView.getWidth(); bounds.height = calendarHeight; if (!bounds.intersects(clip)) { cal.add(Calendar.MONTH, numCalCols); continue; } for (int column = 0; column < numCalCols; column++) { // Check if the month to paint falls in the clip. bounds.x = startX + (isLeftToRight ? column * (calendarWidth + CALENDAR_SPACING) : -(column * (calendarWidth + CALENDAR_SPACING) + calendarWidth)); bounds.y = startY + row * (calendarHeight + CALENDAR_SPACING); bounds.width = calendarWidth; bounds.height = calendarHeight; // Paint the month if it intersects the clip. If we don't move // the calendar forward a month as it would have if paintMonth // was called. if (bounds.intersects(clip)) { paintMonth(g, bounds.x, bounds.y, bounds.width, bounds.height); } else { cal.add(Calendar.MONTH, 1); } } } // Restore the calendar. cal.setTimeInMillis(firstDisplayedDate); if (g2 != null && monthView.isAntialiased()) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); } } /** * Paints a month. It is assumed the calendar, <code>monthView.getCalendar()</code>, is already set to the * first day of the month to be painted. * * @param g Graphics object. * @param x x location of month * @param y y location of month * @param width width of month * @param height height of month */ @SuppressWarnings({"UnusedDeclaration"}) private void paintMonth(Graphics g, int x, int y, int width, int height) { Calendar cal = monthView.getCalendar(); int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); Rectangle clip = g.getClipBounds(); long day; int oldWeek = -1; int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); // Paint month name background. paintMonthStringBackground(g, x, y, width, boxPaddingY + monthBoxHeight + boxPaddingY); paintMonthStringForeground(g, x, y, width, boxPaddingY + monthBoxHeight + boxPaddingY); // Paint arrow buttons for traversing months if enabled. if (monthView.isTraversable()) { //draw the icons monthDownImage.paintIcon(monthView, g, x + arrowPaddingX, y + ((fullMonthBoxHeight - monthDownImage.getIconHeight()) / 2)); monthUpImage.paintIcon(monthView, g, x + width - arrowPaddingX - monthUpImage.getIconWidth(), y + ((fullMonthBoxHeight - monthDownImage.getIconHeight()) / 2)); } // Paint background of the short names for the days of the week. boolean showingWeekNumber = monthView.isShowingWeekNumber(); int tmpX = isLeftToRight ? x + (showingWeekNumber ? fullBoxWidth : 0) : x; int tmpY = y + fullMonthBoxHeight; int tmpWidth = width - (showingWeekNumber ? fullBoxWidth : 0); paintDayOfTheWeekBackground(g, tmpX, tmpY, tmpWidth, fullBoxHeight); // Paint short representation of day of the week. int dayIndex = monthView.getFirstDayOfWeek() - 1; Font oldFont = monthView.getFont(); g.setFont(derivedFont); g.setColor(monthView.getDaysOfTheWeekForeground()); FontMetrics fm = monthView.getFontMetrics(derivedFont); String[] daysOfTheWeek = monthView.getDaysOfTheWeek(); for (int i = 0; i < JXMonthView.DAYS_IN_WEEK; i++) { tmpX = isLeftToRight ? x + (i * fullBoxWidth) + boxPaddingX + (boxWidth / 2) - (fm.stringWidth(daysOfTheWeek[dayIndex]) / 2) : x + width - (i * fullBoxWidth) - boxPaddingX - (boxWidth / 2) - (fm.stringWidth(daysOfTheWeek[dayIndex]) / 2); if (showingWeekNumber) { tmpX += isLeftToRight ? fullBoxWidth : -fullBoxWidth; } tmpY = y + fullMonthBoxHeight + boxPaddingY + fm.getAscent(); g.drawString(daysOfTheWeek[dayIndex], tmpX, tmpY); dayIndex++; if (dayIndex == JXMonthView.DAYS_IN_WEEK) { dayIndex = 0; } } g.setFont(oldFont); if (showingWeekNumber) { tmpX = isLeftToRight ? x : x + width - fullBoxWidth; paintWeekOfYearBackground(g, tmpX, y + fullMonthBoxHeight + fullBoxHeight, fullBoxWidth, calendarHeight - (fullMonthBoxHeight + fullBoxHeight)); } if (monthView.isShowingLeadingDates()) { // Figure out how many days we need to move back for the leading days. int dayOfWeekViewIndex = getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK)); if (dayOfWeekViewIndex != 0) { // Move the calendar back and paint the leading days cal.add(Calendar.DAY_OF_MONTH, -dayOfWeekViewIndex); for (int i = 0; i < dayOfWeekViewIndex; i++) { // Paint a day calculateBoundsForDay(bounds, LEADING_DAY_OFFSET); day = cal.getTimeInMillis(); paintLeadingDayBackground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); paintLeadingDayForeground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); cal.add(Calendar.DAY_OF_MONTH, 1); } } } int oldY = -1; for (int i = 0; i < days; i++) { calculateBoundsForDay(bounds, NO_OFFSET); // Paint the week numbers if we're displaying them. if (showingWeekNumber && oldY != bounds.y) { oldY = bounds.y; int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); if (weekOfYear != oldWeek) { tmpX = isLeftToRight ? x : x + width - fullBoxWidth; paintWeekOfYearForeground(g, tmpX, bounds.y, fullBoxWidth, fullBoxHeight, weekOfYear); oldWeek = weekOfYear; } } if (bounds.intersects(clip)) { day = cal.getTimeInMillis(); // Paint bounding box around any date that falls within the // selection. if (monthView.isSelectedDate(day)) { // Keep track of the rectangle for the currently // selected date so we don't have to recalculate it // later when it becomes unselected. This is only // useful for SINGLE_SELECTION mode. if (monthView.getSelectionMode() == SelectionMode.SINGLE_SELECTION) { dirtyRect.x = bounds.x; dirtyRect.y = bounds.y; dirtyRect.width = bounds.width; dirtyRect.height = bounds.height; } } if (monthView.isUnselectableDate(day)) { paintUnselectableDayBackground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); paintUnselectableDayForeground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); } else if (monthView.isFlaggedDate(day)) { paintFlaggedDayBackground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); paintFlaggedDayForeground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); } else { paintDayBackground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); paintDayForeground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); } } cal.add(Calendar.DAY_OF_MONTH, 1); } if (monthView.isShowingTrailingDates()) { // Figure out how many days we need to paint for trailing days. cal.add(Calendar.DAY_OF_MONTH, -1); int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); if (JXMonthView.DAYS_IN_WEEK - 1 == getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK))) { weekOfMonth++; } cal.add(Calendar.DAY_OF_MONTH, 1); int daysToPaint = JXMonthView.DAYS_IN_WEEK * (WEEKS_IN_MONTH - weekOfMonth); daysToPaint += JXMonthView.DAYS_IN_WEEK - getDayOfWeekViewIndex(cal.get(Calendar.DAY_OF_WEEK)); if (daysToPaint != 0) { for (int i = 0; i < daysToPaint; i++) { // Paint a day calculateBoundsForDay(bounds, TRAILING_DAY_OFFSET); day = cal.getTimeInMillis(); paintTrailingDayBackground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); paintTrailingDayForeground(g, bounds.x, bounds.y, bounds.width, bounds.height, day); cal.add(Calendar.DAY_OF_MONTH, 1); } } // Move the calendar back to the first of the month cal.set(Calendar.DAY_OF_MONTH, 1); } } protected void paintDayOfTheWeekBackground(Graphics g, int x, int y, int width, int height) { int boxPaddingX = monthView.getBoxPaddingX(); g.drawLine(x + boxPaddingX, y + height - 1, x + width - boxPaddingX, y + height - 1); } protected void paintWeekOfYearBackground(Graphics g, int x, int y, int width, int height) { int boxPaddingY = monthView.getBoxPaddingY(); x = isLeftToRight ? x + width - 1 : x; g.drawLine(x, y + boxPaddingY, x, y + height - boxPaddingY); } /** * Paints the week of the year * * @param g Graphics object * @param x x-coordinate of upper left corner. * @param y y-coordinate of upper left corner. * @param width width of bounding box * @param height height of bounding box * @param weekOfYear week of the year */ @SuppressWarnings({"UNUSED_SYMBOL", "UnusedDeclaration"}) protected void paintWeekOfYearForeground(Graphics g, int x, int y, int width, int height, int weekOfYear) { String str = Integer.toString(weekOfYear); FontMetrics fm; g.setColor(weekOfTheYearForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); g.drawString(str, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(str) : x + boxPaddingX + boxWidth - fm.stringWidth(str) - 1, y + boxPaddingY + fm.getAscent()); } protected void paintMonthStringBackground(Graphics g, int x, int y, int width, int height) { // Modify bounds by the month string insets. Insets monthStringInsets = monthView.getMonthStringInsets(); x = isLeftToRight ? x + monthStringInsets.left : x + monthStringInsets.right; y = y + monthStringInsets.top; width = width - monthStringInsets.left - monthStringInsets.right; height = height - monthStringInsets.top - monthStringInsets.bottom; g.setColor(monthView.getMonthStringBackground()); g.fillRect(x, y, width, height); } protected void paintMonthStringForeground(Graphics g, int x, int y, int width, int height) { // Paint month name. Calendar cal = monthView.getCalendar(); Font oldFont = monthView.getFont(); // TODO: Calculating the bounds of the text dynamically so we can invoke // a popup for selecting the month/year to view. g.setFont(derivedFont); FontMetrics fm = monthView.getFontMetrics(derivedFont); int month = cal.get(Calendar.MONTH); String monthName = monthsOfTheYear[month]; String yearString = Integer.toString(cal.get(Calendar.YEAR)); Rectangle2D rect = fm.getStringBounds(monthName, g); monthStringBounds[month] = new Rectangle((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); int spaceWidth = (int) fm.getStringBounds(" ", g).getWidth(); rect = fm.getStringBounds(yearString, g); yearStringBounds[month] = new Rectangle((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); // END g.setColor(monthView.getMonthStringForeground()); int tmpX = x + (calendarWidth / 2) - ((monthStringBounds[month].width + yearStringBounds[month].width + spaceWidth) / 2); int tmpY = y + monthView.getBoxPaddingY() + ((monthBoxHeight - boxHeight) / 2) + fm.getAscent(); monthStringBounds[month].x = tmpX; yearStringBounds[month].x = (monthStringBounds[month].x + monthStringBounds[month].width + spaceWidth); paintMonthStringForeground(g,monthName, monthStringBounds[month].x, tmpY, yearString, yearStringBounds[month].x, tmpY); g.setFont(oldFont); } /** * Paints only text for month and year. No calculations made. Used by custom LAFs. * @param g Graphics to paint into. * @param monthName Name of the month. * @param monthX Month string x coordinate. * @param monthY Month string y coordinate. * @param yearName Name (number) of the year. * @param yearX Year string x coordinate. * @param yearY Year string y coordinate. */ protected void paintMonthStringForeground(Graphics g, String monthName, int monthX, int monthY, String yearName, int yearX, int yearY) { g.drawString(monthName, monthX, monthY); g.drawString(yearName, yearX, yearY); } /** * Paint the background for the specified day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the day being painted * @see org.jdesktop.swingx.calendar.JXMonthView#isSelectedDate * @see #isToday */ protected void paintDayBackground(Graphics g, int x, int y, int width, int height, long date) { if (monthView.isSelectedDate(date)) { g.setColor(monthView.getSelectedBackground()); g.fillRect(x, y, width, height); } // If the date is today make sure we draw it's background over the selected // background. if (isToday(date)) { g.setColor(monthView.getTodayBackground()); g.drawRect(x, y, width - 1, height - 1); } } /** * Paint the foreground for the specified day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the day being painted */ protected void paintDayForeground(Graphics g, int x, int y, int width, int height, long date) { String numericDay = dayOfMonthFormatter.format(date); g.setColor(monthView.getDayForeground(getDayOfTheWeek())); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); paintDayForeground(g, numericDay, isLeftToRight ? x + boxPaddingX + boxWidth : x + boxPaddingX + boxWidth - 1, y + boxPaddingY); } /** * Paints string of the day. No calculations made. Used by LAFs. * @param g Graphics to paint on. * @param dayName Text representation of the day. * @param x X coordinate of the upper left corner. * @param y Y coordinate of the upper left corner. */ protected void paintDayForeground(Graphics g, String dayName, int x, int y) { FontMetrics fm = g.getFontMetrics(); g.drawString(dayName, x - fm.stringWidth(dayName), y + fm.getAscent()); } /** * Paint the background for the specified flagged day. The default implementation just calls * <code>paintDayBackground</code>. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the flagged day being painted */ protected void paintFlaggedDayBackground(Graphics g, int x, int y, int width, int height, long date) { paintDayBackground(g, x, y, width, height, date); } /** * Paint the foreground for the specified flagged day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the flagged day being painted */ protected void paintFlaggedDayForeground(Graphics g, int x, int y, int width, int height, long date) { String numericDay = dayOfMonthFormatter.format(date); FontMetrics fm; int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); Font oldFont = monthView.getFont(); g.setColor(monthView.getFlaggedDayForeground()); g.setFont(derivedFont); fm = monthView.getFontMetrics(derivedFont); g.drawString(numericDay, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay): x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1, y + boxPaddingY + fm.getAscent()); g.setFont(oldFont); } /** * Paint the foreground for the specified unselectable day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the flagged day being painted */ protected void paintUnselectableDayBackground(Graphics g, int x, int y, int width, int height, long date) { paintDayBackground(g, x, y, width, height, date); } /** * Paint the foreground for the specified unselectable day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the flagged day being painted */ protected void paintUnselectableDayForeground(Graphics g, int x, int y, int width, int height, long date) { paintDayForeground(g, x, y, width, height, date); g.setColor(unselectableDayForeground); String numericDay = dayOfMonthFormatter.format(date); FontMetrics fm = monthView.getFontMetrics(derivedFont); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); width = fm.stringWidth(numericDay); height = fm.getAscent(); x = isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) : x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1; y = y + boxPaddingY; g.drawLine(x, y, x + width, y + height); g.drawLine(x + 1, y, x + width + 1, y + height); g.drawLine(x + width, y, x, y + height); g.drawLine(x + width - 1, y, x - 1, y + height); } /** * Paint the background for the specified leading day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the leading day being painted */ protected void paintLeadingDayBackground(Graphics g, int x, int y, int width, int height, long date) { paintDayBackground(g, x, y, width, height, date); } /** * Paint the foreground for the specified leading day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the leading day being painted */ protected void paintLeadingDayForeground(Graphics g, int x, int y, int width, int height, long date) { String numericDay = dayOfMonthFormatter.format(date); FontMetrics fm; g.setColor(leadingDayForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); g.drawString(numericDay, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) : x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1, y + boxPaddingY + fm.getAscent()); } /** * Paint the background for the specified trailing day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the leading day being painted */ protected void paintTrailingDayBackground(Graphics g, int x, int y, int width, int height, long date) { paintLeadingDayBackground(g, x, y, width, height, date); } /** * Paint the foreground for the specified trailing day. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param date long value representing the leading day being painted */ protected void paintTrailingDayForeground(Graphics g, int x, int y, int width, int height, long date) { String numericDay = dayOfMonthFormatter.format(date); FontMetrics fm; g.setColor(trailingDayForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); g.drawString(numericDay, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) : x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1, y + boxPaddingY + fm.getAscent()); } private long cleanupDate(long date) { Calendar cal = monthView.getCalendar(); cal.setTimeInMillis(date); // We only want to compare the day, month and year // so reset all other values to 0. cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } protected void paintBackground(final Rectangle clip, final Graphics g) { if (monthView.isOpaque()) { g.setColor(monthView.getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); } } private class Handler implements ComponentListener, MouseListener, MouseMotionListener, LayoutManager, PropertyChangeListener, DateSelectionListener { private boolean armed; private long startDate; private long endDate; public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); if (!monthView.isEnabled()) { return; } if (!monthView.hasFocus() && monthView.isFocusable()) { monthView.requestFocusInWindow(); } // Check if one of the month traverse buttons was pushed. if (monthView.isTraversable()) { int arrowType = getTraversableButtonAt(e.getX(), e.getY()); if (arrowType == JXMonthView.MONTH_DOWN) { Date lowerBound = monthView.getSelectionModel().getLowerBound(); if (lowerBound == null || lowerBound.getTime() < firstDisplayedDate) { monthView.setFirstDisplayedDate(DateUtils.getPreviousMonth(firstDisplayedDate)); calculateDirtyRectForSelection(); return; } } else if (arrowType == JXMonthView.MONTH_UP) { Date upperBound = monthView.getSelectionModel().getUpperBound(); if (upperBound == null || upperBound.getTime() > lastDisplayedDate) { monthView.setFirstDisplayedDate(DateUtils.getNextMonth(firstDisplayedDate)); calculateDirtyRectForSelection(); return; } } } SelectionMode selectionMode = monthView.getSelectionMode(); if (selectionMode == SelectionMode.NO_SELECTION) { return; } long selected = monthView.getDayAt(e.getX(), e.getY()); if (selected == -1) { return; } // Update the selected dates. startDate = selected; endDate = selected; if (selectionMode == SelectionMode.SINGLE_INTERVAL_SELECTION || selectionMode == SelectionMode.WEEK_INTERVAL_SELECTION || selectionMode == SelectionMode.MULTIPLE_INTERVAL_SELECTION) { pivotDate = selected; } if (selectionMode == SelectionMode.MULTIPLE_INTERVAL_SELECTION && e.isControlDown()) { monthView.addSelectionInterval(new Date(startDate), new Date(endDate)); } else { monthView.setSelectionInterval(new Date(startDate), new Date(endDate)); } // Arm so we fire action performed on mouse release. armed = true; } public void mouseReleased(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); if (!monthView.isEnabled()) { return; } if (!monthView.hasFocus() && monthView.isFocusable()) { monthView.requestFocusInWindow(); } if (armed) { monthView.postActionEvent(); } armed = false; } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseDragged(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); SelectionMode selectionMode = monthView.getSelectionMode(); if (!monthView.isEnabled() || selectionMode == SelectionMode.NO_SELECTION) { return; } long selected = monthView.getDayAt(e.getX(), e.getY()); if (selected == -1) { return; } long oldStart = startDate; long oldEnd = endDate; if (selectionMode == SelectionMode.SINGLE_SELECTION) { if (selected == oldStart) { return; } startDate = selected; endDate = selected; } else { if (selected <= pivotDate) { startDate = selected; endDate = pivotDate; } else if (selected > pivotDate) { startDate = pivotDate; endDate = selected; } } if (oldStart == startDate && oldEnd == endDate) { return; } if (selectionMode == SelectionMode.MULTIPLE_INTERVAL_SELECTION && e.isControlDown()) { monthView.addSelectionInterval(new Date(startDate), new Date(endDate)); } else { monthView.setSelectionInterval(new Date(startDate), new Date(endDate)); } // Set trigger. armed = true; } public void mouseMoved(MouseEvent e) {} public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { layoutContainer(parent); return new Dimension(dim); } public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } public void layoutContainer(Container parent) { // Loop through year and get largest representation of the month. // Keep track of the longest month so we can loop through it to // determine the width of a date box. int currDays; int longestMonth = 0; int daysInLongestMonth = 0; int currWidth; int longestMonthWidth = 0; // We use a bold font for figuring out size constraints since // it's larger and flaggedDates will be noted in this style. FontMetrics fm = monthView.getFontMetrics(derivedFont); Calendar cal = monthView.getCalendar(); cal.set(Calendar.MONTH, cal.getMinimum(Calendar.MONTH)); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < cal.getMaximum(Calendar.MONTH); i++) { currWidth = fm.stringWidth(monthsOfTheYear[i]); if (currWidth > longestMonthWidth) { longestMonthWidth = currWidth; } currDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (currDays > daysInLongestMonth) { longestMonth = cal.get(Calendar.MONTH); daysInLongestMonth = currDays; } cal.add(Calendar.MONTH, 1); } // Loop through the days of the week and adjust the box width // accordingly. boxHeight = fm.getHeight(); String[] daysOfTheWeek = monthView.getDaysOfTheWeek(); for (String dayOfTheWeek : daysOfTheWeek) { currWidth = fm.stringWidth(dayOfTheWeek); if (currWidth > boxWidth) { boxWidth = currWidth; } } // Loop through longest month and get largest representation of the day // of the month. cal.set(Calendar.MONTH, longestMonth); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < daysInLongestMonth; i++) { currWidth = fm.stringWidth( dayOfMonthFormatter.format(cal.getTime())); if (currWidth > boxWidth) { boxWidth = currWidth; } cal.add(Calendar.DAY_OF_MONTH, 1); } // If we are displaying week numbers find the largest displayed week number. boolean showingWeekNumber = monthView.isShowingWeekNumber(); if (showingWeekNumber) { int val = cal.getActualMaximum(Calendar.WEEK_OF_YEAR); currWidth = fm.stringWidth(Integer.toString(val)); if (currWidth > boxWidth) { boxWidth = currWidth; } } // If the calendar is traversable, check the icon heights and // adjust the month box height accordingly. monthBoxHeight = boxHeight; if (monthView.isTraversable()) { int newHeight = monthDownImage.getIconHeight() + arrowPaddingY + arrowPaddingY; if (newHeight > monthBoxHeight) { monthBoxHeight = newHeight; } } // Modify boxWidth if month string is longer int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); dim.width = (boxWidth + (2 * boxPaddingX)) * JXMonthView.DAYS_IN_WEEK; if (dim.width < longestMonthWidth) { double diff = longestMonthWidth - dim.width; if (monthView.isTraversable()) { diff += monthDownImage.getIconWidth() + monthUpImage.getIconWidth() + (arrowPaddingX * 4); } boxWidth += Math.ceil(diff / (double)JXMonthView.DAYS_IN_WEEK); } // Keep track of a full box height/width and full month box height fullBoxWidth = boxWidth + boxPaddingX + boxPaddingX; fullBoxHeight = boxHeight + boxPaddingY + boxPaddingY; fullMonthBoxHeight = monthBoxHeight + boxPaddingY + boxPaddingY; // Keep track of calendar width and height for use later. calendarWidth = fullBoxWidth * JXMonthView.DAYS_IN_WEEK; if (showingWeekNumber) { calendarWidth += fullBoxWidth; } calendarHeight = (fullBoxHeight * 7) + fullMonthBoxHeight; // Calculate minimum width/height for the component. int prefRows = monthView.getPreferredRows(); dim.height = (calendarHeight * prefRows) + (CALENDAR_SPACING * (prefRows - 1)); int prefCols = monthView.getPreferredCols(); dim.width = (calendarWidth * prefCols) + (CALENDAR_SPACING * (prefCols - 1)); // Add insets to the dimensions. Insets insets = monthView.getInsets(); dim.width += insets.left + insets.right; dim.height += insets.top + insets.bottom; // Restore calendar. cal.setTimeInMillis(firstDisplayedDate); calculateNumDisplayedCals(); calculateStartPosition(); if (!monthView.getSelectionModel().isSelectionEmpty()) { long startDate = selection.first().getTime(); if (startDate > lastDisplayedDate || startDate < firstDisplayedDate) { // Already does the recalculation for the dirty rect. monthView.ensureDateVisible(startDate); } else { calculateDirtyRectForSelection(); } } } public void propertyChange(PropertyChangeEvent evt) { String property = evt.getPropertyName(); if ("componentOrientation".equals(property)) { isLeftToRight = monthView.getComponentOrientation().isLeftToRight(); monthView.revalidate(); calculateStartPosition(); calculateDirtyRectForSelection(); } else if (JXMonthView.ENSURE_DATE_VISIBILITY.equals(property)) { calculateDirtyRectForSelection(); } else if (JXMonthView.SELECTION_MODEL.equals(property)) { DateSelectionModel selectionModel = (DateSelectionModel) evt.getOldValue(); selectionModel.removeDateSelectionListener(getHandler()); selectionModel = (DateSelectionModel) evt.getNewValue(); selectionModel.addDateSelectionListener(getHandler()); } else if (JXMonthView.FIRST_DISPLAYED_DATE.equals(property)) { firstDisplayedDate = (Long)evt.getNewValue(); } else if (JXMonthView.FIRST_DISPLAYED_MONTH.equals(property)) { firstDisplayedMonth = (Integer)evt.getNewValue(); } else if (JXMonthView.FIRST_DISPLAYED_YEAR.equals(property)) { firstDisplayedYear = (Integer)evt.getNewValue(); } else if ("today".equals(property)) { today = (Long)evt.getNewValue(); } else if (JXMonthView.BOX_PADDING_X.equals(property) || JXMonthView.BOX_PADDING_Y.equals(property) || JXMonthView.TRAVERSABLE.equals(property) || JXMonthView.DAYS_OF_THE_WEEK.equals(property) || "border".equals(property) || JXMonthView.WEEK_NUMBER.equals(property)) { monthView.revalidate(); } else if ("font".equals(property)) { derivedFont = createDerivedFont(); monthView.revalidate(); } } public void componentResized(ComponentEvent e) { monthView.revalidate(); monthView.repaint(); } public void componentMoved(ComponentEvent e) {} public void componentShown(ComponentEvent e) {} public void componentHidden(ComponentEvent e) {} public void valueChanged(DateSelectionEvent ev) { selection = ev.getSelection(); // repaint old dirty region monthView.repaint(dirtyRect); // calculate new dirty region based on selection calculateDirtyRectForSelection(); // repaint new selection monthView.repaint(dirtyRect); } } /** * Class that supports keyboard traversal of the JXMonthView component. */ private class KeyboardAction extends AbstractAction { public static final int ACCEPT_SELECTION = 0; public static final int CANCEL_SELECTION = 1; public static final int SELECT_PREVIOUS_DAY = 2; public static final int SELECT_NEXT_DAY = 3; public static final int SELECT_DAY_PREVIOUS_WEEK = 4; public static final int SELECT_DAY_NEXT_WEEK = 5; public static final int ADJUST_SELECTION_PREVIOUS_DAY = 6; public static final int ADJUST_SELECTION_NEXT_DAY = 7; public static final int ADJUST_SELECTION_PREVIOUS_WEEK = 8; public static final int ADJUST_SELECTION_NEXT_WEEK = 9; private int action; public KeyboardAction(int action) { this.action = action; } public void actionPerformed(ActionEvent ev) { SelectionMode selectionMode = monthView.getSelectionMode(); if (selectionMode != SelectionMode.NO_SELECTION) { if (!isUsingKeyboard()) { originalDateSpan = monthView.getSelection(); } if (action >= ACCEPT_SELECTION && action <= CANCEL_SELECTION && isUsingKeyboard()) { if (action == CANCEL_SELECTION) { // Restore the original selection. if (!originalDateSpan.isEmpty()) { monthView.setSelectionInterval(originalDateSpan.first(), originalDateSpan.last()); } else { monthView.clearSelection(); } monthView.postActionEvent(); } else { // Accept the keyboard selection. monthView.postActionEvent(); } setUsingKeyboard(false); } else if (action >= SELECT_PREVIOUS_DAY && action <= SELECT_DAY_NEXT_WEEK) { setUsingKeyboard(true); pivotDate = -1; traverse(action); } else if (selectionMode == SelectionMode.SINGLE_INTERVAL_SELECTION && action >= ADJUST_SELECTION_PREVIOUS_DAY && action <= ADJUST_SELECTION_NEXT_WEEK) { setUsingKeyboard(true); addToSelection(action); } } } private void traverse(int action) { long oldStart = selection.isEmpty() ? System.currentTimeMillis() : selection.first().getTime(); Calendar cal = monthView.getCalendar(); cal.setTimeInMillis(oldStart); switch (action) { case SELECT_PREVIOUS_DAY: cal.add(Calendar.DAY_OF_MONTH, -1); break; case SELECT_NEXT_DAY: cal.add(Calendar.DAY_OF_MONTH, 1); break; case SELECT_DAY_PREVIOUS_WEEK: cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); break; case SELECT_DAY_NEXT_WEEK: cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); break; } long newStartDate = cal.getTimeInMillis(); if (newStartDate != oldStart) { final Date startDate = new Date(newStartDate); monthView.setSelectionInterval(startDate, startDate); monthView.ensureDateVisible(newStartDate); } // Restore the original time value. cal.setTimeInMillis(firstDisplayedDate); } /** * If we are in a mode that allows for range selection this method * will extend the currently selected range. * * NOTE: This may not be the expected behavior for the keyboard controls * and we ay need to update this code to act in a way that people expect. * * @param action action for adjusting selection */ private void addToSelection(int action) { long newStartDate; long newEndDate; long selectionStart; long selectionEnd; if (!selection.isEmpty()) { newStartDate = selectionStart = selection.first().getTime(); newEndDate = selectionEnd = selection.last().getTime(); } else { newStartDate = selectionStart = cleanupDate(System.currentTimeMillis()); newEndDate = selectionEnd = newStartDate; } if (-1 == pivotDate) { pivotDate = newStartDate; } boolean isForward = true; Calendar cal = monthView.getCalendar(); switch (action) { case ADJUST_SELECTION_PREVIOUS_DAY: if (newEndDate <= pivotDate) { cal.setTimeInMillis(newStartDate); cal.add(Calendar.DAY_OF_MONTH, -1); newStartDate = cal.getTimeInMillis(); } else { cal.setTimeInMillis(newEndDate); cal.add(Calendar.DAY_OF_MONTH, -1); newEndDate = cal.getTimeInMillis(); } isForward = false; break; case ADJUST_SELECTION_NEXT_DAY: if (newStartDate >= pivotDate) { cal.setTimeInMillis(newEndDate); cal.add(Calendar.DAY_OF_MONTH, 1); newStartDate = pivotDate; newEndDate = cal.getTimeInMillis(); } else { cal.setTimeInMillis(newStartDate); cal.add(Calendar.DAY_OF_MONTH, 1); newStartDate = cal.getTimeInMillis(); } break; case ADJUST_SELECTION_PREVIOUS_WEEK: if (newEndDate <= pivotDate) { cal.setTimeInMillis(newStartDate); cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); newStartDate = cal.getTimeInMillis(); } else { cal.setTimeInMillis(newEndDate); cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); long newTime = cal.getTimeInMillis(); if (newTime <= pivotDate) { newStartDate = newTime; newEndDate = pivotDate; } else { newEndDate = cal.getTimeInMillis(); } } isForward = false; break; case ADJUST_SELECTION_NEXT_WEEK: if (newStartDate >= pivotDate) { cal.setTimeInMillis(newEndDate); cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); newEndDate = cal.getTimeInMillis(); } else { cal.setTimeInMillis(newStartDate); cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); long newTime = cal.getTimeInMillis(); if (newTime >= pivotDate) { newStartDate = pivotDate; newEndDate = newTime; } else { newStartDate = cal.getTimeInMillis(); } } break; } if (newStartDate != selectionStart || newEndDate != selectionEnd) { monthView.setSelectionInterval(new Date(newStartDate), new Date(newEndDate)); monthView.ensureDateVisible(isForward ? newEndDate : newStartDate); } // Restore the original time value. cal.setTimeInMillis(firstDisplayedDate); } } }
package org.intermine.api.profile; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.lang.StringUtils; import org.intermine.api.config.ClassKeyHelper; import org.intermine.api.search.Scope; import org.intermine.api.search.SearchRepository; import org.intermine.api.search.WebSearchable; import org.intermine.api.tag.TagTypes; import org.intermine.api.template.ApiTemplate; import org.intermine.api.tracker.TrackerDelegate; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; /** * Class to represent a user of the webapp * * @author Mark Woodbridge * @author Thomas Riley */ public class Profile { protected ProfileManager manager; protected String username; protected Integer userId; protected String password; protected Map<String, SavedQuery> savedQueries = new TreeMap<String, SavedQuery>(); protected Map<String, InterMineBag> savedBags = new TreeMap<String, InterMineBag>(); protected Map<String, ApiTemplate> savedTemplates = new TreeMap<String, ApiTemplate>(); protected Map<String, InterMineBag> savedInvalidBags = new TreeMap<String, InterMineBag>(); protected Map queryHistory = new ListOrderedMap(); private boolean savingDisabled; private final SearchRepository searchRepository; private String token; /** * True if this account is purely local. False if it was created * in reference to another authenticator, such as an OpenID provider. */ private final boolean isLocal; /** * Construct a Profile * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedTemplates the saved templates for this profile * @param token The token to use as an API key */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal) { this.manager = manager; this.username = username; this.userId = userId; this.password = password; this.isLocal = isLocal; if (savedQueries != null) { this.savedQueries.putAll(savedQueries); } if (savedBags != null) { this.savedBags.putAll(savedBags); } if (savedTemplates != null) { this.savedTemplates.putAll(savedTemplates); } searchRepository = new SearchRepository(this, Scope.USER); this.token = token; } /** * Construct a Profile * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedInvalidBags the saved bags which type doesn't match with the model * @param savedTemplates the saved templates for this profile * @param token The token to use as an API key */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, InterMineBag> savedInvalidBags, Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal) { this(manager, username, userId, password, savedQueries, savedBags, savedTemplates, token, isLocal); this.savedInvalidBags = savedInvalidBags; } /** * Construct a profile without an API key * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedTemplates the saved templates for this profile */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, ApiTemplate> savedTemplates, boolean isLocal) { this(manager, username, userId, password, savedQueries, savedBags, savedTemplates, null, isLocal); } /** * Return the ProfileManager that was passed to the constructor. * @return the ProfileManager */ public ProfileManager getProfileManager() { return manager; } /** * Get the value of username * @return the value of username */ public String getUsername() { return username; } /** * Return a first part of the username before the "@" sign (used in metabolicMine) * @author radek * * @return String */ public String getName() { int atPos = username.indexOf("@"); if (atPos > 0) { return username.substring(0, atPos); } else { return username; } } /** * Return true if and only if the user is logged is (and the Profile will be written to the * userprofile). * @return Return true if logged in */ public boolean isLoggedIn() { return getUsername() != null; } /** * Return true if and only if the user logged is superuser * @return Return true if superuser */ public boolean isSuperuser() { if (username != null && manager.getSuperuser().equals(username)) { return true; } return false; } /** * Get the value of userId * @return an Integer */ public Integer getUserId() { return userId; } /** * Set the userId * * @param userId an Integer */ public void setUserId(Integer userId) { this.userId = userId; } /** * Get the value of password * @return the value of password */ public String getPassword() { return password; } /** * Disable saving until enableSaving() is called. This is called before many templates or * queries need to be saved or deleted because each call to ProfileManager.saveProfile() is * slow. */ public void disableSaving() { savingDisabled = true; } /** * Re-enable saving when saveTemplate(), deleteQuery() etc. are called. Also calls * ProfileManager.saveProfile() to write this Profile to the database and rebuilds the * template description index. */ public void enableSaving() { savingDisabled = false; if (manager != null) { manager.saveProfile(this); } reindex(TagTypes.TEMPLATE); reindex(TagTypes.BAG); } /** * Get the users saved templates * @return saved templates */ public Map<String, ApiTemplate> getSavedTemplates() { return Collections.unmodifiableMap(savedTemplates); } /** * Save a template * @param name the template name * @param template the template */ public void saveTemplate(String name, ApiTemplate template) { savedTemplates.put(name, template); if (manager != null && !savingDisabled) { manager.saveProfile(this); reindex(TagTypes.TEMPLATE); } } /** * get a template * @param name the template * @return template */ public ApiTemplate getTemplate(String name) { return savedTemplates.get(name); } /** * Delete a template and its tags, rename the template tracks adding the prefix "deleted_" * to the previous name. If trackerDelegate is null, the template tracks are not renamed * @param name the template name * @param trackerDelegate used to rename the template tracks. */ public void deleteTemplate(String name, TrackerDelegate trackerDelegate, boolean deleteTracks) { savedTemplates.remove(name); if (manager != null) { if (!savingDisabled) { manager.saveProfile(this); reindex(TagTypes.TEMPLATE); } } TagManager tagManager = getTagManager(); tagManager.deleteObjectTags(name, TagTypes.TEMPLATE, username); if (trackerDelegate != null && deleteTracks) { trackerDelegate.updateTemplateName(name, "deleted_" + name); } } /** * Get the value of savedQueries * @return the value of savedQueries */ public Map<String, SavedQuery> getSavedQueries() { return Collections.unmodifiableMap(savedQueries); } /** * Save a query * @param name the query name * @param query the query */ public void saveQuery(String name, SavedQuery query) { savedQueries.put(name, query); if (manager != null && !savingDisabled) { manager.saveProfile(this); } } /** * Delete a query * @param name the query name */ public void deleteQuery(String name) { savedQueries.remove(name); if (manager != null && !savingDisabled) { manager.saveProfile(this); } } /** * Get the session query history. * @return map from query name to SavedQuery */ public Map<String, SavedQuery> getHistory() { return Collections.unmodifiableMap(queryHistory); } /** * Save a query to the query history. * @param query the SavedQuery to save to the history */ public void saveHistory(SavedQuery query) { queryHistory.put(query.getName(), query); } /** * Remove an item from the query history. * @param name the of the SavedQuery from the history */ public void deleteHistory(String name) { queryHistory.remove(name); } /** * Rename an item in the history. * @param oldName the name of the old item * @param newName the new name */ public void renameHistory(String oldName, String newName) { Map<String, SavedQuery> newMap = new ListOrderedMap(); Iterator<String> iter = queryHistory.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); SavedQuery sq = (SavedQuery) queryHistory.get(name); if (name.equals(oldName)) { sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery()); } newMap.put(sq.getName(), sq); } queryHistory = newMap; } /** * Get the value of savedBags * @return the value of savedBags */ public Map<String, InterMineBag> getSavedBags() { return Collections.unmodifiableMap(savedBags); } /** * Get the saved bags in a map of "status key" -> map of lists * @return */ public Map<String, Map<String, InterMineBag>> getSavedBagsByStatus() { Map<String, Map<String, InterMineBag>> result = new LinkedHashMap<String, Map<String, InterMineBag>>(); // maintain order on the JSP page result.put("NOT_CURRENT", new HashMap<String, InterMineBag>()); result.put("TO_UPGRADE", new HashMap<String, InterMineBag>()); result.put("CURRENT", new HashMap<String, InterMineBag>()); for (InterMineBag bag : savedBags.values()) { String state = bag.getState(); // XXX: this can go pear shaped if new states are introduced Map<String, InterMineBag> stateMap = result.get(state); stateMap.put(bag.getName(), bag); } return result; } /** * Get the value of savedBags current * @return the value of savedBags */ public Map<String, InterMineBag> getCurrentSavedBags() { Map<String, InterMineBag> clone = new HashMap<String, InterMineBag>(); clone.putAll(savedBags); for (InterMineBag bag : savedBags.values()) { if (!bag.isCurrent()) { clone.remove(bag.getName()); } } return clone; } /** * Stores a new bag in the profile. Note that bags are always present in the user profile * database, so this just adds the bag to the in-memory list of this profile. * * @param name the name of the bag * @param bag the InterMineBag object */ public void saveBag(String name, InterMineBag bag) { if (StringUtils.isBlank(name)) { throw new RuntimeException("No name specified for the list to save."); } savedBags.put(name, bag); reindex(TagTypes.BAG); } /** * Create a bag and save it to the userprofile database. * * @param name the bag name * @param type the bag type * @param description the bag description * @param classKeys the classKeys used to obtain the primary identifier field * @return the new bag * @throws ObjectStoreException if something goes wrong */ public InterMineBag createBag(String name, String type, String description, Map<String, List<FieldDescriptor>> classKeys) throws ObjectStoreException { ObjectStore os = manager.getProductionObjectStore(); ObjectStoreWriter uosw = manager.getProfileObjectStoreWriter(); List<String> keyFielNames = ClassKeyHelper.getKeyFieldNames( classKeys, type); InterMineBag bag = new InterMineBag(name, type, description, new Date(), BagState.CURRENT, os, userId, uosw, keyFielNames); savedBags.put(name, bag); reindex(TagTypes.BAG); return bag; } /** * Delete a bag from the user account, if user is logged in also deletes from the userprofile * database. * If there is no such bag associated with the account, no action is performed. * @param name the bag name * @throws ObjectStoreException if problems deleting bag */ public void deleteBag(String name) throws ObjectStoreException { if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) { throw new BagDoesNotExistException(name + " not found"); } InterMineBag bagToDelete; if (savedBags.containsKey(name)) { bagToDelete = savedBags.get(name); savedBags.remove(name); } else { bagToDelete = savedInvalidBags.get(name); savedInvalidBags.remove(name); } if (isLoggedIn()) { bagToDelete.delete(); } TagManager tagManager = getTagManager(); tagManager.deleteObjectTags(name, TagTypes.BAG, username); reindex(TagTypes.BAG); } /** * Update the type of bag. * If there is no such bag associated with the account, no action is performed. * @param name the bag name * @param newType the type to set * @throws ObjectStoreException if problems deleting bag */ public void updateBagType(String name, String newType) throws ObjectStoreException { if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) { throw new BagDoesNotExistException(name + " not found"); } InterMineBag bagToUpdate; if (savedBags.containsKey(name)) { bagToUpdate = savedBags.get(name); } else { bagToUpdate = savedInvalidBags.get(name); } if (isLoggedIn()) { bagToUpdate.setType(newType); } } /** * Rename an existing bag, throw exceptions when bag doesn't exist of if new name already * exists. Moves tags from old bag to new bag. * @param oldName the bag to rename * @param newName new name for the bag * @throws ObjectStoreException if problems storing */ public void renameBag(String oldName, String newName) throws ObjectStoreException { if (!savedBags.containsKey(oldName)) { throw new BagDoesNotExistException("Attempting to rename " + oldName); } if (savedBags.containsKey(newName)) { throw new ProfileAlreadyExistsException("Attempting to rename a bag to a new name that" + " already exists: " + newName); } InterMineBag bag = savedBags.get(oldName); savedBags.remove(oldName); bag.setName(newName); saveBag(newName, bag); moveTagsToNewObject(oldName, newName, TagTypes.BAG); } /** * Update an existing template, throw exceptions when template doesn't exist. * Moves tags from old template to new template. * @param oldName the template to rename * @param template the new template * @throws ObjectStoreException if problems storing */ public void updateTemplate(String oldName, ApiTemplate template) throws ObjectStoreException { if (!savedTemplates.containsKey(oldName)) { throw new IllegalArgumentException("Attempting to rename a template that doesn't" + " exist: " + oldName); } savedTemplates.remove(oldName); saveTemplate(template.getName(), template); if (!oldName.equals(template.getName())) { moveTagsToNewObject(oldName, template.getName(), TagTypes.TEMPLATE); } } private void moveTagsToNewObject(String oldTaggedObj, String newTaggedObj, String type) { TagManager tagManager = getTagManager(); List<Tag> tags = tagManager.getTags(null, oldTaggedObj, type, username); for (Tag tag : tags) { tagManager.addTag(tag.getTagName(), newTaggedObj, type, username); tagManager.deleteTag(tag); } } private TagManager getTagManager() { return new TagManagerFactory(manager).getTagManager(); } /** * Create a map from category name to a list of templates contained * within that category. */ private void reindex(String type) { // We also take this opportunity to index the user's template queries, bags, etc. searchRepository.addWebSearchables(type); } /** * Return a WebSearchable Map for the given type. * @param type the type (from TagTypes) * @return the Map */ public Map<String, ? extends WebSearchable> getWebSearchablesByType(String type) { if (type.equals(TagTypes.TEMPLATE)) { return savedTemplates; } if (type.equals(TagTypes.BAG)) { return getSavedBags(); } throw new RuntimeException("unknown type: " + type); } /** * Get the SearchRepository for this Profile. * @return the SearchRepository for the user */ public SearchRepository getSearchRepository() { return searchRepository; } /** * Get the user's API key token. * @return */ public String getApiKey() { return token; } /** * Set the API token for this user, and save it in * the backing db. * @param token */ public void setApiKey(String token) { this.token = token; manager.saveProfile(this); } /** * Returns true if this is a local account, and not, for * example, an OpenID account. * @return Whether or not this is a local account. */ public boolean isLocal() { return this.isLocal; } /** * Return a single use API key for this profile * @return */ public String getSingleUseKey() { return manager.generateSingleUseKey(this); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4915.ArcadeDriveRobot; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc4915.ArcadeDriveRobot.commands.*; import org.usfirst.frc4915.ArcadeDriveRobot.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; public static Harvester harvester; public static AirCompressor airCompressor; public static Launcher launcher; public static Gyroscope gyroscope; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static final String VERSION = "v1.08.03"; // Adds IntakeDown and IntakeUp commands // Adds Magnetic Switch // Changed buttons on Joystick to activate the Intake Down and Intake Up instead of Extend/Retract Pneumatics // Fixed exceptions when there is no gyroscope /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); harvester = new Harvester(); airCompressor = new AirCompressor(); launcher = new Launcher(); gyroscope = new Gyroscope(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // This MUST be here. If the OI creates Commands (which it very likely // will), constructing it during the construction of CommandBase (from // which commands extend), subsystems are not guaranteed to be // yet. Thus, their requires() statements may grab null pointers. Bad // news. Don't move it. oi = new OI(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommand(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS System.out.println(VERSION); SendUserMessages.display(1, VERSION); //tests the SendUserMessages, 30 characters SendUserMessages.display(2, "Inverted both motors"); //tests the SendUserMessages, 30 characters if (gyroscope != null) { gyroscope.reset(); } if (airCompressor != null) { airCompressor.start(); } driveTrain.setSafetyEnabled(false); driveTrain.joystickThrottle = driveTrain.modifyThrottle(); SmartDashboard.putData(Scheduler.getInstance()); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) { autonomousCommand.start(); } } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) { autonomousCommand.cancel(); } SmartDashboard.putBoolean("Pressure Switch", RobotMap.airCompressorCompressor.getPressureSwitchValue()); // Makes our throttle from the original [-1,1] to [.1,1] // SmartDashboard.putNumber("Z Axis ", oi.joystickDrive.getAxis(Joystick.AxisType.kZ)); // Attack Joystick Throttle SmartDashboard.putBoolean("Gearbox Pneumatics", launcher.getStatePneumatics()); SmartDashboard.putBoolean("Magnetic Switch value:", harvester.getMagneticSwitchPneumatics()); SmartDashboard.putBoolean("Harvester Limit Switch is Ball Loaded: ", harvester.getLimitSwitchBallLoaded()); SmartDashboard.putBoolean("Harvester Intake down", !harvester.getMagneticSwitchPneumatics()); // fully extended is false -> true SmartDashboard.putBoolean("Harvester Intake up", harvester.getMagneticSwitchPneumatics()); // fully retraced is true -> true SmartDashboard.putNumber("Gyroscope", gyroscope.getAngle()); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package ca.ualberta.cs.cmput301t02project; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.core.Get; import io.searchbox.core.Index; import io.searchbox.core.Search; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import android.accounts.NetworkErrorException; import ca.ualberta.cs.cmput301t02project.model.CommentModel; import ca.ualberta.cs.cmput301t02project.model.StorageModel; import com.searchly.jestdroid.DroidClientConfig; import com.searchly.jestdroid.JestClientFactory; public class Server { private static final String serverUri = "http://cmput301.softwareprocess.es:8080/"; private JestClient client; private User user; public Server() { //TODO Add custom Gson here to clientConfig.Builder DroidClientConfig clientConfig = new DroidClientConfig.Builder(serverUri).multiThreaded(true).build(); JestClientFactory jestClientFactory = new JestClientFactory(); jestClientFactory.setDroidClientConfig(clientConfig); client = jestClientFactory.getObject(); } public void post(final CommentModel comment) { Thread thread = new Thread() { @Override public void run() { try { Index index = new Index.Builder(comment).index("cmput301w14t02").type("comments").id(comment.getId()).build(); JestResult result = client.execute(index); String id = result.getJsonObject().get("_id").getAsString(); comment.setId(id); index = new Index.Builder(comment).index("cmput301w14t02").type("comments").id(comment.getId()).build(); result = client.execute(index); if(!result.isSucceeded()) { throw new NetworkErrorException(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } finally { client.shutdownClient(); } } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public ArrayList<CommentModel> pull(final ArrayList<String> idList) { final ArrayList<CommentModel> commentList = new ArrayList<CommentModel>(); Thread thread = new Thread() { @Override public void run() { for(String Id:idList) { Get get = new Get.Builder("cmput301w14t02", Id).type("comments").build(); JestResult result = null; try { result = client.execute(get); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } CommentModel comment = result.getSourceAsObject(CommentModel.class); commentList.add(comment); } } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return commentList; } public ArrayList<CommentModel> pullTopLevel() { final ArrayList<CommentModel> commentList = new ArrayList<CommentModel>(); Thread thread = new Thread() { @Override public void run() { if(true) { String query = "{\"size\": 1000, \"query\": {\"term\": {\"topLevelComment\": \"True\"}}}"; Search search = new Search.Builder(query).addIndex("cmput301w14t02").addType("comments").build(); JestResult result = null; try { result = client.execute(search); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } commentList.addAll((ArrayList<CommentModel>) result.getSourceAsObjectList(CommentModel.class)); } else { StorageModel storage = new StorageModel(); //commentList = storage.retrieveCachedComments(context, FILENAME) } } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return commentList; } private static boolean isConnectionAvailable() { try { return InetAddress.getByName(serverUri).isReachable(300); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public void postUser(final User user) { Thread thread = new Thread() { @Override public void run() { try { Index index = new Index.Builder(user).index("cmput301w14t02").type("users").id(user.getId()).build(); JestResult result = client.execute(index); String id = result.getJsonObject().get("_id").getAsString(); user.setId(id); index = new Index.Builder(user).index("cmput301w14t02").type("users").id(user.getId()).build(); result = client.execute(index); if(!result.isSucceeded()) { throw new NetworkErrorException(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } finally { client.shutdownClient(); } } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public User pullUser(final String username) { Thread thread = new Thread() { @Override public void run() { String query = "{\"size\": 1000, \"query\": {\"term\": {\"username\": \""+ username +"\"}}}"; Search search = new Search.Builder(query).addIndex("cmput301w14t02").addType("users").build(); JestResult result = null; try { result = client.execute(search); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } user = result.getSourceAsObject(User.class); } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return user; } }
package com.logistics.activity; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.apache.http.Header; import me.maxwin.view.XListView; import me.maxwin.view.XListView.IXListViewListener; import roboguice.activity.RoboActivity; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import com.google.inject.Inject; import com.logistics.R; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.annotation.SuppressLint; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; @SuppressLint("WorldReadableFiles") @ContentView(R.layout.activity_map) public class MapActivity extends RoboActivity implements IXListViewListener{ public static final String TAG = MapActivity.class.getSimpleName(); public static final int MODE_PRIVATE = 0; public final static int MODE_WORLD_READABLE = 1; public static final int MODE_APPEND = 32768; private final String BASE_URL = "http://219.223.190.211"; public boolean firsttime = false; private static String pat1 = "yyyy-MM-dd HH:mm:ss" ; private static String pat2 = "yyyyMMdd HH:mm:ss" ; @SuppressLint("SimpleDateFormat") private static SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; @SuppressLint("SimpleDateFormat") private static SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ; @Inject //private AsyncHttpHelper httpHelper; private AsyncHttpClient httpHelper = new AsyncHttpClient(80); @InjectView(R.id.xListView) private XListView mListView; @InjectView(R.id.refresh) private Button mRefresh; private ArrayAdapter<String[]> mAdapter; private ArrayList<String[]> items = new ArrayList<String[]>(); private Handler mHandler; private JSONArray jArray = new JSONArray(); private JSONObject jObj = new JSONObject(); private Boolean isIn = true; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { initComponent(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void initComponent() throws IOException, JSONException { // TODO Auto-generated method stub mListView.setPullLoadEnable(true); mAdapter = new ArrayAdapter<String[]>(this, android.R.layout.simple_list_item_2, android.R.id.text1, items){ @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = super.getView(position, convertView, parent); String[] entry = items.get(position); TextView text1 = (TextView) view.findViewById(android.R.id.text1); TextView text2 = (TextView) view.findViewById(android.R.id.text2); text1.setText(entry[0]); text2.setText(entry[1]); return view; } }; mListView.setAdapter(mAdapter); mListView.setRefreshTime(DateFormat.getTimeFormat(this).format(new Date(System.currentTimeMillis()))); mListView.setXListViewListener(this); mHandler = new Handler(); downFile(); loadFile(); loadReadFile(); Log.d(TAG,"initial"); if(jArray.length()==0){ firsttime = true; } else if(jArray.length()>0){ try { mAdapter.clear(); for (int i =0; i<jArray.length();i++){ long dt = jArray.getJSONObject(i).getJSONObject("datetime").getLong("$date"); Date datetime = new Date(dt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT")); String crawlTime = sdf1.format(datetime); String title = jArray.getJSONObject(i).getString("from")+" -> " + jArray.getJSONObject(i).getString("to"); String time = getTime(crawlTime); Log.d("read",jObj.toString()); if(jObj.has(jArray.getJSONObject(i).getJSONObject("_id").getString("$oid"))){ title = title+"( )"; } mAdapter.add(new String[]{title,time}); //+DateFormat.getDateFormat(GoodResultActivity.this).format(new Date(jArray.getJSONObject(i).getLong("$date")))); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }} mListView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(MapActivity.this,ProfileCurrentDealDetailActivity.class); isIn = false; try { // intent.putExtra("from", jArray.getJSONObject(position-1).getString("from")); // intent.putExtra("to", jArray.getJSONObject(position-1).getString("to")); // intent.putExtra("site", jArray.getJSONObject(position-1).getString("site")); // //intent.putExtra("url", jArray.getJSONObject(position-1).getString("url")); // long deadline = jArray.getJSONObject(position-1).getJSONObject("deadline").getLong("$date"); // intent.putExtra("deadline", DateFormat.getDateFormat(MapActivity.this).format(new Date(deadline))); intent.putExtra("title",""); intent.putExtra("data", jArray.getJSONObject(position-1).toString()); String readID = jArray.getJSONObject(position-1).getJSONObject("_id").getString("$oid"); jObj.put(readID, 1); downReadFile(jObj); Log.d("read",jObj.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } startActivity(intent); onPause(); } }); mRefresh.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub //mAdapter.clear(); onRefresh(); //items.clear(); }}); } private void onLoad() { mListView.stopRefresh(); //mListView.stopLoadMore(); mListView.setRefreshTime(DateFormat.getTimeFormat(this).format(new Date(System.currentTimeMillis()))); } private void onLoad2() { mListView.stopLoadMore(); //mListView.stopRefresh(); //mListView.setRefreshTime(SimpleDateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()))); //mListView.setRefreshTime(DateFormat.getTimeFormat(this).format(new Date(System.currentTimeMillis()))); } @Override public void onRefresh() { mHandler.postDelayed(new Runnable() { @Override public void run() { //start = ++refreshCnt; //mAdapter.clear(); if(firsttime){ getHttpResponse1(); mAdapter.notifyDataSetChanged(); firsttime = false; }else { Log.d(TAG,"refresh begin"); try { getHttpResponse(); mAdapter.notifyDataSetChanged(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }} // mAdapter = new ArrayAdapter<String>(MapActivity.this, android.R.layout.simple_expandable_list_item_1, items); // mListView.setAdapter(mAdapter); onLoad(); Intent intent = new Intent("com.example.communication.RECEIVER"); intent.putExtra("data",0); sendBroadcast(intent); Log.d("foregroudn","refresh send"); mListView.setSelection(0);//view } }, 1000); } @Override public void onLoadMore() { mHandler.postDelayed(new Runnable() { @Override public void run() { //items.clear(); if(firsttime){ getHttpResponse1(); mAdapter.notifyDataSetChanged(); firsttime = false; }else { try { getHttpResponse2(); mAdapter.notifyDataSetChanged(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }} //mAdapter.notifyDataSetChanged(); onLoad2(); } }, 1000); } public static boolean isInteger(String input){ Matcher mer = Pattern.compile("^[0-9]+$").matcher(input); return mer.find(); } //for refreshing not the first time public void getHttpResponse() throws IOException, JSONException{ RequestParams rp = new RequestParams(); loadFile(); loadReadFile(); Log.d(TAG+"nihao","now jArray"+Integer.toString(jArray.length())); String jOS = jArray.getJSONObject(0).toString(); rp.put("data", jOS); JsonHttpResponseHandler jrh = new JsonHttpResponseHandler("UTF-8") { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { //Toast.makeText(MapActivity.this, response.toString(), Toast.LENGTH_LONG).show(); try { downFile(response); //Log.d(TAG+"nihao","header num"+Integer.toString(headers.length)); int updata_num =0; for(int i=0;i<headers.length;i++){ Log.d(TAG+"nihao",headers[i].toString()); if(isInteger(headers[i].getValue().toString())){ updata_num = Integer.parseInt(headers[i].getValue()); Log.d("nihao",headers[i].getValue()); } } //updata_num = statusCode; if(updata_num==0){ Toast toast = Toast.makeText(MapActivity.this, " ", Toast.LENGTH_SHORT); toast.setGravity(0x00000030, 0, 55); toast.show(); //loadFile(); }else{ Toast toast = Toast.makeText(MapActivity.this, " "+updata_num+"", Toast.LENGTH_SHORT); toast.setGravity(0x00000030, 0, 55); toast.show();} loadFile(); mAdapter.clear(); Log.d(TAG+"nihao","read done"); //Log.d(TAG+"nihao",jArray.toString()); for (int i =0; i<jArray.length();i++){ long dt = jArray.getJSONObject(i).getJSONObject("datetime").getLong("$date"); Date datetime = new Date(dt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT")); String crawlTime = sdf1.format(datetime); String time = getTime(crawlTime); String title = jArray.getJSONObject(i).getString("from")+" -> " + jArray.getJSONObject(i).getString("to"); Log.d("read",jObj.toString()); if(jObj.has(jArray.getJSONObject(i).getJSONObject("_id").getString("$oid"))){ title = title+" ()"; } mAdapter.add(new String[]{title,time}); //+DateFormat.getDateFormat(GoodResultActivity.this).format(new Date(jArray.getJSONObject(i).getLong("$date")))); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) { Toast.makeText(MapActivity.this, statusCode + "\t" + responseBody, Toast.LENGTH_LONG).show(); } }; httpHelper.post(BASE_URL+"/latest",rp, jrh); } //for loading for the first time public void getHttpResponse1(){ RequestParams rp = new RequestParams(); JsonHttpResponseHandler jrh = new JsonHttpResponseHandler("UTF-8"){ public void onSuccess(int statusCode, Header[] headers, JSONArray response) { //Toast.makeText(MapActivity.this, response.toString(), Toast.LENGTH_LONG).show(); try { downFile(response); //Log.d(TAG+"nihao","header num"+Integer.toString(headers.length)); loadFile(); mAdapter.clear(); for (int i =0; i<jArray.length();i++){ long dt = jArray.getJSONObject(i).getJSONObject("datetime").getLong("$date"); Date datetime = new Date(dt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT")); String crawlTime = sdf1.format(datetime); String time = getTime(crawlTime); mAdapter.add(new String[]{jArray.getJSONObject(i).getString("from")+" -> " + jArray.getJSONObject(i).getString("to"), time}); //+DateFormat.getDateFormat(GoodResultActivity.this).format(new Date(jArray.getJSONObject(i).getLong("$date")))); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; httpHelper.get(BASE_URL+"/latest",rp, jrh); } //for loading more public void getHttpResponse2() throws IOException, JSONException{ RequestParams rp = new RequestParams(); //loadFile(); Log.d("nihao",Integer.toString(jArray.length())); String jOS = jArray.getJSONObject(jArray.length()-1).toString(); rp.put("data", jOS); JsonHttpResponseHandler jrh = new JsonHttpResponseHandler("UTF-8"){ @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) { // TODO Auto-generated method stub //super.onFailure(statusCode, headers, responseBody, e); Toast.makeText(MapActivity.this, statusCode + "\t" + responseBody, Toast.LENGTH_LONG).show(); } @Override public void onSuccess(JSONArray response) { // TODO Auto-generated method stub try { //updateFile(response); //loadFile(jArray); int len = jArray.length(); Log.d("nihao-len",Integer.toString(len)); for(int i =0;i<response.length();i++){ jArray.put(jArray.length(), response.getJSONObject(i)); long dt = response.getJSONObject(i).getJSONObject("datetime").getLong("$date"); Date datetime = new Date(dt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT")); String crawlTime = sdf1.format(datetime); String time = getTime(crawlTime); String title = response.getJSONObject(i).getString("from")+" -> " + response.getJSONObject(i).getString("to"); Log.d("read",jObj.toString()); if(jObj.has(response.getJSONObject(i).getJSONObject("_id").getString("$oid"))){ title = title+" ()"; } mAdapter.add(new String[]{title,time}); } Log.d(TAG,"update read done"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; //httpHelper. httpHelper.post(BASE_URL+"/previous",rp,jrh); } public void loadFile() throws IOException, JSONException{ FileInputStream inStream=MapActivity.this.openFileInput("tmp.txt"); ByteArrayOutputStream stream=new ByteArrayOutputStream(); byte[] buffer=new byte[10240]; int length=-1; while((length=inStream.read(buffer))!=-1) { stream.write(buffer,0,length); } clearArray(); JSONArray tmp = new JSONArray(stream.toString()); // Log.d(TAG,tmp.toString()); for(int i = 0; i<tmp.length();i++){ jArray.put(i, tmp.getJSONObject(i)); } Log.d(TAG,"jArray in loadfile()"+Integer.toString(jArray.length())); stream.close(); inStream.close(); } public void loadReadFile() throws IOException, JSONException{ FileInputStream inStream=MapActivity.this.openFileInput("read.txt"); ByteArrayOutputStream stream=new ByteArrayOutputStream(); byte[] buffer=new byte[10240]; int length=-1; while((length=inStream.read(buffer))!=-1) { stream.write(buffer,0,length); } jObj = new JSONObject(stream.toString()); stream.close(); inStream.close(); } public void downFile() throws IOException{ FileOutputStream outStream=MapActivity.this.openFileOutput("tmp.txt",MODE_APPEND); FileOutputStream outStream1=MapActivity.this.openFileOutput("read.txt",MODE_APPEND); outStream.write(new JSONArray().toString().getBytes()); outStream1.write(new JSONObject().toString().getBytes()); outStream.close(); outStream1.close(); } public void downFile(JSONArray response) throws IOException{ FileOutputStream outStream=MapActivity.this.openFileOutput("tmp.txt",MODE_PRIVATE); outStream.write(response.toString().getBytes()); outStream.close(); Log.d(TAG,"write done"); } public void downReadFile(JSONObject response) throws IOException{ FileOutputStream outStream=MapActivity.this.openFileOutput("read.txt",MODE_PRIVATE); outStream.write(response.toString().getBytes()); outStream.close(); Log.d(TAG,"write done"); } public void clearArray() throws JSONException{ jArray = new JSONArray(); Log.d(TAG+"nihao",jArray.toString()); } public boolean onKeyDown(int keyCode, KeyEvent event) { PackageManager pm = getPackageManager(); ResolveInfo homeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0); if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityInfo ai = homeInfo.activityInfo; Intent startIntent = new Intent(Intent.ACTION_MAIN); startIntent.addCategory(Intent.CATEGORY_LAUNCHER); startIntent.setComponent(new ComponentName(ai.packageName, ai.name)); startActivitySafely(startIntent); return true; } else return super.onKeyDown(keyCode, event); } private void startActivitySafely(Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "null", Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, "null", Toast.LENGTH_SHORT).show(); } } private String getTime(String crawlTime) { // TODO Auto-generated method stub //yyyy-MM-dd HH:mm:ss long nt = System.currentTimeMillis(); Date nowtime = new Date(nt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT+8")); String curTime = sdf1.format(nowtime); int yearC = Integer.valueOf(curTime.substring(0, 4)); int monthC = Integer.valueOf(curTime.substring(5, 7)); int dayC = Integer.valueOf(curTime.substring(8, 10)); int hourC = Integer.valueOf(curTime.substring(11, 13)); int minC = Integer.valueOf(curTime.substring(14, 16)); // Log.d("time=cur",curTime); // Log.d("time",crawlTime); int yearT = Integer.valueOf(crawlTime.substring(0, 4)); int monthT = Integer.valueOf(crawlTime.substring(5, 7)); int dayT = Integer.valueOf(crawlTime.substring(8, 10)); int hourT = Integer.valueOf(crawlTime.substring(11, 13)); int minT = Integer.valueOf(crawlTime.substring(14, 16)); //int secT = Integer.valueOf(crawlTime.substring(8, 10)); if(yearT != yearC || monthT!= monthC){ return crawlTime; }else if(dayT != dayC){ if(dayC - dayT > 1){return crawlTime;} else return ""; }else if(hourC!=hourT){ if(hourC - hourT ==1 && minC< minT){ return 60+minC-minT+""; } else return hourC-hourT-1+""; }else if (minC-minT>1){ return minC-minT-1+""; }else return ""; } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Log.d("resume",isIn.toString()); if(isIn){ onRefresh(); }else{ try { mAdapter.clear(); for (int i =0; i<jArray.length();i++){ long dt = jArray.getJSONObject(i).getJSONObject("datetime").getLong("$date"); Date datetime = new Date(dt); sdf1.setTimeZone(TimeZone.getTimeZone("GMT")); String crawlTime = sdf1.format(datetime); String title = jArray.getJSONObject(i).getString("from")+" -> " + jArray.getJSONObject(i).getString("to"); String time = getTime(crawlTime); Log.d("read",jObj.toString()); if(jObj.has(jArray.getJSONObject(i).getJSONObject("_id").getString("$oid"))){ title = title+"( )"; } mAdapter.add(new String[]{title,time}); //+DateFormat.getDateFormat(GoodResultActivity.this).format(new Date(jArray.getJSONObject(i).getLong("$date")))); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } isIn =true; } }
package com.twitter.intellij.pants.util; import com.intellij.openapi.vfs.VirtualFile; import com.twitter.intellij.pants.base.PantsCodeInsightFixtureTestCase; import com.twitter.intellij.pants.util.PantsPsiUtil; import com.twitter.intellij.pants.util.Target; import java.util.ArrayList; import java.util.List; abstract public class PantsPsiUtilTestBase extends PantsCodeInsightFixtureTestCase { private final String myPath; public PantsPsiUtilTestBase(String... path) { myPath = getPath(path); } @Override protected String getBasePath() { return myPath; } private static String getPath(String... args) { final StringBuilder result = new StringBuilder(); for (String folder : args) { result.append("/"); result.append(folder); } return result.toString(); } public void doTest(List<Target> actualTargets) { doTest(null, actualTargets); } public void doTest(String targetPath, List<Target> actualTargets) { final String buildPath = targetPath == null ? "BUILD" : targetPath + "/BUILD"; final VirtualFile buildFile = myFixture.copyFileToProject(getTestName(true) + ".py", buildPath); myFixture.configureFromExistingVirtualFile(buildFile); final List<Target> targets = PantsPsiUtil.findTargets(myFixture.getFile()); assertOrderedEquals(actualTargets, targets); } }
package chess.model; import chess.model.pieces.*; import java.util.ArrayList; import java.util.List; /** * Holds the state of a single chess game */ public class ChessGame { public final static int BOARD_SIZE = 8; private BoardSpace[][] board = new BoardSpace[BOARD_SIZE][BOARD_SIZE]; private PieceColor currentTurn = PieceColor.WHITE; private Position selectedPosition = null; private PlayerPieceSet blackPieces = new PlayerPieceSet(PieceColor.BLACK); private PlayerPieceSet whitePieces = new PlayerPieceSet(PieceColor.WHITE); private List<Move> gameHistory = new ArrayList<>(); public ChessGame() { createBoard(); setUpNewGame(); } /** * Constructor that allows you to create an instance with an * empty board * * @param setUpAsNewGame */ public ChessGame(boolean setUpAsNewGame) { createBoard(); if (setUpAsNewGame) { setUpNewGame(); } } /** * Create a new instance of a chess game from an older game history * * @param gameHistory The move history of the game to copy */ public ChessGame(List<Move> gameHistory) { createBoard(); setUpNewGame(); //simulate the moves for (Move move : gameHistory) { this.simulateMove(move); } } /** * Initializes the array for all spaces on the board */ private void createBoard() { //set up all spaces on the game for (int row = 0; row < BOARD_SIZE; row++) { for (int col = 0; col < BOARD_SIZE; col++) { board[row][col] = new BoardSpace(new Position(row, col)); } } } /** * Sets up the pieces in the correct places for a new game */ private void setUpNewGame() { //add black pieces to the game board[0][0].setPiece(blackPieces.addPiece(Rook.class, board[0][0].getPosition())); board[0][1].setPiece(blackPieces.addPiece(Knight.class, board[0][1].getPosition())); board[0][2].setPiece(blackPieces.addPiece(Bishop.class, board[0][2].getPosition())); board[0][3].setPiece(blackPieces.addPiece(Queen.class, board[0][3].getPosition())); board[0][4].setPiece(blackPieces.addPiece(King.class, board[0][4].getPosition())); board[0][5].setPiece(blackPieces.addPiece(Bishop.class, board[0][5].getPosition())); board[0][6].setPiece(blackPieces.addPiece(Knight.class, board[0][6].getPosition())); board[0][7].setPiece(blackPieces.addPiece(Rook.class, board[0][7].getPosition())); for (int col = 0; col < 8; col++) { board[1][col].setPiece(blackPieces.addPiece(Pawn.class, board[1][col].getPosition())); } //add white pieces to the game for (int col = 0; col < 8; col++) { board[6][col].setPiece(whitePieces.addPiece(Pawn.class, board[6][col].getPosition())); } board[7][0].setPiece(whitePieces.addPiece(Rook.class, board[7][0].getPosition())); board[7][1].setPiece(whitePieces.addPiece(Knight.class, board[7][1].getPosition())); board[7][2].setPiece(whitePieces.addPiece(Bishop.class, board[7][2].getPosition())); board[7][3].setPiece(whitePieces.addPiece(Queen.class, board[7][3].getPosition())); board[7][4].setPiece(whitePieces.addPiece(King.class, board[7][4].getPosition())); board[7][5].setPiece(whitePieces.addPiece(Bishop.class, board[7][5].getPosition())); board[7][6].setPiece(whitePieces.addPiece(Knight.class, board[7][6].getPosition())); board[7][7].setPiece(whitePieces.addPiece(Rook.class, board[7][7].getPosition())); } /** * Sets a new position as the currently selected position * * @param position */ public void selectNewPosition(Position position) { selectedPosition = position; } /** * Gets the currently selected position * @return */ public Position getSelectedPosition() { return selectedPosition; } /** * Gets the pieces at the currently selected position * @return */ public ChessPiece getSelectedPiece() { return getBoardSpace(getSelectedPosition()).getPiece(); } /** * Gets the current players turn (based on color) * * @return */ public PieceColor getCurrentTurn() { return currentTurn; } /** * Changes which player's turn it is */ public void changeTurns() { currentTurn = getCurrentTurn() == PieceColor.BLACK ? PieceColor.WHITE : PieceColor.BLACK; } /** * Returns a single space on the board based on its position on the board * * @param position * @return */ public BoardSpace getBoardSpace(Position position) { int row = position.getRow(); int column = position.getCol(); if (row < 0 || row > 7 || column < 0 || column > 7) return null; return board[row][column]; } /** * Switches the position of a piece in the board * * @param from The starting position * @param to The ending position * @return Whether the move was successfully completed */ public boolean makeMove(Position from, Position to) { //get piece being moved ChessPiece piece = getBoardSpace(from).getPiece(); Move currentMove = new Move(piece, from, to); gameHistory.add(currentMove); //keep this at the start. trust me. if (isEnPassant(piece, from, to)) { //must be done before setting all pawns to no longer be eligible. See method documentation for details. int direction = piece.getPieceColor() == PieceColor.BLACK ? -1 : 1; BoardSpace captureSpace = getBoardSpace(new Position(to.getRow() + direction, to.getCol())); currentMove.setAsCaptureMove(captureSpace.getPiece(), captureSpace.getPosition()); capture(captureSpace.getPosition()); } setAllPawnToNotEligibleForEnPassant(); //must be called before the moveTo method. See method documentation for details if (isCapture(to)) { currentMove.setAsCaptureMove(getBoardSpace(to).getPiece(), to); capture(to); } //move the piece getBoardSpace(from).setPiece(null); getBoardSpace(to).setPiece(piece); piece.moveTo(to); //check if castling, if yes move rook if (isKingSideCastling(getBoardSpace(to).getPiece(), from, to)) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() - 1)); currentMove.setAsKingSideCastle(); } else if (isQueenSideCastling(getBoardSpace(to).getPiece(), from, to)) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() + 1)); currentMove.setAsQueenSideCastle(); } //check if pawn gets promoted if (piece.getClass() == Pawn.class && ((Pawn)piece).deservesPromotion()){ PlayerPieceSet pieceSet = piece.getPieceColor() == PieceColor.BLACK ? blackPieces : whitePieces; ChessPiece promotedPiece = ((Pawn)piece).promote(); capture(piece); pieceSet.addPiece(promotedPiece); this.getBoardSpace(to).setPiece(promotedPiece); currentMove.setAsPawnPromotion(promotedPiece); } if (isCheckmate()) currentMove.setAsCheckmate(); else if (isCheck()) currentMove.setAsCheck(); changeTurns(); return true; } /** * Switches the position of a piece in the board * * @param move The move being simulated * @return Whether the move was successfully completed */ public boolean simulateMove(Move move) { Position from = move.getStartPosition(); Position to = move.getEndPosition(); //get piece being moved ChessPiece piece = getBoardSpace(from).getPiece(); if (isEnPassant(piece, from, to)) { //must be done before setting all pawns to no longer be eligible. See method documentation for details. int direction = piece.getPieceColor() == PieceColor.BLACK ? -1 : 1; BoardSpace captureSpace = getBoardSpace(new Position(to.getRow() + direction, to.getCol())); capture(captureSpace.getPosition()); } setAllPawnToNotEligibleForEnPassant(); //must be called before the moveTo method. See method documentation for details if (isCapture(to)) capture(to); //move the piece getBoardSpace(from).setPiece(null); getBoardSpace(to).setPiece(piece); piece.moveTo(to); //check if castling, if yes move rook if (move.isKingSideCastle()) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() - 1)); } else if (move.isQueenSideCastle()) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() + 1)); } //check if pawn gets promoted if (piece.getClass() == Pawn.class && ((Pawn)piece).deservesPromotion()){ PlayerPieceSet pieceSet = piece.getPieceColor() == PieceColor.BLACK ? blackPieces : whitePieces; ChessPiece promotedPiece = move.getPromotedPiece(); capture(piece); pieceSet.addPiece(promotedPiece); this.getBoardSpace(to).setPiece(promotedPiece); } changeTurns(); return true; } /** * Simulates a move being made * * @param from The position being moved from * @param to The position being moved to * @return Whether the move was successfully completed */ public boolean simulateMove(Position from, Position to) { //get piece being moved ChessPiece piece = getBoardSpace(from).getPiece(); if (piece == null) { return false; } if (isEnPassant(piece, from, to)) { //must be done before setting all pawns to no longer be eligible. See method documentation for details. int direction = piece.getPieceColor() == PieceColor.BLACK ? -1 : 1; BoardSpace captureSpace = getBoardSpace(new Position(to.getRow() + direction, to.getCol())); capture(captureSpace.getPosition()); } setAllPawnToNotEligibleForEnPassant(); //must be called before the moveTo method. See method documentation for details if (isCapture(to)) capture(to); //move the piece getBoardSpace(from).setPiece(null); getBoardSpace(to).setPiece(piece); piece.moveTo(to); //check if castling, if yes move rook if (isKingSideCastling(getBoardSpace(to).getPiece(), from, to)) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() - 1)); } else if (isQueenSideCastling(getBoardSpace(to).getPiece(), from, to)) { Rook rookToMove = (Rook) getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).getPiece(); getBoardSpace(new Position(to.getRow(), to.getCol() - 1)).setPiece(null); getBoardSpace(new Position(to.getRow(), to.getCol() + 1)).setPiece(rookToMove); rookToMove.moveTo(new Position(to.getRow(), to.getCol() + 1)); } //we dont care about pawn promotion? changeTurns(); return true; } public boolean isCapture(Position position) { if (getBoardSpace(position).isOccupied()) return true; else return false; } public void capture(Position position) { ChessPiece pieceToCapture = getBoardSpace(position).getPiece(); capture(pieceToCapture); } public void capture(ChessPiece pieceToCapture) { if (pieceToCapture.getPieceColor() == PieceColor.BLACK) blackPieces.capture(pieceToCapture); else whitePieces.capture(pieceToCapture); } /** * Checks if a move is performing an En Passant. * * NOTE: This must be done before all pawns that are eligible for En Passant are reset to be ineligible. * This is for the obvious reason that if it first resets it, the pawn will never be able to do an en passant. * * @param piece * @param from * @param to * @return */ private boolean isEnPassant(ChessPiece piece, Position from, Position to) { if (!(piece instanceof Pawn)) { //piece being moved is not a pawn return false; } else if (from.getCol() == to.getCol()) { //is pawn but not a capture move (pawns only move diagonal when capturing) return false; } //get piece in space above the one being moved to //if it is a pawn that is eligible for en passant return true int direction = piece.getPieceColor() == PieceColor.BLACK ? -1 : 1; Position potentialCapturePosition = new Position(to.getRow() + direction, to.getCol()); BoardSpace potentialCaptureSpace = getBoardSpace(potentialCapturePosition); ChessPiece potentialCapturePiece = potentialCaptureSpace.getPiece(); if (!(potentialCapturePiece instanceof Pawn)) { //the piece is not a pawn return false; } else if (((Pawn) potentialCapturePiece).isEligibleForEnPassant()) { return true; } else { return false; } } private boolean isKingSideCastling(ChessPiece piece, Position from, Position to) { return piece.getClass() == King.class && to.getCol() == from.getCol() + 2; } private boolean isQueenSideCastling(ChessPiece piece, Position from, Position to) { return piece.getClass() == King.class && to.getCol() == from.getCol() - 3; } /** * Set all pawns which are eligible for En Passant to no longer be eligible * * NOTE: This must be done before the piece is moved, otherwise if it is a pawn moving 2 spaces it will become ineligible */ public void setAllPawnToNotEligibleForEnPassant() { for (int row = 0; row < board.length; row++) { for (int col = 0; col < board[0].length; col++) { ChessPiece piece = getBoardSpace(new Position(row, col)).getPiece(); if (piece instanceof Pawn && ((Pawn) piece).isEligibleForEnPassant()) ((Pawn) piece).setEligibleForEnPassant(false); } } } /** * Checks if the current state of the game is a checkmate * @return */ public boolean isCheckmate() { return isWhiteCheckmated() || isBlackCheckmated(); } public boolean isWhiteCheckmated() { if (isWhiteInCheck()) { for (ChessPiece piece : whitePieces.getAllAlivePieces()) { if (piece.getLegalMoves(this, true).size() > 0) { return false; } } } else { return false; } return true; } public boolean isBlackCheckmated() { if (isBlackInCheck()) { for (ChessPiece piece : blackPieces.getAllAlivePieces()) { if (piece.getLegalMoves(this, true).size() > 0) { return false; } } } else { return false; } return true; } /** * Checks if the current state of the game is a check * @return */ public boolean isCheck() { return isWhiteInCheck() || isBlackInCheck(); } public boolean isWhiteInCheck() { Position whiteKingPosition = whitePieces.getAlivePiecesOfType(King.class).get(0).getPosition(); //look for white in check for (ChessPiece piece : blackPieces.getAllAlivePieces()) { if (piece.getClass() != King.class) { for (Position position : piece.getLegalMoves(this, false)) { if (position.equals(whiteKingPosition)) return true; } } } return false; } public boolean isBlackInCheck() { Position blackKingPosition = blackPieces.getAlivePiecesOfType(King.class).get(0).getPosition(); //look for black in check for (ChessPiece piece : whitePieces.getAllAlivePieces()) { if (piece.getClass() != King.class) { for (Position position : piece.getLegalMoves(this, false)) { if (position.equals(blackKingPosition)) return true; } } } return false; } /** * Checks if the current state of the game is a stalemate * @return */ public boolean isStalemate() {return false; } public boolean moveCausesCheckForItsOwnKing(Position moveFrom, Position moveTo ) { ChessPiece piece = getBoardSpace(moveFrom).getPiece(); //create new instance based off of the current game ChessGame simulatedGame = new ChessGame(gameHistory); //simulate the move simulatedGame.simulateMove(moveFrom, moveTo); //check if the king is in check if (piece.getPieceColor() == PieceColor.WHITE) return simulatedGame.isWhiteInCheck(); else return simulatedGame.isBlackInCheck(); } public List<Move> getGameHistory() { return this.gameHistory; } public PlayerPieceSet getBlackPieces() { return this.blackPieces; } public PlayerPieceSet getWhitePieces() { return this.whitePieces; } }
package jadx.core.xmlgen; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; public class BinaryXMLParser { private byte[] bytes; private String[] strings; private int count; private String nsPrefix="ERROR"; public BinaryXMLParser(String xmlfilepath) { System.out.println(xmlfilepath); File manifest = new File(xmlfilepath); if(null==manifest) die("null==manifest"); bytes = new byte[(int) manifest.length()]; try { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(manifest)); int total = 0; while(total < bytes.length) { int remain = bytes.length - total; int read = is.read(bytes, total, remain); if(read > 0) total += read; } } finally { is.close(); } } catch(FileNotFoundException fnfe) { die("FILE NOT FOUND"); } catch(IOException ioe) { die("IOE"); } count=0; } public void parse() { if(cInt16(bytes, count) != 0x0003) die("Version is not 3"); if(cInt16(bytes, count) != 0x0008) die("Size of header is not 8"); if(cInt32(bytes, count) != bytes.length) die("Size of manifest doesn't match"); while((count+2)<=bytes.length) { int type = cInt16(bytes, count); if(type==0x0001) parseStringPool(); else if(type==0x0180) parseResourceMap(); else if(type==0x0100) parseNameSpace(); else if(type==0x0101) parseNameSpaceEnd(); else if(type==0x0102) parseElement(); else if(type==0x0103) parseElementEnd(); else if(type==0x0000) continue; // NullType is just doing nothing else die("Type: " + Integer.toHexString(type) + " not yet implemented"); System.out.println("COUNT: "+Integer.toHexString(count)); } //die("Done"); } private void parseStringPool() { if(cInt16(bytes, count) != 0x001c) die("Header header size not 28"); int hsize = cInt32(bytes, count); int stringCount = cInt32(bytes, count); int styleCount = cInt32(bytes, count); int flags = cInt32(bytes, count); int stringsStart = cInt32(bytes, count); int stylesStart = cInt32(bytes, count); /* System.out.println(hsize); System.out.println(stringCount); System.out.println(styleCount); System.out.println(flags); System.out.println(stringsStart); System.out.println(stylesStart); */ int[] stringsOffsets = new int[stringCount]; for(int i=0; i<stringCount; i++) { stringsOffsets[i] = cInt32(bytes, count); //System.out.println("i["+i+"]: " + stringsOffsets[i]); } strings = new String[stringCount]; for(int i=0; i<stringCount; i++) { int off = 8 + stringsStart + stringsOffsets[i]; int strlen = cInt16(bytes, off); //System.out.println("strlen: " + strlen); byte[] str = new byte[strlen*2]; System.arraycopy(bytes, count, str, 0, strlen*2); count+=strlen*2; strings[i] = new String(str, Charset.forName("UTF-16LE")); System.out.println("index i["+i+"] string: " + strings[i]); count+=2; } } private void parseResourceMap() { if(cInt16(bytes, count) != 0x8) die("Header size of resmap is not 8!"); int rhsize = cInt32(bytes, count); System.out.println("RHeader Size: " + rhsize); int[] ids = new int[(rhsize-8)/4]; for(int i=0; i<ids.length; i++) { ids[i]=cInt32(bytes, count); System.out.println("i["+i+"] ID: "+ids[i]); System.out.println("Hex: 0x0" + Integer.toHexString(ids[i]) + " should be: " + strings[i]); } } private void parseNameSpace() { if(cInt16(bytes, count) != 0x0010) die("NAMESPACE header is not 0x0010"); if(cInt32(bytes, count) != 0x18) die("NAMESPACE header chunk is not 0x18 big"); int beginLineNumber = cInt32(bytes, count); //if(beginLineNumber!=2) die("NAMESPACE beginning line number != 2 not supported yet"); System.out.println("NAMESPACE BEGIN Line: " + beginLineNumber); System.out.println("Comment: 0x" + Integer.toHexString(cInt32(bytes, count))); int beginPrefix = cInt32(bytes, count); System.out.println("Prefix: " + strings[beginPrefix]); nsPrefix = strings[beginPrefix]; int beginURI = cInt32(bytes, count); System.out.println("URI: " + strings[beginURI]); System.out.println("COUNT: "+Integer.toHexString(count)); } private void parseNameSpaceEnd() { if(cInt16(bytes, count) != 0x0010) die("NAMESPACE header is not 0x0010"); if(cInt32(bytes, count) != 0x18) die("NAMESPACE header chunk is not 0x18 big"); int endLineNumber = cInt32(bytes, count); //if(endLineNumber!=2) die("NAMESPACE begining line number != 2 not supported yet"); System.out.println("NAMESPACE END Line: " + endLineNumber); System.out.println("Comment: 0x" + Integer.toHexString(cInt32(bytes, count))); int endPrefix = cInt32(bytes, count); System.out.println("Prefix: " + strings[endPrefix]); nsPrefix = strings[endPrefix]; int endURI = cInt32(bytes, count); System.out.println("URI: " + strings[endURI]); } private void parseElement() { if(cInt16(bytes, count) != 0x0010) die("ELEMENT HEADER SIZE is not 0x10"); //if(cInt32(bytes, count) != 0x0060) die("ELEMENT CHUNK SIZE is not 0x60"); count+=4; int elementLineNumber = cInt32(bytes, count); System.out.println("elementLineNumber: " + elementLineNumber); System.out.println("Comment: 0x" + Integer.toHexString(cInt32(bytes, count))); System.out.println("COUNT: "+Integer.toHexString(count)); int startNS = cInt32(bytes, count); System.out.println("Namespace: 0x" + Integer.toHexString(startNS)); int startNSName = cInt32(bytes, count); // what to do with this id? System.out.println("Namespace name: " + strings[startNSName]); System.out.println("<" + strings[startNSName] + ""); int attributeStart = cInt16(bytes, count); if(attributeStart != 0x14) die("startNS's attributeStart is not 0x14"); int attributeSize = cInt16(bytes, count); if(attributeSize != 0x14) die("startNS's attributeSize is not 0x14"); int attributeCount = cInt16(bytes, count); System.out.println("startNS: attributeCount: " + attributeCount); int idIndex = cInt16(bytes, count); System.out.println("startNS: idIndex: " + idIndex); int classIndex = cInt16(bytes, count); System.out.println("startNS: classIndex: " + classIndex); int styleIndex = cInt16(bytes, count); System.out.println("startNS: styleIndex: " + styleIndex); for(int i=0; i<attributeCount; i++) { int attributeNS = cInt32(bytes, count); int attributeName = cInt32(bytes, count); int attributeRawValue = cInt32(bytes, count); int attrValSize = cInt16(bytes, count); //System.out.println(attrValSize); if(attrValSize != 0x08) die("attrValSize != 0x08 not supported"); if(cInt8(bytes, count) != 0) die("res0 is not 0"); int attrValDataType = cInt8(bytes, count); int attrValData = cInt32(bytes, count); System.out.println("ai["+i+"] ns: " + attributeNS); System.out.println("ai["+i+"] name: " + attributeName); System.out.println("ai["+i+"] rawval: " + attributeRawValue); System.out.println("ai["+i+"] dt: " + attrValDataType); System.out.println("ai["+i+"] d: " + attrValData); if(attributeNS != -1) System.out.print(nsPrefix+":"); if(attrValDataType==0x3) System.out.println(strings[attributeName] + "=" + strings[attrValData]); else if(attrValDataType==0x10) System.out.println(strings[attributeName] + "=" + attrValData); else System.out.println(strings[attributeName] + " = UNKNOWN DATA TYPE: " + attrValDataType); } System.out.println(">"); } private void parseElementEnd() { if(cInt16(bytes, count) != 0x0010) die("ELEMENT END header is not 0x0010"); if(cInt32(bytes, count) != 0x18) die("ELEMENT END header chunk is not 0x18 big"); int endLineNumber = cInt32(bytes, count); //if(endLineNumber!=2) die("NAMESPACE beginning line number != 2 not supported yet"); System.out.println("ELEMENT END Line:" + endLineNumber); System.out.println("Comment: 0x" + Integer.toHexString(cInt32(bytes, count))); int elementNS = cInt32(bytes, count); int elementName = cInt32(bytes, count); System.out.print("</"); if(elementNS != -1) System.out.print(strings[elementNS]+":"); System.out.println(strings[elementName]+">"); } private int cInt8(byte[] bytes, int offset) { byte[] tmp = new byte[4]; tmp[3]=bytes[count++]; return ByteBuffer.wrap(tmp).getInt(); } private int cInt16(byte[] bytes, int offset) { byte[] tmp = new byte[4]; tmp[3]=bytes[count++]; tmp[2]=bytes[count++]; return ByteBuffer.wrap(tmp).getInt(); } private int cInt32(byte[] bytes, int offset) { byte[] tmp = new byte[4]; for(int i=0;i <4; i++) tmp[3-i]=bytes[count+i]; count+=4; return ByteBuffer.wrap(tmp).getInt(); } private void die(String message) { System.err.println(message); System.exit(3); } }
package org.jgroups.tests.perf; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; /** * Utility tool that creates configuration files for automated performance tests. * PerformanceTestGenerator, given an input file with -config flag, generates * test files that are used in conjunction with bin/clusterperfromancetest.sh. * The number of test files generated is numOfSenders*messageSizes. * * Default configuration file used for this utility is conf/performancetestconfig.txt * See bin/clusterperformancetest.sh * * @author Vladimir Blagojevic * @version $Id$ */ public class PerformanceTestGenerator { Properties configProperties = null; private long totalDataBytes; private int[] numOfSenders; private int[] messageSizes; private int numNodes; private int dataLogPoints; public PerformanceTestGenerator(Properties config) { configProperties = config; } /** * @param args */ public static void main(String[] args) { Properties config = null; for(int i=0; i < args.length; i++) { if("-config".equals(args[i])) { String config_file=args[++i]; config = new Properties(); try { config.load(new FileInputStream(config_file)); } catch (FileNotFoundException e) { System.err.println("File " + config_file + " not found"); return; } catch (IOException e) { System.err.println("Error reading configuration file " + config_file); return; } continue; } System.out.println("PerformanceTestGenerator -config <file>"); return; } try { PerformanceTestGenerator t=new PerformanceTestGenerator(config); t.parse(); t.generateTestConfigFiles(); } catch(Exception e) { e.printStackTrace(); } } private void parse() throws Exception{ numNodes = Integer.parseInt(configProperties.getProperty("nodes")); totalDataBytes = Long.parseLong(configProperties.getProperty("total_data")); numOfSenders = tokenizeAndConvert(configProperties.getProperty("number_of_senders"),","); messageSizes = tokenizeAndConvert(configProperties.getProperty("message_sizes"),","); dataLogPoints = Integer.parseInt(configProperties.getProperty("log_data_points")); } private void generateFile(int numOfSenders, int messageSize,int nodeCount) { FileWriter fw = null; long numOfMessages = (totalDataBytes/messageSize); try { fw = new FileWriter("config_"+numOfSenders + "_" +nodeCount +"_"+ messageSize + ".txt"); fw.write("transport=org.jgroups.tests.perf.transports.JGroupsTransport\n"); fw.write("msg_size="+messageSize+"\n"); fw.write("num_msgs="+(numOfMessages/numOfSenders) +"\n"); fw.write("num_senders="+numOfSenders+"\n"); fw.write("num_members="+nodeCount+"\n"); fw.write("log_interval="+(numOfMessages/dataLogPoints)+"\n"); fw.write("gnuplot_output=true\n"); fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static String[] tokenize(String s, String delim) { if (s == null || s.length() == 0) { return new String[0]; } if (delim == null || delim.length() == 0) { return new String[] { s }; } ArrayList tokens = new ArrayList(); int pos = 0; int delPos = 0; while ((delPos = s.indexOf(delim, pos)) != -1) { tokens.add(s.substring(pos, delPos)); pos = delim.length() + delPos; } tokens.add(s.substring(pos)); return (String[]) tokens.toArray(new String[tokens.size()]); } public static int[] tokenizeAndConvert(String s, String delim) { String stokens [] = tokenize(s,delim); int result [] = new int[stokens.length]; for (int i = 0; i < stokens.length; i++) { result[i]=Integer.parseInt(stokens[i]); } return result; } private void generateTestConfigFiles() { for (int i = 0; i < numOfSenders.length; i++) { for (int j = 0; j < messageSizes.length; j++) { generateFile(numOfSenders[i],messageSizes[j],numNodes); } } } }
package com.wilutions.joa.outlook.ex; import java.util.logging.Level; import java.util.logging.Logger; import com.wilutions.com.ComException; import com.wilutions.com.Dispatch; import com.wilutions.com.IDispatch; import com.wilutions.com.reg.Registry; import com.wilutions.joa.IconManager; import com.wilutions.joa.outlook.OutlookAddin; import com.wilutions.mslib.office.IRibbonControl; import com.wilutions.mslib.office.IRibbonUI; import com.wilutions.mslib.outlook.Explorer; import com.wilutions.mslib.outlook.ExplorersEvents; import com.wilutions.mslib.outlook.Inspector; import com.wilutions.mslib.outlook.InspectorsEvents; import com.wilutions.mslib.outlook.OlObjectClass; import com.wilutions.mslib.outlook._Explorer; import com.wilutions.mslib.outlook._Explorers; import com.wilutions.mslib.outlook._Inspector; import com.wilutions.mslib.outlook._Inspectors; public class OutlookAddinEx extends OutlookAddin implements InspectorsEvents, ExplorersEvents { private final IconManager iconManager; private IRibbonUI ribbon; private final Registry registry; private volatile _Inspectors inspectors; /** * Explorers collection. * Need to hold this in order to permanently receive the onNewExplore event. */ private volatile _Explorers explorers; public OutlookAddinEx() { iconManager = new IconManager(this); registry = new Registry(getClass()); } public IRibbonUI getRibbon() { return ribbon; } public Registry getRegistry() { return registry; } public void onLoadRibbon(IRibbonUI ribbon) { this.ribbon = ribbon; } public Dispatch getRibbonIcon(IRibbonControl control) { Dispatch picdisp = iconManager.getIconByTag(control); return picdisp; } @Override public void onStartup() throws ComException { try { explorers = getApplication().getExplorers(); Dispatch.withEvents(explorers, this); int n = explorers.getCount(); for (int i = 1; i <= n; i++) { Explorer explorer = explorers.Item(i); onNewExplorer(explorer); } } catch (Throwable e) { e.printStackTrace(); } try { inspectors = getApplication().getInspectors(); Dispatch.withEvents(inspectors, this); int n = inspectors.getCount(); for (int i = 1; i <= n; i++) { Inspector inspector = inspectors.Item(i); onNewInspector(inspector); } } catch (Throwable e) { e.printStackTrace(); } } @Override public void onQuit() throws ComException { Dispatch.releaseEvents(inspectors, this); super.onQuit(); } @Override public void onNewInspector(final _Inspector insp) throws ComException { Inspector inspector = Dispatch.as(insp, Inspector.class); IDispatch dispItem = inspector.getCurrentItem(); OlObjectClass olclass = OlObjectClass.valueOf((Integer) dispItem._get("Class")); System.out.println("new inspector, item=" + dispItem + ", class=" + olclass); InspectorWrapper inspectorWrapper = createInspectorWrapper(inspector, olclass); if (inspectorWrapper == null) { inspectorWrapper = new InspectorWrapper(inspector, dispItem); } InspectorWrappers.add(inspectorWrapper); } protected InspectorWrapper createInspectorWrapper(Inspector inspector, OlObjectClass olclass) { return null; } public InspectorWrapper getInspectorWrapper(Inspector inspector) { return InspectorWrappers.get(inspector); } @Override public void onNewExplorer(_Explorer expl) throws ComException { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "getMyExplorerWrapper("); Explorer explorer = expl.as(Explorer.class); ExplorerWrapper explorerWrapper = createExplorerWrapper(explorer); if (explorerWrapper == null) { explorerWrapper = new ExplorerWrapper(explorer); } ExplorerWrappers.add(explorerWrapper); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, ")getMyExplorerWrapper"); } protected ExplorerWrapper createExplorerWrapper(Explorer explorer) { return null; } public ExplorerWrapper getExplorerWrapper(Explorer explorer) { return ExplorerWrappers.get(explorer); } private Logger log = Logger.getLogger("OutlookAddinEx"); }
// our package package org.broadinstitute.sting.utils.baq; // the imports for unit testing. import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.DataProvider; import org.testng.annotations.BeforeMethod; import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.gatk.walkers.qc.ValidateBAQWalker; import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile; import org.broadinstitute.sting.utils.sam.ArtificialSAMFileWriter; import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; import org.broadinstitute.sting.utils.Utils; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import net.sf.picard.reference.IndexedFastaSequenceFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.samtools.*; /** * Basic unit test for GenomeLoc */ public class BAQUnitTest extends BaseTest { private SAMFileHeader header; private final int startChr = 1; private final int numChr = 2; private final int chrSize = 1000; IndexedFastaSequenceFile fasta = null; @BeforeMethod public void before() { header = ArtificialSAMUtils.createArtificialSamHeader(numChr, startChr, chrSize); fasta = new IndexedFastaSequenceFile(new File(hg18Reference)); } private class BAQTest { String readBases, refBases; byte[] quals, expected; String cigar; int refOffset; int pos; public BAQTest(String _refBases, String _readBases, String _quals, String _expected) { this(0, -1, null, _readBases, _refBases, _quals, _expected); } public BAQTest(int refOffset, String _refBases, String _readBases, String _quals, String _expected) { this(refOffset, -1, null, _refBases, _readBases, _quals, _expected); } public BAQTest(long pos, String cigar, String _readBases, String _quals, String _expected) { this(0, pos, cigar, null, _readBases, _quals, _expected); } public BAQTest(int _refOffset, long _pos, String _cigar, String _refBases, String _readBases, String _quals, String _expected) { refOffset = _refOffset; pos = (int)_pos; cigar = _cigar; readBases = _readBases; refBases = _refBases; quals = new byte[_quals.getBytes().length]; expected = new byte[_quals.getBytes().length]; for ( int i = 0; i < quals.length; i++) { quals[i] = (byte)(_quals.getBytes()[i] - 33); expected[i] = (byte)(_expected.getBytes()[i] - 33); } } public String toString() { return readBases; } public SAMRecord createRead() { SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "foo", 0, pos > 0 ? pos + (refOffset > 0 ? refOffset : 0): 1, readBases.getBytes(), quals); //if ( cigar != null ) read.setAlignmentEnd(readBases.getBytes().length + pos); read.setCigarString( cigar == null ? String.format("%dM", quals.length) : cigar); return read; } } @DataProvider(name = "data") public Object[][] createData1() { List<BAQTest> params = new ArrayList<BAQTest>(); params.add(new BAQTest("GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTTCTCCTGCTCCTGCGTGATCCGCTGCAG", "GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTCCTCCTGCTCCTGCGTGATCCGCTGCAG", "?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGIIHGGGIHHIIHIIHIIHGICCIGEII@IGIHCG", "?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGII410..0HIIHIIHIIHGICCIGEII@IGIHCE")); params.add(new BAQTest("GCTTTTTCTCCTCCTG", "GCTTTTCCTCCTCCTG", "IIHGGGIHHIIHHIIH", "EI410..0HIIHHIIE")); // big and complex, also does a cap from 3 to 4! params.add(new BAQTest(-3, 9999810l, "49M1I126M1I20M1I25M", "AAATTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATAG", "TTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGTAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCCACCCACCACCACGCCTGGCCTAATTTTTTTGTATTTTTAGTAGAGA", ">IHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?B3BBC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@C<>5;<A5=A;>=64>???B>=6497<<;;<;>2?>BA@??A6<<A59", ">EHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?838BC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@%<>5;<A5=A;>=64>???B;86497<<;;<;>2?>BA@??A6<<A59")); // now changes params.add(new BAQTest(-3, 9999966l, "36M", "CCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCC", "AGTAGCTGGGACTACAGGCACCCACCACCACGCCTG", "A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9", "A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9")); // raw base qualities are low -- but they shouldn't be capped params.add(new BAQTest(-3, 9999993l, "36M", "CCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATA", "CCACGCTTGGCAAAGTTTTCCGTACGTTTAGCCGAG", "33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8", "33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8")); // soft clipping // todo soft clip testing just doesn't work right now! // params.add(new BAQTest(29, 10000109l, "29S190M", // null, "GAAGGTTGAATCAAACCTTCGGTTCCAACGGATTACAGGTGTGAGCCACCGCGACCGGCCTGCTCAAGATAATTTTTAGGGCTAACTATGACATGAACCCCAAAATTCCTGTCCTCTAGATGGCAGAAACCAAGATAAAGTATCCCCACATGGCCACAAGGTTAAGCTCTTATGGACACAAAACAAGGCAGAGAAATGTCATTTGGCATTGGTTTCAGG", // params.add(new BAQTest(30, 10000373l, "30S69M1D2M", // null, "TGAAATCCTGCCTTATAGTTCCCCTAAACCCACGTTCTATCCCCAGATACTCCCCTCTTCATTACAGAACAACAAAGAAAGACAAATTCTTAGCATCAATG", // " // " // params.add(new BAQTest(5, 10000109l, "5S5M", // "GAAGGTTGAA", // null, // "HHHHHHHHHH", // "HHHHHHHHHE")); // params.add(new BAQTest(10009480l, "102M1I18M1I16M1I43M1I10M1D9M1I7M1I7M1I16M1I9M1I8M1I14M2I18M", // "AGAGATGGGGTTTCGCCATGTTGTCCAGGCTGGTCTTGAACTCCTGACCTCAAGTGATCTGCCCACCTCGGCCTCCCAAAGTGCTGGGATTACACGTGTGAAACCACCATGCCTGGTCTCTTAATTTTTCNGATTCTAATAAAATTACATTCTATTTGCTGAAAGNGTACTTTAGAGTTGAAAGAAAAAGAAAGGNGTGGAACTTCCCCTAGTAAACAAGGAAAAACNTCCATGTTATTTATTGGACCTTAAAAATAGTGAAACATCTTAAGAAAAAAAATCAATCCTA", // "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413577/675;><;==@=<>>968;6;>????:#;=?>:3072077726/6;3719;9A=9;774771#30532676??=8::97<7144448/4425#65688821515986255/5601548355551#218>96/5/8<4/.2344/914/55553)1047;:30312:4:63556565631=:62610", // "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413&!7/675;><;==@=<>>96!;6;>????:#;=?>:3!72077726/6;3719;9A=9;774771#30532676??=8::&!<7144448'$!25#65687421515986255/560!548355551#218>96!5/8<4/.2344/614(%!!53)1047;:30312:4:63556565631=:62610")); List<Object[]> params2 = new ArrayList<Object[]>(); for ( BAQTest x : params ) params2.add(new Object[]{x}); return params2.toArray(new Object[][]{}); } @Test(dataProvider = "data", enabled = true) public void testBAQWithProvidedReference(BAQTest test) { if ( test.refBases != null ) { testBAQ(test, false); } } @Test(dataProvider = "data", enabled = true) public void testBAQWithCigarAndRefLookup(BAQTest test) { if ( test.cigar != null ) { testBAQ(test, true); } } public void testBAQ(BAQTest test, boolean lookupWithFasta) { BAQ baqHMM = new BAQ(1e-3, 0.1, 7, (byte)4, false); // matches current samtools parameters SAMRecord read = test.createRead(); BAQ.BAQCalculationResult result; if ( lookupWithFasta && test.cigar != null ) result = baqHMM.calcBAQFromHMM(read, fasta); else result = baqHMM.calcBAQFromHMM(read, test.refBases.getBytes(), test.refOffset); System.out.println(Utils.dupString('-', 40)); System.out.println("reads : " + new String(test.readBases)); ValidateBAQWalker.printQuals(System.out, "in-quals:", test.quals, false); ValidateBAQWalker.printQuals(System.out, "bq-quals:", result.bq, false); for (int i = 0; i < test.quals.length; i++) { //result.bq[i] = baqHMM.capBaseByBAQ(result.rawQuals[i], result.bq[i], result.state[i], i); Assert.assertTrue(result.bq[i] >= baqHMM.getMinBaseQual() || test.expected[i] < baqHMM.getMinBaseQual(), "BQ < min base quality"); Assert.assertEquals(result.bq[i], test.expected[i], "Did not see the expected BAQ value at " + i); } } }
package org.glexey.citewidget.test; import java.util.ArrayList; import org.glexey.citewidget.Cite; import org.glexey.citewidget.LangDBManager; import android.content.Context; import android.test.InstrumentationTestCase; //import android.test.RenamingDelegatingContext; /** * @author aagaidiu * */ public class ValidateLangDBManager extends InstrumentationTestCase { private Context tst_ctx; //private RenamingDelegatingContext target_ctx; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { // context of the AndroidTestCase tst_ctx = getInstrumentation().getContext(); // otherwise file creation will fail due to lack of access. // Use renaming context not to accidentally corrupt the application files. //target_ctx = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test_"); super.setUp(); } /* (non-Javadoc) * @see android.test.InstrumentationTestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } // The main functionality of LangDBManager class is to give us quotes // let's test that it always gives us some quote, even if a stub public void testGetNextQuoteBasic() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); Cite cite = reader.getNextQuote(); assertNotNull(cite); } // LangDBManager should get the list of languages from resources upon // constructing, from string array 'languages' public void testLanguagesArrayConstruction() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); String[] langs = reader.getlanguageList(); assertNotNull(langs); assertTrue(langs.length == 3); assertTrue(langs[0].equals("ru")); assertTrue(langs[1].equals("en")); assertTrue(langs[2].equals("es")); } public void testReaderInitialization() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); // Create a set of 2 dictionaries per language, e.g.: "ru.fix", "ru.web" reader.initFromScratch(); Cite cite = reader.getNextQuote(); assertTrue(cite.equals(new Cite("Цитата номер 1|Алексей"))); } // Add a quote to the specified dictionary public void testAddQuote() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); // Create a set of 2 dictionaries per language, e.g.: "ru.fix", "ru.web" reader.initFromScratch(); Cite cite1 = new Cite("Test quote"); reader.addQuote("ru.web", cite1); Cite cite2 = reader.getNextQuote("ru.web"); assertTrue(cite1.equals(cite2)); } public void testOrder() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); // Create a set of 2 dictionaries per language, e.g.: "ru.fix", "ru.web" reader.initFromScratch(); reader.addQuote("ru.fix", new Cite("ru_fix1")); reader.addQuote("en.fix", new Cite("en_fix1")); reader.addQuote("es.fix", new Cite("es_fix1")); reader.addQuote("es.fix", new Cite("es_fix2")); // Now we should have 12 quotes assertTrue(reader.getNextQuote().equals(new Cite("ru_fix1"))); assertTrue(reader.getNextQuote().equals(new Cite("en_fix1"))); assertTrue(reader.getNextQuote().equals(new Cite("es_fix2"))); // first in last out assertTrue(reader.getNextQuote().equals(new Cite("es_fix1"))); assertTrue(reader.getNextQuote().equals(new Cite("Цитата номер 1|Алексей"))); assertTrue(reader.getNextQuote().equals(new Cite("English quote 1|Alexey"))); assertTrue(reader.getNextQuote().equals(new Cite("Cita Española 1|Alexei"))); assertTrue(reader.getNextQuote().equals(new Cite("Цитата номер 2|Настя"))); assertTrue(reader.getNextQuote().equals(new Cite("English quote 2|Nastuu"))); assertTrue(reader.getNextQuote().equals(new Cite("Cita Española 2|Nastya"))); assertTrue(reader.getNextQuote().equals(new Cite("Цитата номер 3|Федя|5 лет"))); assertTrue(reader.getNextQuote().equals(new Cite("English quote 3|Fyodor|5 years"))); assertTrue(reader.getNextQuote().equals(new Cite("Cita Española 3|Fedya|5 años"))); } public void testHistory() { LangDBManager reader = new LangDBManager(tst_ctx, R.array.languages); // Create a set of 2 dictionaries per language, e.g.: "ru.fix", "ru.web" reader.initFromScratch(); Cite[] cite = new Cite[10]; for (int i=0; i<10; i++) { cite[i] = reader.getNextQuote(); } // test set contains 9 quotes, so 10th should return a stub assertTrue(cite[9].equals(LangDBManager.stubCite)); ArrayList<Cite> hist = reader.getQuoteHistory(); assertNotNull(hist); assertEquals(9, hist.size()); for (int i=8; i>=0; i Cite histCite = hist.get(8-i); assertEquals(cite[i], histCite); } // Blow up past max history size and then check history stays at max size for(int i=0; i<LangDBManager.historySize+10; i++) reader.addQuote("ru.web", new Cite("Cite" + i)); ArrayList<Cite> maxhist = reader.getQuoteHistory(); assertEquals(LangDBManager.historySize, maxhist.size()); } public void testLanguageDisabling() { fail("testLanguageDisabling() not yet written"); } }
package HxCKDMS.HxCEnchants.Handlers; import HxCKDMS.HxCCore.api.Utils.AABBUtils; import HxCKDMS.HxCEnchants.Configurations.Configurations; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.world.BlockEvent; import java.util.LinkedHashMap; import java.util.List; import static HxCKDMS.HxCEnchants.Configurations.Configurations.EnabledEnchants; import static HxCKDMS.HxCEnchants.Configurations.Configurations.EnchantIDs; import static net.minecraft.enchantment.EnchantmentHelper.getEnchantmentLevel; import static net.minecraft.enchantment.EnchantmentHelper.getEnchantments; //Null pointer checked no NPE's can happen ignoring my NPE that will never be thrown because these enchants have already been configured and checked.. @SuppressWarnings({"unchecked", "ConstantConditions", "unused"}) public class EventHandlers { private EnchantHandlers handler = new EnchantHandlers(); private int tickTimer = Configurations.updateTime; @SubscribeEvent @SuppressWarnings("unchecked") public void livingHurtEvent(LivingHurtEvent event) { if (event.entityLiving instanceof EntityPlayerMP) { handler.playerHurtEvent((EntityPlayerMP)event.entityLiving, event.source, event.ammount, event); } if (event.source.getSourceOfDamage() instanceof EntityPlayerMP && ((EntityPlayerMP) event.source.getSourceOfDamage()).getHeldItem() != null && ((EntityPlayerMP) event.source.getSourceOfDamage()).getHeldItem().hasTagCompound() && ((EntityPlayerMP) event.source.getSourceOfDamage()).getHeldItem().isItemEnchanted()) { EntityPlayerMP player = (EntityPlayerMP)event.source.getSourceOfDamage(); ItemStack item = player.getHeldItem(); LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(item); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.handleAttackEvent(player, event.entityLiving, item, event.ammount, event, enchants); } } @SubscribeEvent public void LivingDeathEvent(LivingDeathEvent event) { Entity deadent = event.entity; if (deadent instanceof EntityLivingBase && event.source.getSourceOfDamage() instanceof EntityPlayerMP && (!((EntityPlayerMP) event.source.getSourceOfDamage()).getDisplayName().contains("[")) && !(event.source.getSourceOfDamage() instanceof FakePlayer)){ EntityPlayerMP Attacker = (EntityPlayerMP) event.source.getSourceOfDamage(); ItemStack item; if (Attacker.getHeldItem() != null && (Attacker.getHeldItem().getItem() instanceof ItemSword || Attacker.getHeldItem().getItem() instanceof ItemAxe)) item = Attacker.getHeldItem(); else return; if (item.hasTagCompound() && item.isItemEnchanted()){ long chrg = item.getTagCompound().getLong("HxCEnchantCharge"); handler.handleDeathEvent(Attacker, (EntityLivingBase)deadent, item); } } } @SubscribeEvent public void onHarvestBlocks(BlockEvent.HarvestDropsEvent event) { if (event.harvester != null && event.harvester.getHeldItem() != null) { EntityPlayer player = event.harvester; ItemStack heldItem = player.getHeldItem(); long chrg = -1; if (heldItem.hasTagCompound() && heldItem.isItemEnchanted()) { LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(heldItem); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.playerMineBlockEvent(player, heldItem, event, enchants); } } } @SubscribeEvent public void breakBlockEvent(BlockEvent.BreakEvent event) { EntityPlayer player = event.getPlayer(); if (player.getHeldItem() != null && player.getHeldItem().hasTagCompound() && player.getHeldItem().isItemEnchanted()) { ItemStack item = player.getHeldItem(); int worldeater = (int) EnchantIDs.get("EarthEater"); Block block = event.block; LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(item); if (enchs.keySet().contains(worldeater)) { int l = enchs.get(worldeater), width, depth, height; height = Math.round(l / Configurations.EarthEaterHeightModifier); width = Math.round(l / Configurations.EarthEaterWidthModifier); depth = Math.round(l / Configurations.EarthEaterDepthModifier); float rot = player.getRotationYawHead(); if (player.rotationPitch < 45 && player.rotationPitch > -45) { if ((rot > 45 && rot < 135) || (rot < -45 && rot > -135)) { // System.out.println("West"); for (int x = event.x - (depth); x <= event.x; x++) { for (int y = event.y - 1; y <= event.y + (height-1); y++) { for (int z = event.z - (width/2); z <= event.z + (width/2); z++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.canMineBlock(player, x, y, z)) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } } } else if ((rot > 225 && rot < 315) || (rot < -225 && rot > -315)) { // System.out.println("East"); for (int x = event.x; x <= event.x + (depth); x++) { for (int y = event.y - 1; y <= event.y + (height-1); y++) { for (int z = event.z - (width/2); z <= event.z + (width/2); z++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.getBlock(x, y, z).getBlockHardness(player.worldObj, x ,y ,z) > 0) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } } } else if ((rot < 225 && rot > 135) || (rot < -225 && rot > -135)) { // System.out.println("North"); for (int x = event.x- (width/2); x <= event.x + (width/2); x++) { for (int y = event.y - 1; y <= event.y + (height-1); y++) { for (int z = event.z - (depth); z <= event.z; z++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.getBlock(x, y, z).getBlockHardness(player.worldObj, x ,y ,z) > 0) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } } } else { // System.out.println("South"); for (int x = event.x- (width/2); x <= event.x + (width/2); x++) { for (int y = event.y - 1; y <= event.y + (height-1); y++) { for (int z = event.z; z <= event.z + (depth); z++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.getBlock(x, y, z).getBlockHardness(player.worldObj, x ,y ,z) > 0) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } } } } else { int xMod = ((rot > 45 && rot < 135) || (rot > -45 && rot < -135) ? (height/2) : (width/2)); int zMod = ((rot > 45 && rot < 135) || (rot > -45 && rot < -135) ? (width/2) : (height/2)); for (int x = event.x - xMod; x <= event.x + xMod; x++) { for (int z = event.z - zMod; z <= event.z + zMod; z++) { if (player.rotationPitch > 45) { for (int y = event.y; y <= event.y + (depth); y++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.getBlock(x, y, z).getBlockHardness(player.worldObj, x ,y ,z) > 0) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } else { for (int y = event.y - (depth); y <= event.y; y++) { if (player.worldObj.getBlock(x, y, z).getMaterial() == block.getMaterial() && player.canHarvestBlock(player.worldObj.getBlock(x, y, z)) && player.worldObj.getBlock(x, y, z).getBlockHardness(player.worldObj, x ,y ,z) > 0) player.worldObj.breakBlock(x, y, z, !player.capabilities.isCreativeMode); } } } } } } } } @SubscribeEvent public void PlayerEvent(PlayerEvent.BreakSpeed event) { if (Configurations.EnabledEnchants.get("SpeedMine") && event.entityPlayer.getHeldItem() != null && event.entityPlayer.getHeldItem().isItemEnchanted() && getEnchantmentLevel((int) EnchantIDs.get("SpeedMine"), event.entityPlayer.getHeldItem()) > 0) event.newSpeed = (event.originalSpeed + event.originalSpeed*(getEnchantmentLevel((int) EnchantIDs.get("SpeedMine"), event.entityPlayer.getHeldItem()) / 10)); } @SubscribeEvent public void playerTickEvent(LivingEvent.LivingUpdateEvent event) { if (event.entityLiving != null && event.entityLiving instanceof EntityPlayerMP) { EntityPlayerMP player = (EntityPlayerMP)event.entityLiving; handler.playerTickEvent(player); tickTimer if (tickTimer <= 0) { tickTimer = Configurations.updateTime; handler.delayedPlayerTickEvent(player); ItemStack ArmourHelm = player.inventory.armorItemInSlot(3), ArmourChest = player.inventory.armorItemInSlot(2), ArmourLegs = player.inventory.armorItemInSlot(1), ArmourBoots = player.inventory.armorItemInSlot(0); if (ArmourChest != null && ArmourChest.hasTagCompound() && ArmourChest.isItemEnchanted()) { LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(ArmourChest); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.handleChestplateEnchant(player, ArmourChest, enchants); } if (ArmourLegs != null && ArmourLegs.hasTagCompound() && ArmourLegs.isItemEnchanted()) { LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(ArmourLegs); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.handleLeggingEnchant(player, ArmourLegs, enchants); } if (ArmourBoots != null && ArmourBoots.hasTagCompound() && ArmourBoots.isItemEnchanted()) { LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(ArmourBoots); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.handleBootEnchant(player, ArmourBoots, enchants); } if (ArmourHelm != null && ArmourHelm.hasTagCompound() && ArmourHelm.isItemEnchanted()) { LinkedHashMap<Enchantment, Integer> enchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(ArmourHelm); enchs.forEach((x, y) -> enchants.put(Enchantment.enchantmentsList[x], y)); handler.handleHelmetEnchant(player, ArmourHelm, enchants); } List ents = player.worldObj.getEntitiesWithinAABB(Entity.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), 10)); if (ArmourChest != null && ArmourChest.hasTagCompound() && ArmourChest.isItemEnchanted() && ArmourLegs != null && ArmourLegs.hasTagCompound() && ArmourLegs.isItemEnchanted() && ArmourBoots != null && ArmourBoots.hasTagCompound() && ArmourBoots.isItemEnchanted() && ArmourHelm != null && ArmourHelm.hasTagCompound() && ArmourHelm.isItemEnchanted() && !ents.isEmpty()) { LinkedHashMap<Enchantment, Integer> sharedEnchants = new LinkedHashMap<>(); LinkedHashMap<Integer, Integer> enchs = (LinkedHashMap<Integer, Integer>) getEnchantments(ArmourBoots); ((LinkedHashMap<Integer, Integer>) getEnchantments(ArmourLegs)).forEach(enchs::putIfAbsent); ((LinkedHashMap<Integer, Integer>) getEnchantments(ArmourChest)).forEach(enchs::putIfAbsent); ((LinkedHashMap<Integer, Integer>) getEnchantments(ArmourHelm)).forEach(enchs::putIfAbsent); enchs.keySet().forEach(ench -> { if (getEnchantments(ArmourBoots).containsKey(ench) && getEnchantments(ArmourLegs).containsKey(ench) && getEnchantments(ArmourChest).containsKey(ench) && getEnchantments(ArmourHelm).containsKey(ench)) { int tmpz = (int) getEnchantments(ArmourBoots).get(ench); tmpz += (int) getEnchantments(ArmourLegs).get(ench); tmpz += (int) getEnchantments(ArmourChest).get(ench); tmpz += (int) getEnchantments(ArmourHelm).get(ench); sharedEnchants.put(Enchantment.enchantmentsList[ench], tmpz); } }); ents.removeIf(ent -> ent == player); if (sharedEnchants != null && !sharedEnchants.isEmpty() && !ents.isEmpty()) handler.handleAuraEvent(player, ents, sharedEnchants); } } } } @SubscribeEvent public void livingJumpEvent(LivingEvent.LivingJumpEvent event) { if(event.entityLiving instanceof EntityPlayer && ((EntityPlayer) event.entityLiving).inventory.armorItemInSlot(1) != null && ((EntityPlayer) event.entityLiving).inventory.armorItemInSlot(1).hasTagCompound() && ((EntityPlayer) event.entityLiving).inventory.armorItemInSlot(1).isItemEnchanted()) { ItemStack legs = ((EntityPlayer) event.entityLiving).inventory.armorItemInSlot(1); int JumpBoostLevel = getEnchantmentLevel((int) EnchantIDs.get("JumpBoost"), legs); if (JumpBoostLevel > 0) { EntityPlayer player = (EntityPlayer) event.entityLiving; double JumpBuff = player.motionY + 0.1 * JumpBoostLevel; player.motionY += JumpBuff; } } } @SubscribeEvent public void livingFallEvent(LivingFallEvent event) { if (event.entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer)event.entityLiving; if (player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(0).hasTagCompound() && player.inventory.armorItemInSlot(0).isItemEnchanted()) { ItemStack boots = player.inventory.armorItemInSlot(0); int featherFall = 0, meteorFall = 0; if (EnabledEnchants.get("FeatherFall")) featherFall = getEnchantmentLevel((int) EnchantIDs.get("FeatherFall"), boots); if (EnabledEnchants.get("MeteorFall")) meteorFall = getEnchantmentLevel((int) EnchantIDs.get("MeteorFall"), boots); if (featherFall < 4 && featherFall > 0)event.distance /= featherFall; else if (featherFall > 4) event.distance = 0; if (meteorFall > 0 && event.distance > 10) { player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, event.distance / 5 * meteorFall, false); event.distance = 0; } } } } }
package at.ac.ait.ariadne.routeformat; import java.time.Duration; import java.time.ZonedDateTime; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import at.ac.ait.ariadne.routeformat.RouteSegment.Builder; import at.ac.ait.ariadne.routeformat.geojson.GeoJSONFeature; import at.ac.ait.ariadne.routeformat.geojson.GeoJSONFeatureCollection; import at.ac.ait.ariadne.routeformat.geojson.GeoJSONLineString; import at.ac.ait.ariadne.routeformat.geojson.GeoJSONPolygon; import at.ac.ait.ariadne.routeformat.instruction.Instruction; import at.ac.ait.ariadne.routeformat.location.Location; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** * A {@link RouteSegment} is a part of a route that is traveled with a single * {@link ModeOfTransport}. * <p> * It is guaranteed that at least one of the geometry types (encoded polyline or * GeoJSON) is provided. * * @author AIT Austrian Institute of Technology GmbH */ @JsonDeserialize(builder = Builder.class) @JsonInclude(Include.NON_EMPTY) public class RouteSegment { private final int nr; private final Location from; private final Location to; private final int lengthMeters; private final int durationSeconds; private final ModeOfTransport modeOfTransport; private final Optional<Integer> boardingSeconds; private final Optional<Integer> alightingSeconds; private final Optional<ZonedDateTime> departureTime; private final Optional<ZonedDateTime> arrivalTime; private final List<IntermediateStop> intermediateStops; private final Optional<GeoJSONFeature<GeoJSONPolygon>> boundingBox; private final Optional<String> geometryEncodedPolyLine; private final Optional<GeoJSONFeature<GeoJSONLineString>> geometryGeoJson; private final Optional<GeoJSONFeatureCollection<GeoJSONLineString>> geometryGeoJsonEdges; private final List<Instruction> navigationInstructions; private final List<Sproute.Accessibility> accessibility; private final Map<String, Object> additionalInfo; /** number of the segment in the route (starts with 1) */ @JsonProperty(required = true) public int getNr() { return nr; } @JsonProperty(required = true) public Location getFrom() { return from; } @JsonProperty(required = true) public Location getTo() { return to; } @JsonProperty(required = true) public int getLengthMeters() { return lengthMeters; } /** * @return the total duration for this segment including * {@link #getBoardingSeconds()} and {@link #getAlightingSeconds()} */ @JsonProperty(required = true) public int getDurationSeconds() { return durationSeconds; } @JsonProperty(required = true) public ModeOfTransport getModeOfTransport() { return modeOfTransport; } /** * @return the number of seconds it takes to board (or wait for) the mode of * transport, e.g. estimated time it takes to walk to your bicycle * or car and unlock it, average time to hail a taxi, waiting time * for public transport.. */ public Optional<Integer> getBoardingSeconds() { return boardingSeconds; } /** * @return the number of seconds it takes to alight the mode of transport, * e.g. estimated time it takes to look for a parking spot for your * bicycle or car and lock/park it, average time to pay and leave a * taxi,.. */ public Optional<Integer> getAlightingSeconds() { return alightingSeconds; } /** * @return the start time of this {@link RouteSegment}, i.e. when boarding * starts */ public Optional<String> getDepartureTime() { return departureTime.map(time -> time.toString()); } @JsonIgnore public Optional<ZonedDateTime> getDepartureTimeAsZonedDateTime() { return departureTime; } /** * @return the end time of this {@link RouteSegment}, i.e. when alighting is * finished */ public Optional<String> getArrivalTime() { return arrivalTime.map(time -> time.toString()); } @JsonIgnore public Optional<ZonedDateTime> getArrivalTimeAsZonedDateTime() { return arrivalTime; } /** * intermediate stops on the way (mostly useful for public transport routes) */ public List<IntermediateStop> getIntermediateStops() { return intermediateStops; } public Optional<GeoJSONFeature<GeoJSONPolygon>> getBoundingBox() { return boundingBox; } public Optional<String> getGeometryEncodedPolyLine() { return geometryEncodedPolyLine; } /** segment geometry as a single LineString-Feature */ public Optional<GeoJSONFeature<GeoJSONLineString>> getGeometryGeoJson() { return geometryGeoJson; } /** * segment geometry as a collection of LineStrings (one for each edge in the * routing graph) with debugging information for each edge */ public Optional<GeoJSONFeatureCollection<GeoJSONLineString>> getGeometryGeoJsonEdges() { return geometryGeoJsonEdges; } public List<Instruction> getNavigationInstructions() { return navigationInstructions; } /** * @return the ordered list of potential obstacles for mobility impaired * persons (e.g. first up the elevator, then up the stairs,..) */ public List<Sproute.Accessibility> getAccessibility() { return accessibility; } /** * @return additional information, e.g. other weights for the segment * (energy,..) */ public Map<String, Object> getAdditionalInfo() { return additionalInfo; } private RouteSegment(Builder builder) { this.nr = builder.nr; this.from = builder.from; this.to = builder.to; this.lengthMeters = builder.lengthMeters; this.durationSeconds = builder.durationSeconds; this.modeOfTransport = builder.modeOfTransport; this.boardingSeconds = builder.boardingSeconds; this.alightingSeconds = builder.alightingSeconds; this.departureTime = builder.departureTime; this.arrivalTime = builder.arrivalTime; this.intermediateStops = builder.intermediateStops; this.boundingBox = builder.boundingBox; this.geometryEncodedPolyLine = builder.geometryEncodedPolyLine; this.geometryGeoJson = builder.geometryGeoJson; this.geometryGeoJsonEdges = builder.geometryGeoJsonEdges; this.navigationInstructions = builder.navigationInstructions; this.accessibility = builder.accessibility; this.additionalInfo = builder.additionalInfo; } public static Builder builder() { return new Builder(); } @Override public String toString() { return "RouteSegment [nr=" + nr + ", from=" + from + ", to=" + to + ", lengthMeters=" + lengthMeters + ", durationSeconds=" + durationSeconds + ", modeOfTransport=" + modeOfTransport + ", boardingSeconds=" + boardingSeconds + ", alightingSeconds=" + alightingSeconds + ", departureTime=" + departureTime + ", arrivalTime=" + arrivalTime + "]"; } public static class Builder { private Integer nr; private Location from; private Location to; private Integer lengthMeters; private Integer durationSeconds; private ModeOfTransport modeOfTransport; private Optional<Integer> boardingSeconds = Optional.empty(); private Optional<Integer> alightingSeconds = Optional.empty(); private Optional<ZonedDateTime> departureTime = Optional.empty(); private Optional<ZonedDateTime> arrivalTime = Optional.empty(); private List<IntermediateStop> intermediateStops = Collections.emptyList(); private Optional<GeoJSONFeature<GeoJSONPolygon>> boundingBox = Optional.empty(); private Optional<String> geometryEncodedPolyLine = Optional.empty(); private Optional<GeoJSONFeature<GeoJSONLineString>> geometryGeoJson = Optional.empty(); private Optional<GeoJSONFeatureCollection<GeoJSONLineString>> geometryGeoJsonEdges = Optional.empty(); private List<Instruction> navigationInstructions = Collections.emptyList(); private List<Sproute.Accessibility> accessibility = Collections.emptyList(); private Map<String, Object> additionalInfo = Collections.emptyMap(); public Builder withNr(int nr) { this.nr = nr; return this; } public Builder withFrom(Location from) { this.from = from; return this; } public Builder withTo(Location to) { this.to = to; return this; } public Builder withLengthMeters(int lengthMeters) { this.lengthMeters = lengthMeters; return this; } public Builder withDurationSeconds(int durationSeconds) { this.durationSeconds = durationSeconds; return this; } public Builder withModeOfTransport(ModeOfTransport modeOfTransport) { this.modeOfTransport = modeOfTransport; return this; } public Builder withBoardingSeconds(Integer boardingSeconds) { this.boardingSeconds = Optional.ofNullable(boardingSeconds); return this; } public Builder withAlightingSeconds(Integer alightingSeconds) { this.alightingSeconds = Optional.ofNullable(alightingSeconds); return this; } @JsonIgnore public Builder withDepartureTime(ZonedDateTime departureTime) { this.departureTime = Optional.ofNullable(departureTime); return this; } @JsonProperty public Builder withDepartureTime(String departureTime) { this.departureTime = Optional.ofNullable(SprouteUtils.parseZonedDateTime(departureTime, "departureTime")); return this; } @JsonIgnore public Builder withArrivalTime(ZonedDateTime arrivalTime) { this.arrivalTime = Optional.ofNullable(arrivalTime); return this; } @JsonProperty public Builder withArrivalTime(String arrivalTime) { this.arrivalTime = Optional.ofNullable(SprouteUtils.parseZonedDateTime(arrivalTime, "arrivalTime")); return this; } public Builder withIntermediateStops(List<IntermediateStop> intermediateStops) { this.intermediateStops = ImmutableList.copyOf(intermediateStops); return this; } public Builder withBoundingBox(GeoJSONFeature<GeoJSONPolygon> boundingBox) { this.boundingBox = Optional.ofNullable(boundingBox); return this; } public Builder withGeometryEncodedPolyLine(String geometryEncodedPolyLine) { this.geometryEncodedPolyLine = Optional.ofNullable(geometryEncodedPolyLine); return this; } public Builder withGeometryGeoJson(GeoJSONFeature<GeoJSONLineString> geometryGeoJson) { this.geometryGeoJson = Optional.ofNullable(geometryGeoJson); return this; } public Builder withGeometryGeoJsonEdges(GeoJSONFeatureCollection<GeoJSONLineString> geometryGeoJsonEdges) { this.geometryGeoJsonEdges = Optional.ofNullable(geometryGeoJsonEdges); return this; } public Builder withNavigationInstructions(List<Instruction> navigationInstructions) { this.navigationInstructions = ImmutableList.copyOf(navigationInstructions); return this; } public Builder withAccessibility(List<Sproute.Accessibility> accessibility) { this.accessibility = ImmutableList.copyOf(accessibility); return this; } public Builder withAdditionalInfo(Map<String, Object> additionalInfo) { this.additionalInfo = ImmutableMap.copyOf(additionalInfo); return this; } public RouteSegment build() { validate(); return new RouteSegment(this); } private void validate() { Preconditions.checkArgument(nr != null, "nr is mandatory but missing"); Preconditions.checkArgument(from != null, "from is mandatory but missing"); Preconditions.checkArgument(to != null, "to is mandatory but missing"); Preconditions.checkArgument(lengthMeters != null, "lengthMeters is mandatory but missing"); Preconditions.checkArgument(durationSeconds != null, "durationSeconds is mandatory but missing"); Preconditions.checkArgument(modeOfTransport != null, "modeOfTransport is mandatory but missing"); Preconditions.checkArgument(nr > 0, "nr must be > 0, but was %s", nr); Preconditions.checkArgument(lengthMeters >= 0, "lengthMeters must be >= 0, but was %s", lengthMeters); Preconditions.checkArgument(durationSeconds >= 0, "durationSeconds must be >= 0, but was %s", durationSeconds); Preconditions.checkArgument(alightingSeconds.orElse(0) + boardingSeconds.orElse(0) <= durationSeconds, "boarding+alighting seconds must be equal to or smaller than the total duration"); if (departureTime.isPresent() && arrivalTime.isPresent()) { Preconditions.checkArgument(!arrivalTime.get().isBefore(departureTime.get()), "departureTime must be <= arrivalTime"); long durationBetweenTimestamps = Duration.between(departureTime.get(), arrivalTime.get()).getSeconds(); Preconditions.checkArgument(durationSeconds == durationBetweenTimestamps, "durationSeconds does not match seconds between arrival & departure time: %s!=%s", durationSeconds, durationBetweenTimestamps); String error = "timestamps of intermediate stops must fall in interval between departure & arrival of this segment"; for (IntermediateStop stop : intermediateStops) { Preconditions.checkArgument(isBetween(departureTime.get(), stop.getPlannedArrivalTimeAsZonedDateTime(), arrivalTime.get()), error); Preconditions.checkArgument(isBetween(departureTime.get(), stop.getPlannedDepartureTimeAsZonedDateTime(), arrivalTime.get()), error); Preconditions.checkArgument(isBetween(departureTime.get(), stop.getEstimatedArrivalTimeAsZonedDateTime(), arrivalTime.get()), error); Preconditions.checkArgument(isBetween(departureTime.get(), stop.getEstimatedDepartureTimeAsZonedDateTime(), arrivalTime.get()), error); } } boolean geometryPresent = geometryEncodedPolyLine.isPresent() || geometryGeoJson.isPresent() || geometryGeoJsonEdges.isPresent(); Preconditions.checkArgument(geometryPresent, "at least one geometry must be present"); } /** * @return <code>true</code> if 'between' is really between (or equal) * to start and end */ private boolean isBetween(ZonedDateTime start, Optional<ZonedDateTime> between, ZonedDateTime end) { if (between.isPresent()) { if (start.isAfter(between.get()) || end.isBefore(between.get())) return false; } return true; } } }
package at.ac.tuwien.inso.service; import at.ac.tuwien.inso.entity.StudyPlan; import at.ac.tuwien.inso.entity.Subject; import at.ac.tuwien.inso.entity.SubjectForStudyPlan; import at.ac.tuwien.inso.repository.StudyPlanRepository; import at.ac.tuwien.inso.repository.SubjectForStudyPlanRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudyPlanService { @Autowired private StudyPlanRepository studyPlanRepository; @Autowired private SubjectForStudyPlanRepository subjectForStudyPlanRepository; public StudyPlan create(StudyPlan studyPlan) { return studyPlanRepository.save(studyPlan); } public Iterable<StudyPlan> getAllStudyPlans() { return studyPlanRepository.findAll(); } public StudyPlan getStudyPlanById(Long id) { return studyPlanRepository.findStudyPlanById(id); } public Iterable<SubjectForStudyPlan> getSubjectsForStudyPlan(Long id) { return subjectForStudyPlanRepository.findByStudyPlanIdOrderBySemesterRecommendation(id); } }
package com.backendless; import com.backendless.async.callback.AsyncCallback; import com.backendless.async.message.AsyncMessage; import com.backendless.cache.CacheService; import com.backendless.cache.ICache; import com.backendless.core.ResponseCarrier; import com.backendless.core.responder.AdaptingResponder; import com.backendless.core.responder.policy.PoJoAdaptingPolicy; import com.backendless.exceptions.BackendlessException; import com.backendless.exceptions.BackendlessFault; import weborb.client.IChainedResponder; import weborb.types.IAdaptingType; import weborb.util.io.ISerializer; public class Cache { private final static String CACHE_SERVER_ALIAS = "com.backendless.services.redis.CacheService"; private final static Cache instance = new Cache(); static Cache getInstance() { return instance; } private Cache() { } public <T> ICache<T> with( String key, Class<? extends T> type ) { return new CacheService<T>( type, key ); } public void put( final String key, final Object object, final Integer expire, final AsyncCallback<Object> callback ) { ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { putSync( key, object, expire ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new Object(), callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new BackendlessFault( e ), callback ) ); } } } ); } public void put( final String key, final Object object, final AsyncCallback<Object> callback ) { put( key, object, null, callback ); } public void put( String key, Object object ) { put( key, object, (Integer) null ); } public void put( String key, Object object, Integer expire ) { put( key, object, expire, new AsyncCallback<Object>() { @Override public void handleResponse( Object response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } public void putSync( String key, Object object ) { putSync( key, object, null ); } public void putSync( String key, Object object, Integer expire ) { byte[] bytes = serialize( object ); Invoker.invokeSync( CACHE_SERVER_ALIAS, "putBytes", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), key, bytes, expire }, getChainedResponder() ); } public <T> T getSync( String key, Class<T> clazz ) { byte[] bytes = Invoker.invokeSync( CACHE_SERVER_ALIAS, "getBytes", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), key }, new AdaptingResponder<byte[]>( byte[].class, new PoJoAdaptingPolicy<byte[]>() ) ); if( bytes == null ) return null; return (T) deserialize( bytes, clazz ); } public Object getSync( String key ) { return getSync( key, null ); } public void get( String key, AsyncCallback<Object> callback ) { get( key, callback ); } public <T> void get( final String key, final Class<? extends T> clazz, final AsyncCallback<T> callback ) { ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { T result = getSync( key, clazz ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( result, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new BackendlessFault( e ), callback ) ); } } } ); } public Boolean containsSync( String key ) { return Invoker.invokeSync( CACHE_SERVER_ALIAS, "containsKey", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), key }, getChainedResponder() ); } public void contains( final String key, final AsyncCallback<Boolean> callback ) { ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { Boolean isContains = containsSync( key ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<Boolean>( isContains, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new BackendlessFault( e ), callback ) ); } } } ); } public void expireSync( String key, int expire ) { Invoker.invokeSync( CACHE_SERVER_ALIAS, "extendLife", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), key, expire }, getChainedResponder() ); } public void expire( final String key, final int expire ) { expire( key, expire, new AsyncCallback<Object>() { @Override public void handleResponse( Object response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } public void expire( final String key, final int expire, final AsyncCallback<Object> callback ) { ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { expireSync( key, expire ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<Object>( null, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new BackendlessFault( e ), callback ) ); } } } ); } public void deleteSync( String key ) { Invoker.invokeSync( CACHE_SERVER_ALIAS, "delete", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), key }, getChainedResponder() ); } public void delete( final String key ) { delete( key, new AsyncCallback<Object>() { @Override public void handleResponse( Object response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } public void delete( final String key, final AsyncCallback<Object> callback ) { ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { deleteSync( key ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<Object>( null, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage( new BackendlessFault( e ), callback ) ); } } } ); } private static <T> IChainedResponder getChainedResponder() { return new AdaptingResponder<T>(); } private static Object deserialize( byte[] bytes, Class clazz ) { Object object = null; try { object = weborb.util.io.Serializer.fromBytes( bytes, ISerializer.AMF3, false ); if( object instanceof IAdaptingType ) return clazz == null ? ((IAdaptingType) object).defaultAdapt() : ((IAdaptingType) object).adapt( clazz ); } catch( Exception e ) { throw new BackendlessException( e ); } return object; } private static byte[] serialize( Object object ) { byte[] bytes; try { bytes = weborb.util.io.Serializer.toBytes( object, ISerializer.AMF3 ); } catch( Exception e ) { throw new BackendlessException( e ); } return bytes; } }
package bammerbom.ultimatecore.sponge; import bammerbom.ultimatecore.sponge.api.command.CommandService; import bammerbom.ultimatecore.sponge.api.event.module.ModuleInitializeEvent; import bammerbom.ultimatecore.sponge.api.event.module.ModulePostInitializeEvent; import bammerbom.ultimatecore.sponge.api.event.module.ModuleStoppingEvent; import bammerbom.ultimatecore.sponge.api.module.Module; import bammerbom.ultimatecore.sponge.api.module.ModuleService; import bammerbom.ultimatecore.sponge.api.permission.PermissionService; import bammerbom.ultimatecore.sponge.api.sign.SignService; import bammerbom.ultimatecore.sponge.api.teleport.TeleportService; import bammerbom.ultimatecore.sponge.api.tick.TickService; import bammerbom.ultimatecore.sponge.api.user.UserService; import bammerbom.ultimatecore.sponge.api.variable.VariableService; import bammerbom.ultimatecore.sponge.config.CommandsConfig; import bammerbom.ultimatecore.sponge.config.GeneralConfig; import bammerbom.ultimatecore.sponge.config.ModulesConfig; import bammerbom.ultimatecore.sponge.config.serializers.ItemStackSnapshotSerializer; import bammerbom.ultimatecore.sponge.config.serializers.TransformSerializer; import bammerbom.ultimatecore.sponge.config.serializers.Vector3dSerializer; import bammerbom.ultimatecore.sponge.impl.command.UCCommandService; import bammerbom.ultimatecore.sponge.impl.module.UCModuleService; import bammerbom.ultimatecore.sponge.impl.permission.UCPermissionService; import bammerbom.ultimatecore.sponge.impl.teleport.UCTeleportService; import bammerbom.ultimatecore.sponge.impl.tick.UCTickService; import bammerbom.ultimatecore.sponge.impl.user.UCUserService; import bammerbom.ultimatecore.sponge.impl.variable.UCVariableService; import bammerbom.ultimatecore.sponge.utils.*; import com.flowpowered.math.vector.Vector3d; import com.google.common.reflect.TypeToken; import com.google.inject.Inject; import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection; import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; import org.spongepowered.api.Platform; import org.spongepowered.api.Sponge; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.game.GameReloadEvent; import org.spongepowered.api.event.game.state.*; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.service.ServiceManager; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import java.util.Optional; import java.util.logging.Logger; @Plugin(id = "ultimatecore", name = "UltimateCore", version = "@VERSION@", description = "All you need to set up a server and more!", url = "http://ultimatecore.org/index", authors = {"Bammerbom"}) public class UltimateCore { private static UltimateCore instance = null; //Config files private GeneralConfig generalConfig; private CommandsConfig commandsConfig; private ModulesConfig modulesConfig; @Inject @ConfigDir(sharedRoot = false) public Path dir; @Inject private Logger logger; //Did uc start yet? boolean started = false; //Bstats @Inject private Metrics metrics; public static UltimateCore get() { if (instance == null) { instance = new UltimateCore(); } return instance; } @Listener(order = Order.LATE) public void onPreInit(GamePreInitializationEvent ev) { try { if (Sponge.getPlatform().getType().equals(Platform.Type.CLIENT)) { return; } Long time = System.currentTimeMillis(); //Save instance instance = this; //Load utils ServerID.start(); Messages.reloadEnglishMessages(); //Register serializers because sponge doesn't for some reason TypeSerializerCollection serializers = TypeSerializers.getDefaultSerializers(); // serializers.registerType(TypeToken.of(BlockState.class), new BlockStateSerializer()); serializers.registerType(TypeToken.of(ItemStackSnapshot.class), new ItemStackSnapshotSerializer()); serializers.registerType(TypeToken.of(Transform.class), new TransformSerializer()); serializers.registerType(TypeToken.of(Vector3d.class), new Vector3dSerializer()); //Config generalConfig = new GeneralConfig(); generalConfig.reload(); commandsConfig = new CommandsConfig(); commandsConfig.preload(); modulesConfig = new ModulesConfig(); modulesConfig.preload(); Messages.reloadCustomMessages(); //Load services UCModuleService moduleService = new UCModuleService(); UCCommandService commandService = new UCCommandService(); UCUserService userService = new UCUserService(); UCPermissionService permissionService = new UCPermissionService(); UCTeleportService teleportService = new UCTeleportService(); UCTickService tickService = new UCTickService(); tickService.init(); UCVariableService variableService = new UCVariableService(); variableService.init(); //Register services ServiceManager sm = Sponge.getServiceManager(); sm.setProvider(this, ModuleService.class, moduleService); sm.setProvider(this, CommandService.class, commandService); sm.setProvider(this, UserService.class, userService); sm.setProvider(this, PermissionService.class, permissionService); sm.setProvider(this, TeleportService.class, teleportService); sm.setProvider(this, TickService.class, tickService); sm.setProvider(this, VariableService.class, variableService); //Load modules for (Module module : moduleService.findModules()) { try { if (moduleService.registerModule(module)) { if (!module.getIdentifier().equals("default")) { Messages.log(Messages.getFormatted("core.load.module.registered", "%module%", module.getIdentifier())); } } } catch (Exception ex) { ErrorLogger.log(ex, "Failed to register module " + module.getIdentifier()); } } time = System.currentTimeMillis() - time; Messages.log(Messages.getFormatted("core.load.preinit", "%ms%", time)); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to pre-initialize UltimateCore"); } } @Listener public void onInit(GameInitializationEvent ev) { try { if (Sponge.getPlatform().getType().equals(Platform.Type.CLIENT)) { System.out.println("[UC] You are running UC on a client. Waiting with starting the game until getServer() is available."); return; } started = true; Long time = System.currentTimeMillis(); //Initialize modules for (Module module : getModuleService().getModules()) { try { ModuleInitializeEvent event = new ModuleInitializeEvent(module, ev, Cause.builder().owner(this).build()); Sponge.getEventManager().post(event); module.onInit(ev); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to initialize module " + module.getIdentifier()); } } time = System.currentTimeMillis() - time; Messages.log(Messages.getFormatted("core.load.init", "%ms%", time)); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to initialize UltimateCore"); } } @Listener public void onPostInit(GamePostInitializationEvent ev) { try { if (Sponge.getPlatform().getType().equals(Platform.Type.CLIENT)) { return; } Long time = System.currentTimeMillis(); //All commands should be registered by now commandsConfig.postload(); modulesConfig.postload(); //Add custom bstats charts metrics.addCustomChart(new Metrics.AdvancedPie("modules") { @Override public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) { HashMap<String, Integer> modules = new HashMap<>(); UltimateCore.get().getModuleService().getModules().forEach(module -> { modules.put(module.getIdentifier(), 1); }); return modules; } }); metrics.addCustomChart(new Metrics.SimplePie("language") { @Override public String getValue() { return getGeneralConfig().get().getNode("language", "language").getString(); } }); metrics.addCustomChart(new Metrics.SimplePie("platform") { @Override public String getValue() { return StringUtil.firstUpperCase(Sponge.getPlatform().getType().name()); } }); metrics.addCustomChart(new Metrics.SimplePie("implementation") { @Override public String getValue() { return Sponge.getPlatform().getContainer(Platform.Component.IMPLEMENTATION).getName(); } }); //Post-initialize modules for (Module module : getModuleService().getModules()) { try { ModulePostInitializeEvent event = new ModulePostInitializeEvent(module, ev, Cause.builder().owner(this).build()); Sponge.getEventManager().post(event); module.onPostInit(ev); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to post initialize module " + module.getIdentifier()); } } time = System.currentTimeMillis() - time; Messages.log(Messages.getFormatted("core.load.postinit", "%ms%", time)); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to post-initialize UltimateCore"); } } @Listener public void onStart(GameStartingServerEvent ev) { //On a client, wait until the Sponge.getServer() is available and then load UC if (Sponge.getPlatform().getType().equals(Platform.Type.CLIENT) && !started) { onPreInit(null); onInit(null); onPostInit(null); return; } } @Listener public void onStopping(GameStoppingEvent ev) { try { Long time = System.currentTimeMillis(); //Stop modules for (Module module : getModuleService().getModules()) { try { ModuleStoppingEvent event = new ModuleStoppingEvent(module, ev, Cause.builder().owner(this).build()); Sponge.getEventManager().post(event); module.onStop(ev); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to stop module " + module.getIdentifier()); } } time = System.currentTimeMillis() - time; Messages.log(Messages.getFormatted("core.load.stop", "%ms%", time)); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to stop UltimateCore"); } } @Listener public void onStart(GameStartedServerEvent ev) { getCommandService().registerLateCommands(); } @Listener public void onReload(GameReloadEvent event) { try { Long time = System.currentTimeMillis(); UltimateCore.get().getGeneralConfig().reload(); UltimateCore.get().getCommandsConfig().preload(); UltimateCore.get().getCommandsConfig().postload(); UltimateCore.get().getModulesConfig().preload(); UltimateCore.get().getModulesConfig().postload(); for (Module mod : UltimateCore.get().getModuleService().getModules()) { if (mod.getConfig().isPresent()) { mod.getConfig().get().reload(); mod.onReload(event); } } Messages.reloadMessages(); time = System.currentTimeMillis() - time; Messages.log(Messages.getFormatted("core.load.reload", "%ms%", time)); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to stop UltimateCore"); } } public Path getConfigFolder() { return dir; } public Path getDataFolder() { return new File("ultimatecore").toPath(); } //TODO move these methods??? public ModuleService getModuleService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(ModuleService.class).orElse(null); } public CommandService getCommandService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(CommandService.class).orElse(null); } public UserService getUserService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(UserService.class).orElse(null); } public PermissionService getPermissionService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(PermissionService.class).orElse(null); } public TeleportService getTeleportService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(TeleportService.class).orElse(null); } public TickService getTickService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(TickService.class).orElse(null); } public VariableService getVariableService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(VariableService.class).orElse(null); } public Optional<SignService> getSignService() { ServiceManager manager = Sponge.getServiceManager(); return manager.provide(SignService.class); } //Get configs public GeneralConfig getGeneralConfig() { return generalConfig; } public CommandsConfig getCommandsConfig() { return commandsConfig; } public ModulesConfig getModulesConfig() { return modulesConfig; } }
package com.gh4a; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.ViewGroup; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.gh4a.fragment.PrivateEventListFragment; import com.gh4a.fragment.PublicEventListFragment; import com.gh4a.fragment.RepositoryIssueListFragment; import com.gh4a.fragment.UserFragment; public class UserActivity extends BaseSherlockFragmentActivity { public String mUserLogin; public String mUserName; private UserAdapter mAdapter; private ViewPager mPager; private ActionBar mActionBar; private boolean isLoginUserPage; private int tabCount; @Override public void onCreate(Bundle savedInstanceState) { setTheme(Gh4Application.THEME); super.onCreate(savedInstanceState); setContentView(R.layout.view_pager); Bundle data = getIntent().getExtras(); mUserLogin = data.getString(Constants.User.USER_LOGIN); mUserName = data.getString(Constants.User.USER_NAME); int position = data.getInt("position"); isLoginUserPage = mUserLogin.equals(getAuthLogin()); if (isLoginUserPage) { tabCount = 4; } else { tabCount = 2; } mActionBar = getSupportActionBar(); mActionBar.setTitle(mUserLogin); mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); if (mUserLogin.equals(getAuthLogin())) { mActionBar.setHomeButtonEnabled(false); } else { mActionBar.setDisplayHomeAsUpEnabled(true); } mAdapter = new UserAdapter(getSupportFragmentManager()); mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); mPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) {} @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageSelected(int position) { Log.i(Constants.LOG_TAG, ">>>>>>>>>>> onPageSelected " + position); mActionBar.setSelectedNavigationItem(position); invalidateOptionsMenu(); } }); Tab tab = mActionBar .newTab() .setText(R.string.about) .setTabListener( new TabListener<SherlockFragmentActivity>(this, 0 + "", mPager)); mActionBar.addTab(tab, position == 0); tab = mActionBar .newTab() .setText(isLoginUserPage ? R.string.user_news_feed : R.string.user_public_activity) .setTabListener( new TabListener<SherlockFragmentActivity>(this, 1 + "", mPager)); mActionBar.addTab(tab, position == 1); if (isLoginUserPage) { tab = mActionBar .newTab() .setText(R.string.user_your_actions) .setTabListener( new TabListener<SherlockFragmentActivity>(this, 2 + "", mPager)); mActionBar.addTab(tab, position == 2); tab = mActionBar .newTab() .setText(R.string.issues) .setTabListener( new TabListener<SherlockFragmentActivity>(this, 3 + "", mPager)); mActionBar.addTab(tab, position == 3); } } public class UserAdapter extends FragmentStatePagerAdapter { public UserAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return tabCount; } @Override public android.support.v4.app.Fragment getItem(int position) { Log.i(Constants.LOG_TAG, ">>>>>>>>>>> getItem " + position); if (position == 0) { return UserFragment.newInstance(UserActivity.this.mUserLogin, UserActivity.this.mUserName); } else if (position == 1) { return PrivateEventListFragment.newInstance(UserActivity.this.mUserLogin, UserActivity.this.isLoginUserPage); } else if (position == 2 && isLoginUserPage) { return PublicEventListFragment.newInstance(UserActivity.this.mUserLogin, false); } else if (position == 3 && isLoginUserPage) { Map<String, String> filterData = new HashMap<String, String>(); filterData.put("filter", "subscribed"); return RepositoryIssueListFragment.newInstance(filterData); } else { return UserFragment.newInstance(UserActivity.this.mUserLogin, UserActivity.this.mUserName); } } @Override public void destroyItem(ViewGroup container, int position, Object object) { Log.i(Constants.LOG_TAG, ">>>>>>>>>>> destroyItem " + container + ", " + position + ", " + object); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(Constants.LOG_TAG, ">>>>>>>>>>> onConfigurationChanged " + newConfig.orientation); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { //invalidateOptionsMenu(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.user_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean setMenuOptionItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getApplicationContext().openUserInfoActivity(this, getAuthLogin(), null, Intent.FLAG_ACTIVITY_CLEAR_TOP); return true; case R.id.refresh: Intent intent = new Intent().setClass(this, UserActivity.class); intent.putExtra(Constants.User.USER_LOGIN, mUserLogin); intent.putExtra(Constants.User.USER_NAME, mUserName); intent.putExtra("position", mPager.getCurrentItem()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.theme: return true; case R.id.logout: SharedPreferences sharedPreferences = getApplication().getSharedPreferences( Constants.PREF_NAME, MODE_PRIVATE); if (sharedPreferences != null) { if (sharedPreferences.getString(Constants.User.USER_LOGIN, null) != null && sharedPreferences.getString(Constants.User.USER_AUTH_TOKEN, null) != null){ Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); intent = new Intent().setClass(this, Github4AndroidActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP |Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); this.finish(); } } return true; case R.id.dark: Gh4Application.THEME = R.style.DarkTheme; saveTheme(R.style.DarkTheme); return true; case R.id.light: Gh4Application.THEME = R.style.LightTheme; saveTheme(R.style.LightTheme); return true; case R.id.lightDark: Gh4Application.THEME = R.style.DefaultTheme; saveTheme(R.style.DefaultTheme); return true; default: return true; } } private void saveTheme(int theme) { SharedPreferences sharedPreferences = getSharedPreferences( Constants.PREF_NAME, MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putInt("THEME", theme); editor.commit(); recreate(); } @Override public void recreate() { //This SUCKS! Figure out a way to call the super method and support Android 1.6 /* if (IS_HONEYCOMB) { super.recreate(); } else { */ final Intent intent = getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { OverridePendingTransition.invoke(this); } finish(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { OverridePendingTransition.invoke(this); } } private static final class OverridePendingTransition { static void invoke(Activity activity) { activity.overridePendingTransition(0, 0); } } }
package ca.gc.ip346.classification.cors; import static org.apache.logging.log4j.Level.DEBUG; import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Provider public class CORSFilter implements ContainerResponseFilter { private static final Logger logger = LogManager.getLogger(CORSFilter.class); @Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); responseContext.getHeaders().add("Access-Control-Allow-Headers", "ORIGIN, CONTENT_TYPE, ACCEPT, AUTHORIZATION, ACCESS_CONTROL_ALLOW_ORIGIN"); responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true"); responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");; logger.printf(DEBUG, "%s%s%s\n", "", "Romario's CORS Magic!!", ""); } }
package co.phoenixlab.discord.commands; import co.phoenixlab.common.lang.SafeNav; import co.phoenixlab.common.localization.Localizer; import co.phoenixlab.discord.CommandDispatcher; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.VahrhedralBot; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Role; import co.phoenixlab.discord.api.entities.Server; import co.phoenixlab.discord.api.entities.User; import co.phoenixlab.discord.api.event.MemberChangeEvent; import co.phoenixlab.discord.api.event.MemberChangeEvent.MemberChange; import co.phoenixlab.discord.commands.tempstorage.ServerTimeout; import co.phoenixlab.discord.commands.tempstorage.ServerTimeoutStorage; import co.phoenixlab.discord.util.WeakEventSubscriber; import co.phoenixlab.discord.util.adapters.DurationGsonTypeAdapter; import co.phoenixlab.discord.util.adapters.InstantGsonTypeAdapter; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; import static co.phoenixlab.discord.VahrhedralBot.LOGGER; import static co.phoenixlab.discord.api.DiscordApiClient.*; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; public class ModCommands { private final CommandDispatcher dispatcher; private Localizer loc; private final VahrhedralBot bot; private final DiscordApiClient apiClient; private final Consumer<MemberChangeEvent> memberJoinListener; private final Map<String, ServerTimeoutStorage> timeoutStorage; private static final Path serverStorageDir = Paths.get("config/tempServerStorage/"); private final Gson gson; public ModCommands(VahrhedralBot bot) { this.bot = bot; dispatcher = new CommandDispatcher(bot, ""); loc = bot.getLocalizer(); apiClient = bot.getApiClient(); memberJoinListener = this::onMemberJoinedServer; timeoutStorage = new HashMap<>(); gson = new GsonBuilder(). registerTypeAdapter(Instant.class, new InstantGsonTypeAdapter()). registerTypeAdapter(Duration.class, new DurationGsonTypeAdapter()). create(); } public CommandDispatcher getModCommandDispatcher() { return dispatcher; } public void registerModCommands() { CommandDispatcher d = dispatcher; d.registerAlwaysActiveCommand("commands.mod.timeout", this::timeout); d.registerAlwaysActiveCommand("commands.mod.stoptimeout", this::stopTimeout); d.registerAlwaysActiveCommand("commands.mod.settimeoutrole", this::setTimeoutRole); EventBus eventBus = bot.getApiClient().getEventBus(); eventBus.register(new WeakEventSubscriber<>(memberJoinListener, eventBus, MemberChangeEvent.class)); } private void timeout(MessageContext context, String args) { // TODO } private void stopTimeout(MessageContext context, String args) { // TODO } private void setTimeoutRole(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); if (args.isEmpty()) { apiClient.sendMessage(loc.localize("commands.mod.settimeoutrole.response.missing"), context.getChannel()); return; } Role role = apiClient.getRole(args, context.getServer()); if (role == NO_ROLE) { apiClient.sendMessage(loc.localize("commands.mod.settimeoutrole.response.not_found", args), context.getChannel()); return; } String serverId = context.getServer().getId(); ServerTimeoutStorage storage = timeoutStorage.get(serverId); if (storage == null) { storage = new ServerTimeoutStorage(serverId); timeoutStorage.put(serverId, storage); } storage.setTimeoutRoleId(role.getId()); apiClient.sendMessage(loc.localize("commands.mod.settimeoutrole.response", role.getName(), role.getId()), context.getChannel()); } @Subscribe public void onMemberJoinedServer(MemberChangeEvent memberChangeEvent) { if (memberChangeEvent.getMemberChange() == MemberChange.ADDED) { User user = memberChangeEvent.getMember().getUser(); Server server = memberChangeEvent.getServer(); if (isUserTimedOut(user, server)) { refreshTimeoutOnEvade(user, server); } else { removeTimeout(user, server); } } } private void refreshTimeoutOnEvade(User user, Server server) { ServerTimeout timeout = SafeNav.of(timeoutStorage.get(server.getId())). next(ServerTimeoutStorage::getTimeouts). next(timeouts -> timeouts.get(user.getId())). get(); if (timeout == null) { LOGGER.warn("Attempted to refresh a timeout on a user who was not timed out!"); return; } LOGGER.info("User {} ({}) attempted to evade a timeout on {} ({})!", user.getUsername(), user.getId(), server.getName(), server.getId()); Channel channel = apiClient.getChannelById(server.getId(), server); applyTimeoutRole(user, server, channel); } /** * Applies the timeout role to the given user. This does NOT create or manage any storage/persistence, it only * sets the user's roles * * @param user The user to add to the timeout role * @param server The server on which to add the user to the timeout role * @param invocationChannel The channel to send messages on error */ public void applyTimeoutRole(User user, Server server, Channel invocationChannel) { String serverId = server.getId(); ServerTimeoutStorage storage = timeoutStorage.get(serverId); String serverName = server.getName(); if (storage != null && storage.getTimeoutRoleId() != null) { String timeoutRoleId = storage.getTimeoutRoleId(); Role timeoutRole = apiClient.getRole(timeoutRoleId, server); if (timeoutRole != NO_ROLE) { // Add role to user Set<Role> userRoles = apiClient.getMemberRoles(apiClient.getUserMember(user, server), server); // Push the ban role to the front LinkedHashSet<String> newRoles = new LinkedHashSet<>(userRoles.size() + 1); newRoles.add(timeoutRoleId); userRoles.stream().map(Role::getId). forEach(newRoles::add); // Update apiClient.updateRoles(user, server, newRoles); } else { LOGGER.warn("Timeout role ID {} for server {} ({}) does not exist", timeoutRoleId, serverName, serverId); apiClient.sendMessage(loc.localize("message.mod.timeout.bad_role", timeoutRoleId), invocationChannel); } } else { storage = new ServerTimeoutStorage(serverId); timeoutStorage.put(serverId, storage); LOGGER.warn("Timeout role for server {} ({}) is not configured", storage.getTimeoutRoleId(), serverName, serverId); apiClient.sendMessage(loc.localize("message.mod.timeout.not_configured"), invocationChannel); } } public boolean isUserTimedOut(User user, Server server) { return isUserTimedOut(user.getId(), server.getId()); } public boolean isUserTimedOut(String userId, String serverId) { ServerTimeoutStorage storage = timeoutStorage.get(serverId); if (storage != null) { ServerTimeout timeout = storage.getTimeouts().get(userId); if (timeout != null) { Instant now = Instant.now(); return timeout.getEndTime().compareTo(now) > 0; } } return false; } public void removeTimeout(User user, Server server) { // TODO } /** * Removes the timeout role from the given user. This does NOT create or manage any storage/persistence, it only * sets the user's roles * * @param user The user to remove the timeout role * @param server The server on which to remove the user from the timeout role * @param invocationChannel The channel to send messages on error */ public void removeTimeoutRole(User user, Server server, Channel invocationChannel) { String serverId = server.getId(); ServerTimeoutStorage storage = timeoutStorage.get(serverId); String serverName = server.getName(); if (storage != null && storage.getTimeoutRoleId() != null) { String timeoutRoleId = storage.getTimeoutRoleId(); Role timeoutRole = apiClient.getRole(timeoutRoleId, server); if (timeoutRole != NO_ROLE) { // Get roles Set<Role> userRoles = apiClient.getMemberRoles(apiClient.getUserMember(user, server), server); // Delete the ban role LinkedHashSet<String> newRoles = new LinkedHashSet<>(userRoles.size() - 1); userRoles.stream().map(Role::getId). filter(s -> !timeoutRoleId.equals(s)). forEach(newRoles::add); // Update apiClient.updateRoles(user, server, newRoles); } else { LOGGER.warn("Timeout role ID {} for server {} ({}) does not exist", timeoutRoleId, serverName, serverId); apiClient.sendMessage(loc.localize("message.mod.timeout.bad_role", timeoutRoleId), invocationChannel); } } else { storage = new ServerTimeoutStorage(serverId); timeoutStorage.put(serverId, storage); LOGGER.warn("Timeout role for server {} ({}) is not configured", storage.getTimeoutRoleId(), serverName, serverId); apiClient.sendMessage(loc.localize("message.mod.timeout.not_configured"), invocationChannel); } } public void saveServerTimeoutStorage(ServerTimeoutStorage storage) { try { Files.createDirectories(serverStorageDir); } catch (IOException e) { LOGGER.warn("Unable to create server storage directory", e); return; } Path serverStorageFile = serverStorageDir.resolve(storage.getServerId() + ".json"); try (BufferedWriter writer = Files.newBufferedWriter(serverStorageFile, UTF_8, CREATE, TRUNCATE_EXISTING)) { gson.toJson(storage, writer); writer.flush(); } catch (IOException e) { LOGGER.warn("Unable to write server storage file for " + storage.getServerId(), e); return; } LOGGER.info("Saved server {}", storage.getServerId()); } public void loadServerTimeoutStorageFiles() { if (!Files.exists(serverStorageDir)) { LOGGER.info("Server storage directory doesn't exist, not loading anything"); return; } try (Stream<Path> files = Files.list(serverStorageDir)) { files.filter(p -> p.getFileName().toString().endsWith(".json")). forEach(this::loadServerTimeoutStorage); } catch (IOException e) { LOGGER.warn("Unable to load server storage files", e); return; } } public void loadServerTimeoutStorage(Path path) { try (Reader reader = Files.newBufferedReader(path, UTF_8)) { ServerTimeoutStorage storage = gson.fromJson(reader, ServerTimeoutStorage.class); if (storage != null) { Server server = apiClient.getServerByID(storage.getServerId()); if (server == NO_SERVER) { LOGGER.warn("Rejecting {} server storage file: server not found", storage.getServerId()); return; } timeoutStorage.put(storage.getServerId(), storage); LOGGER.info("Loaded {} ({}) server storage file", server.getName(), server.getId()); // Prune expired entries for (Iterator<Map.Entry<String, ServerTimeout>> iter = storage.getTimeouts().entrySet().iterator(); iter.hasNext(); ) { Map.Entry<String, ServerTimeout> e = iter.next(); ServerTimeout timeout = e.getValue(); String userId = timeout.getUserId(); if (!isUserTimedOut(userId, server.getId())) { // Purge! User user = apiClient.getUserById(userId, server); if (user == NO_USER) { LOGGER.info("Ending timeout for departed user {} ({}) in {} ({})", timeout.getLastUsername(), userId, server.getName(), server.getId()); apiClient.sendMessage(loc.localize("message.mod.timeout.expire.not_found", user.getId()), server.getId()); // Don't need to remove the timeout role because leaving does that for us } else { LOGGER.info("Ending timeout for {} ({}) in {} ({})", user.getUsername(), user.getId(), server.getName(), server.getId()); apiClient.sendMessage(loc.localize("message.mod.timeout.expire", user.getId()), server.getId()); removeTimeoutRole(user, server, apiClient.getChannelById(server.getId())); } iter.remove(); } } } } catch (IOException | JsonParseException e) { LOGGER.warn("Unable to load server storage file " + path.getFileName(), e); return; } } }
package co.willsalz.ttyl.resources.v1; import co.willsalz.ttyl.entities.CallRequest; import co.willsalz.ttyl.service.PhoneService; import com.codahale.metrics.annotation.Timed; import com.twilio.rest.api.v2010.account.Call; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("v1/call") @Consumes(MediaType.APPLICATION_JSON) public class CallResource { private static final Logger logger = LoggerFactory.getLogger(CallResource.class); private final PhoneService phoneService; public CallResource(final PhoneService phoneService) { this.phoneService = phoneService; } @POST @Timed public Response makeCall(@NotNull @Valid final CallRequest callRequest) { final Call call = phoneService.makeCall(callRequest.getTo()); return Response.noContent().build(); } }
package com.akiban.server.types3.common.funcs; import com.akiban.server.types3.*; import com.akiban.server.types3.pvalue.PValueSource; import com.akiban.server.types3.pvalue.PValueTarget; import com.akiban.server.types3.texpressions.TInputSetBuilder; import com.akiban.server.types3.texpressions.TOverloadBase; import java.util.List; public abstract class Trim extends TOverloadBase { // Described by TRIM(<trim_spec>, <char_to_trim>, <string_to_trim> public static TOverload[] create(TClass stringType, TClass intType) { TOverload rtrim = new Trim(stringType, intType) { @Override protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) { String trim = (String) inputs.get(1).getObject(); String st = (String) inputs.get(2).getObject(); output.putObject(rtrim(st, trim)); } @Override public String overloadName() { return "RTRIM"; } }; TOverload ltrim = new Trim(stringType, intType) { @Override protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) { String trim = (String) inputs.get(1).getObject(); String st = (String) inputs.get(2).getObject(); output.putObject(ltrim(st, trim)); } @Override public String overloadName() { return "LTRIM"; } }; TOverload trim = new Trim(stringType, intType) { @Override protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) { int trimType = inputs.get(0).getInt32(); String trim = (String) inputs.get(1).getObject(); String st = (String) inputs.get(2).getObject(); if (trimType != RTRIM) st = ltrim(st, trim); if (trimType != LTRIM) st = rtrim(st, trim); output.putObject(st); } @Override public String overloadName() { return "TRIM"; } }; return new TOverload[]{ltrim, rtrim, trim}; } protected final int RTRIM = 0; protected final int LTRIM = 1; protected final TClass stringType; protected final TClass intType; private Trim(TClass stringType, TClass intType) { this.stringType = stringType; this.intType = intType; } @Override protected void buildInputSets(TInputSetBuilder builder) { builder.covers(intType, 0); builder.covers(stringType, 1, 2); } @Override public TOverloadResult resultType() { // actual return type is exactly the same as input type return TOverloadResult.fixed(stringType.instance()); } // Helper methods protected static String ltrim(String st, String trim) { int n, count; n = count = 0; while (n < st.length()) { count = 0; for (int i = 0; i < trim.length() && n < st.length(); ++i, ++n) { if (st.charAt(n) != trim.charAt(i)) return st.substring(n-i); else count++; } } return count == trim.length() ? "" : st.substring(n-count); } protected static String rtrim(String st, String trim) { int n = st.length() - 1; int count = 0; while (n >= 0) { count = 0; for (int i = trim.length()-1; i >= 0 && n >= 0; --i, --n) { if (st.charAt(n) != trim.charAt(i)) return st.substring(0, n + trim.length() - i); else count++; } } return count == trim.length() ? "" : st.substring(0, count); } }
package org.zalando.tracer; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Iterator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertTrue; class GeneratorTest { @Test void testUuid() { final String value = new UUIDGenerator().generate(); assertThat(value, matchesPattern("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")); } @Test void testFlowId() { final String value = new FlowIDGenerator().generate(); assertThat(value, matchesPattern("R[\\w-]{21}")); } @Test void testPhrase() { final String value = new PhraseGenerator().generate(); assertThat(value, matchesPattern("[a-z]+_[a-z]+_[a-z]+_[a-z]+_[a-z]+")); } @Test void testPhraseWozniakIsNotBoring() { final Iterator<Integer> indexes = Arrays.asList(9, 143, 0, 0, 0, 0, 0, 0, 0, 0).iterator(); final String value = PhraseGenerator.generate(i -> indexes.next()); assertThat(value, is(not(containsString("boring_wozniak")))); } @Test void testPhraseOver_1_000_000_000() { assertTrue(PhraseGenerator.maxCombinations() > 1_000_000_000); } @Test void testPhraseMinLength() { assertThat(PhraseGenerator.minLength(), is(22)); } @Test void testPhraseMaxLength() { assertThat(PhraseGenerator.maxLength(), is(61)); } }
package com.conveyal.r5.speed_test; import com.conveyal.gtfs.model.Stop; import com.conveyal.r5.profile.Path; import com.conveyal.r5.profile.ProfileRequest; import com.conveyal.r5.profile.StreetPath; import com.conveyal.r5.speed_test.api.model.AgencyAndId; import com.conveyal.r5.speed_test.api.model.Leg; import com.conveyal.r5.speed_test.api.model.Place; import com.conveyal.r5.speed_test.api.model.PolylineEncoder; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.transit.RouteInfo; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.TransportNetwork; import com.conveyal.r5.transit.TripPattern; import com.conveyal.r5.transit.TripSchedule; import com.vividsolutions.jts.geom.Coordinate; import java.time.LocalDate; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.TimeZone; import java.util.stream.Collectors; public class ItineraryMapper { private TransportNetwork transportNetwork; public ItineraryMapper(TransportNetwork transportNetwork) { this.transportNetwork = transportNetwork; } SpeedTestItinerary createItinerary(ProfileRequest request, Path path, StreetPath accessPath, StreetPath egressPath) { SpeedTestItinerary itinerary = new SpeedTestItinerary(); if (path == null) { return null; } itinerary.walkDistance = 0.0; itinerary.transitTime = 0; itinerary.waitingTime = 0; itinerary.weight = 0; int accessTime = accessPath.getDuration(); int egressTime = egressPath.getDuration(); List<Coordinate> acessCoords = accessPath.getEdges().stream() .map(t -> new Coordinate(accessPath.getEdge(t).getGeometry().getCoordinate().x, accessPath.getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); List<Coordinate> egressCoords = egressPath.getEdges().stream() .map(t -> new Coordinate(egressPath.getEdge(t).getGeometry().getCoordinate().x, egressPath.getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); Collections.reverse(egressCoords); // Access leg Leg accessLeg = new Leg(); Stop firstStop = transportNetwork.transitLayer.stopForIndex.get(path.boardStops[0]); accessLeg.startTime = createCalendar(request.date, (path.boardTimes[0] - accessTime)); accessLeg.endTime = createCalendar(request.date, path.boardTimes[0]); accessLeg.from = new Place(request.fromLon, request.fromLat, "Origin"); accessLeg.from.stopIndex = -1; accessLeg.to = new Place(firstStop.stop_lat, firstStop.stop_lon, firstStop.stop_name); accessLeg.to.stopId = new AgencyAndId("RB", firstStop.stop_id); accessLeg.to.stopIndex = path.boardStops[0]; accessLeg.mode = "WALK"; accessLeg.legGeometry = PolylineEncoder.createEncodings(acessCoords); accessLeg.distance = distanceMMToMeters(accessPath.getDistance()); itinerary.addLeg(accessLeg); for (int i = 0; i < path.patterns.length; i++) { Stop boardStop = transportNetwork.transitLayer.stopForIndex.get(path.boardStops[i]); Stop alightStop = transportNetwork.transitLayer.stopForIndex.get(path.alightStops[i]); // Transfer leg if present if (i > 0 && path.transferTimes[i] != -1) { Stop previousAlightStop = transportNetwork.transitLayer.stopForIndex.get(path.alightStops[i - 1]); StreetPath transferPath = getWalkLegCoordinates(path.alightStops[i - 1], path.boardStops[i]); List<Coordinate> transferCoords = transferPath.getEdges().stream() .map(t -> new Coordinate(transferPath.getEdge(t).getGeometry().getCoordinate().x, transferPath .getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); Leg transferLeg = new Leg(); transferLeg.startTime = createCalendar(request.date, path.alightTimes[i - 1]); transferLeg.endTime = createCalendar(request.date, path.transferTimes[i]); transferLeg.mode = "WALK"; transferLeg.from = new Place(previousAlightStop.stop_lat, previousAlightStop.stop_lon, previousAlightStop.stop_name); transferLeg.to = new Place(boardStop.stop_lat, boardStop.stop_lon, boardStop.stop_name); transferLeg.legGeometry = PolylineEncoder.createEncodings(transferCoords); transferLeg.distance = distanceMMToMeters (transferPath.getDistance()); itinerary.addLeg(transferLeg); } // Transit leg Leg transitLeg = new Leg(); transitLeg.distance = 0.0; RouteInfo routeInfo = transportNetwork.transitLayer.routes .get(transportNetwork.transitLayer.tripPatterns.get(path.patterns[i]).routeIndex); TripSchedule tripSchedule = transportNetwork.transitLayer.tripPatterns.get(path.patterns[i]).tripSchedules.get(path.trips[i]); TripPattern tripPattern = transportNetwork.transitLayer.tripPatterns.get(path.patterns[i]); itinerary.transitTime += path.alightTimes[i] - path.boardTimes[i]; itinerary.waitingTime += path.boardTimes[i] - path.transferTimes[i]; transitLeg.from = new Place(boardStop.stop_lat, boardStop.stop_lon, boardStop.stop_name); transitLeg.from.stopId = new AgencyAndId("RB", boardStop.stop_id); transitLeg.from.stopIndex = path.boardStops[i]; transitLeg.to = new Place(alightStop.stop_lat, alightStop.stop_lon, alightStop.stop_name); transitLeg.to.stopId = new AgencyAndId("RB", alightStop.stop_id); transitLeg.to.stopIndex = path.alightStops[i]; transitLeg.route = routeInfo.route_short_name; transitLeg.agencyName = routeInfo.agency_name; transitLeg.routeColor = routeInfo.color; transitLeg.tripShortName = tripSchedule.tripId; transitLeg.agencyId = routeInfo.agency_id; transitLeg.routeShortName = routeInfo.route_short_name; transitLeg.routeLongName = routeInfo.route_long_name; transitLeg.mode = TransitLayer.getTransitModes(routeInfo.route_type).toString(); List<Coordinate> transitLegCoordinates = new ArrayList<>(); boolean boarded = false; for (int j = 0; j < tripPattern.stops.length; j++) { if (!boarded && tripSchedule.departures[j] == path.boardTimes[i]) { boarded = true; } if (boarded) { transitLegCoordinates.add(new Coordinate(transportNetwork.transitLayer.stopForIndex.get(tripPattern.stops[j]).stop_lon, transportNetwork.transitLayer.stopForIndex.get(tripPattern.stops[j]).stop_lat )); } if (boarded && tripSchedule.arrivals[j] == path.alightTimes[i]) { break; } } transitLeg.legGeometry = PolylineEncoder.createEncodings(transitLegCoordinates); transitLeg.startTime = createCalendar(request.date, path.boardTimes[i]); transitLeg.endTime = createCalendar(request.date, path.alightTimes[i]); itinerary.addLeg(transitLeg); } // Egress leg Leg egressLeg = new Leg(); Stop lastStop = transportNetwork.transitLayer.stopForIndex.get(path.alightStops[path.length - 1]); egressLeg.startTime = createCalendar(request.date, path.alightTimes[path.alightTimes.length - 1]); egressLeg.endTime = createCalendar(request.date, path.alightTimes[path.alightTimes.length - 1] + egressTime); egressLeg.from = new Place(lastStop.stop_lat, lastStop.stop_lon, lastStop.stop_name); egressLeg.from.stopIndex = path.alightStops[path.length - 1]; egressLeg.from.stopId = new AgencyAndId("RB", lastStop.stop_id); egressLeg.to = new Place(request.toLon, request.toLat, "Destination"); egressLeg.mode = "WALK"; egressLeg.legGeometry = PolylineEncoder.createEncodings(egressCoords); egressLeg.distance = distanceMMToMeters (egressPath.getDistance()); itinerary.addLeg(egressLeg); itinerary.duration = (long) accessTime + (path.alightTimes[path.length - 1] - path.boardTimes[0]) + egressTime; itinerary.startTime = accessLeg.startTime; itinerary.endTime = egressLeg.endTime; itinerary.transfers = path.patterns.length - 1; itinerary.initParetoVector(); return itinerary; } private StreetPath getWalkLegCoordinates(int originStop, int destinationStop) { StreetRouter sr = new StreetRouter(transportNetwork.streetLayer); sr.profileRequest = new ProfileRequest(); int originStreetVertex = transportNetwork.transitLayer.streetVertexForStop.get(originStop); sr.setOrigin(originStreetVertex); sr.quantityToMinimize = StreetRouter.State.RoutingVariable.DURATION_SECONDS; sr.distanceLimitMeters = 1000; sr.route(); StreetRouter.State transferState = sr.getStateAtVertex(transportNetwork.transitLayer.streetVertexForStop .get(destinationStop)); StreetPath transferPath = new StreetPath(transferState, transportNetwork, false); return transferPath; } private Calendar createCalendar(LocalDate date, int timeinSeconds) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Oslo")); calendar.set(date.getYear(), date.getMonth().getValue(), date.getDayOfMonth() , 0, 0, 0); calendar.add(Calendar.SECOND, timeinSeconds); return calendar; } private double distanceMMToMeters(int distanceMm) { return (double) (distanceMm / 1000); } }
package com.elmakers.mine.bukkit.utility; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.spell.TargetType; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.util.BlockIterator; import org.bukkit.util.Vector; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class Targeting { private TargetingResult result = TargetingResult.NONE; private Location source = null; private Target target = null; private List<Target> targets = null; private TargetType targetType = TargetType.NONE; private BlockIterator blockIterator = null; private Block currentBlock = null; private Block previousBlock = null; private Block previousPreviousBlock = null; private Vector targetLocationOffset; private Vector targetDirectionOverride; private String targetLocationWorldName; protected float distanceWeight = 1; protected float fovWeight = 4; protected int npcWeight = -1; protected int mageWeight = 5; protected int playerWeight = 4; protected int livingEntityWeight = 3; private boolean ignoreBlocks = false; private int targetBreakableDepth = 2; private double hitboxPadding = 0; private double hitboxBlockPadding = 0; private double rangeQueryPadding = 1; private boolean useHitbox = true; private double fov = 0.3; private double closeRange = 0; private double closeFOV = 0; private double yOffset = 0; private boolean targetSpaceRequired = false; private int targetMinOffset = 0; public enum TargetingResult { NONE, BLOCK, ENTITY, MISS }; public void reset() { result = TargetingResult.NONE; source = null; target = null; targets = null; blockIterator = null; currentBlock = null; previousBlock = null; previousPreviousBlock = null; targetSpaceRequired = false; targetMinOffset = 0; yOffset = 0; } protected boolean initializeBlockIterator(Location location, double range) { if (blockIterator != null) { return true; } if (location.getBlockY() < 0) { location = location.clone(); location.setY(0); } int maxHeight = CompatibilityUtils.getMaxHeight(location.getWorld()); if (location.getBlockY() > maxHeight) { location = location.clone(); location.setY(maxHeight); } try { blockIterator = new BlockIterator(location, yOffset, (int)Math.ceil(range)); } catch (Exception ex) { if (Target.DEBUG_TARGETING) { org.bukkit.Bukkit.getLogger().warning("Exception creating BlockIterator"); ex.printStackTrace(); } // This seems to happen randomly, like when you use the same target. // Very annoying, and I now kind of regret switching to BlockIterator. // At any rate, we're going to just re-use the last target block and // cross our fingers! return false; } return true; } public Target getOrCreateTarget(Location defaultLocation) { if (target == null) { target = new Target(defaultLocation); } return target; } public Target getTarget() { return target; } public boolean hasTarget() { return target != null; } public void setTargetSpaceRequired(boolean required) { targetSpaceRequired = required; } public void setTargetMinOffset(int offset) { targetMinOffset = offset; } public void targetBlock(Location source, Block block) { target = new Target(source, block, useHitbox, hitboxBlockPadding); } public void setYOffset(int offset) { yOffset = offset; } /** * Move "steps" forward along line of vision and returns the block there * * @return The block at the new location */ protected Block getNextBlock() { previousPreviousBlock = previousBlock; previousBlock = currentBlock; if (blockIterator == null || !blockIterator.hasNext()) { currentBlock = null; } else { currentBlock = blockIterator.next(); } return currentBlock; } /** * Returns the current block along the line of vision * * @return The block */ public Block getCurBlock() { return currentBlock; } /** * Returns the previous block along the line of vision * * @return The block */ public Block getPreviousBlock() { return previousBlock; } public void setFOV(double fov) { this.fov = fov; } public void setCloseRange(double closeRange) { this.closeRange = closeRange; } public void setCloseFOV(double closeFOV) { this.closeFOV = closeFOV; } public void setUseHitbox(boolean useHitbox) { this.useHitbox = useHitbox; } public TargetType getTargetType() { return targetType; } public void setTargetType(TargetType type) { targetType = type; } public void start(Location source) { reset(); this.source = source.clone(); } public Target target(CastContext context, double range) { if (source == null) { source = context.getEyeLocation(); } target = findTarget(context, range); if (targetLocationOffset != null) { target.add(targetLocationOffset); } if (targetDirectionOverride != null) { target.setDirection(targetDirectionOverride); } if (targetLocationWorldName != null && targetLocationWorldName.length() > 0) { Location location = target.getLocation(); if (location != null) { World targetWorld = location.getWorld(); target.setWorld(ConfigurationUtils.overrideWorld(targetLocationWorldName, targetWorld, context.getController().canCreateWorlds())); } } Mage mage = context.getMage(); if (mage != null && mage.getDebugLevel() > 6) { Location targetLocation = target.getLocation(); String message = ChatColor.GREEN + "Targeted from " + ChatColor.GRAY + source.getBlockX() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + source.getBlockY() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + source.getBlockZ() + ChatColor.DARK_GREEN + " with range of " + ChatColor.GREEN + range + ChatColor.DARK_GREEN + ": " + ChatColor.GOLD + result; Entity targetEntity = target.getEntity(); if (targetEntity != null) { message = message + ChatColor.DARK_GREEN + " (" + ChatColor.YELLOW + targetEntity.getType() + ChatColor.DARK_GREEN + ")"; } if (targetLocation != null) { message = message + ChatColor.DARK_GREEN + " (" + ChatColor.LIGHT_PURPLE + targetLocation.getBlock().getType() + ChatColor.DARK_GREEN + ")"; message = message + ChatColor.DARK_GREEN + " at " + ChatColor.GRAY + targetLocation.getBlockX() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + targetLocation.getBlockY() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + targetLocation.getBlockZ(); } mage.sendDebugMessage(message); } return target; } /** * Returns the block at the cursor, or null if out of range * * @return The target block */ protected Target findTarget(CastContext context, double range) { if (targetType == TargetType.NONE) { return new Target(source); } boolean isBlock = targetType == TargetType.BLOCK || targetType == TargetType.SELECT; Mage mage = context.getMage(); final Entity mageEntity = mage.getEntity(); if (targetType == TargetType.SELF && mageEntity != null) { result = TargetingResult.ENTITY; return new Target(source, mageEntity); } CommandSender sender = mage.getCommandSender(); if (targetType == TargetType.SELF && mageEntity == null && sender != null && (sender instanceof BlockCommandSender)) { BlockCommandSender commandBlock = (BlockCommandSender)mage.getCommandSender(); return new Target(commandBlock.getBlock().getLocation(), commandBlock.getBlock()); } if (targetType == TargetType.SELF && source != null) { return new Target(source, source.getBlock()); } if (targetType == TargetType.SELF) { return new Target(source); } Block block = null; if (!ignoreBlocks) { findTargetBlock(context, range); block = currentBlock; } if (isBlock) { return new Target(source, block, useHitbox, hitboxBlockPadding); } Target targetBlock = block == null ? null : new Target(source, block, useHitbox, hitboxBlockPadding); // Don't target entities beyond the block we just hit if (targetBlock != null && source != null && source.getWorld().equals(block.getWorld())) { range = Math.min(range, source.distance(targetBlock.getLocation())); } // Pick the closest candidate entity Target entityTarget = null; List<Target> scored = getAllTargetEntities(context, range); if (scored.size() > 0) { entityTarget = scored.get(0); } // Don't allow targeting entities in an area you couldn't cast the spell in if (entityTarget != null && !context.canCast(entityTarget.getLocation())) { entityTarget = null; } if (targetBlock != null && !context.canCast(targetBlock.getLocation())) { result = TargetingResult.MISS; targetBlock = null; } if (targetType == TargetType.OTHER_ENTITY && entityTarget == null) { result = TargetingResult.MISS; return new Target(source); } if (targetType == TargetType.ANY_ENTITY && entityTarget == null) { result = TargetingResult.ENTITY; return new Target(source, mageEntity); } if (entityTarget == null && targetType == TargetType.ANY && mageEntity != null) { result = TargetingResult.ENTITY; return new Target(source, mageEntity, targetBlock == null ? null : targetBlock.getBlock()); } if (targetBlock != null && entityTarget != null) { if (targetBlock.getDistanceSquared() < entityTarget.getDistanceSquared()) { entityTarget = null; } else { targetBlock = null; } } if (entityTarget != null) { result = TargetingResult.ENTITY; return entityTarget; } else if (targetBlock != null) { result = TargetingResult.BLOCK; return targetBlock; } result = TargetingResult.MISS; return new Target(source); } protected void findTargetBlock(CastContext context, double range) { if (source == null) { return; } // Pre-check for no block movement Location targetLocation = source.clone().add(source.getDirection().multiply(range)); if (targetLocation.getBlockX() == source.getBlockX() && targetLocation.getBlockY() == source.getBlockY() && targetLocation.getBlockZ() == source.getBlockZ()) { currentBlock = source.getBlock(); if (context.isTargetable(currentBlock)) { result = TargetingResult.BLOCK; } else { result = TargetingResult.MISS; } return; } if (!initializeBlockIterator(source, range)) { return; } Block block = getNextBlock(); result = TargetingResult.BLOCK; while (block != null) { if (targetMinOffset <= 0) { if (targetSpaceRequired) { if (!context.allowPassThrough(block.getType())) { break; } if (context.isOkToStandIn(block.getType()) && context.isOkToStandIn(block.getRelative(BlockFace.UP).getType())) { break; } } else if (context.isTargetable(block)) { break; } } else { targetMinOffset } block = getNextBlock(); } if (block == null) { result = TargetingResult.MISS; currentBlock = previousBlock; previousBlock = previousPreviousBlock; } } public List<Target> getAllTargetEntities(CastContext context, double range) { Entity sourceEntity = context.getEntity(); Mage mage = context.getMage(); if (targets != null) { return targets; } targets = new ArrayList<Target>(); // A fuzzy optimization range-check. A hard range limit is enforced in the final target consolidator double rangeSquaredPadded = (range + 1) * (range + 1); List<Entity> entities = null; if (source == null && sourceEntity != null) { range = Math.min(range + hitboxPadding + rangeQueryPadding, CompatibilityUtils.MAX_ENTITY_RANGE); entities = sourceEntity.getNearbyEntities(range, range, range); if (sourceEntity instanceof LivingEntity) { source = ((LivingEntity)sourceEntity).getEyeLocation(); } else { source = sourceEntity.getLocation(); } } else if (source != null) { Vector queryRange = null; Location sourceLocation = source; if (useHitbox) { range = Math.min(range, CompatibilityUtils.MAX_ENTITY_RANGE); Vector direction = source.getDirection(); Location targetLocation = source.clone().add(direction.multiply(range)); BoundingBox bounds = new BoundingBox(source.toVector(), targetLocation.toVector()); bounds.expand(hitboxPadding + rangeQueryPadding); Vector center = bounds.center(); sourceLocation = new Location(source.getWorld(), center.getX(), center.getY(), center.getZ()); queryRange = bounds.size(); } else { queryRange = new Vector(range * 2, range * 2, range * 2); sourceLocation = source; } if (mage != null && mage.getDebugLevel() > 9) { mage.sendDebugMessage(ChatColor.GREEN + "Targeting via bounding box " + ChatColor.GRAY + (int)Math.ceil(queryRange.getX()) + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + (int)Math.ceil(queryRange.getY()) + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + (int)Math.ceil(queryRange.getZ())); } entities = CompatibilityUtils.getNearbyEntities(sourceLocation, queryRange.getX() / 2, queryRange.getY() / 2, queryRange.getZ() / 2); } if (mage != null && mage.getDebugLevel() > 8) { mage.sendDebugMessage(ChatColor.GREEN + "Targeting from " + ChatColor.GRAY + source.getBlockX() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + source.getBlockY() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + source.getBlockZ() + ChatColor.DARK_GREEN + " with range of " + ChatColor.GREEN + range); } if (entities == null) return targets; for (Entity entity : entities) { if (sourceEntity != null && entity.equals(sourceEntity) && !context.getTargetsCaster()) continue; Location entityLocation = entity instanceof LivingEntity ? ((LivingEntity)entity).getEyeLocation() : entity.getLocation(); if (!entityLocation.getWorld().equals(source.getWorld())) continue; if (entityLocation.distanceSquared(source) > rangeSquaredPadded) continue; if (!context.canTarget(entity)) continue; Target newScore = null; if (useHitbox) { newScore = new Target(source, entity, (int)Math.ceil(range), useHitbox, hitboxPadding); } else { newScore = new Target(source, entity, (int)Math.ceil(range), fov, closeRange, closeFOV, distanceWeight, fovWeight, mageWeight, npcWeight, playerWeight, livingEntityWeight); } if (newScore.getScore() > 0) { if (mage != null && mage.getDebugLevel() > 5) { mage.sendDebugMessage(ChatColor.DARK_GREEN + "Target " + ChatColor.GREEN + entity.getType() + ChatColor.DARK_GREEN + ": " + ChatColor.YELLOW + newScore.getScore()); } targets.add(newScore); } } Collections.sort(targets); return targets; } public void parseTargetType(String targetTypeName) { targetType = TargetType.NONE; if (targetTypeName != null) { try { targetType = TargetType.valueOf(targetTypeName.toUpperCase()); } catch (Exception ex) { targetType = TargetType.NONE; } } } public void processParameters(ConfigurationSection parameters) { parseTargetType(parameters.getString("target")); useHitbox = parameters.getBoolean("hitbox", !parameters.contains("fov")); hitboxPadding = parameters.getDouble("hitbox_size", 0); hitboxBlockPadding = parameters.getDouble("hitbox_block_size", 0); rangeQueryPadding = parameters.getDouble("range_padding", 1); fov = parameters.getDouble("fov", 0.3); closeRange = parameters.getDouble("close_range", 1); closeFOV = parameters.getDouble("close_fov", 0.5); distanceWeight = (float)parameters.getDouble("distance_weight", 1); fovWeight = (float)parameters.getDouble("fov_weight", 4); npcWeight = parameters.getInt("npc_weight", -1); playerWeight = parameters.getInt("player_weight", 4); livingEntityWeight = parameters.getInt("entity_weight", 3); targetMinOffset = parameters.getInt("target_min_offset", 0); targetMinOffset = parameters.getInt("tmo", targetMinOffset); ignoreBlocks = parameters.getBoolean("ignore_blocks", false); targetBreakableDepth = parameters.getInt("target_breakable_depth", 2); targetLocationOffset = null; targetDirectionOverride = null; Double otxValue = ConfigurationUtils.getDouble(parameters, "otx", null); Double otyValue = ConfigurationUtils.getDouble(parameters, "oty", null); Double otzValue = ConfigurationUtils.getDouble(parameters, "otz", null); if (otxValue != null || otzValue != null || otyValue != null) { targetLocationOffset = new Vector( (otxValue == null ? 0 : otxValue), (otyValue == null ? 0 : otyValue), (otzValue == null ? 0 : otzValue)); } targetLocationWorldName = parameters.getString("otworld"); Double tdxValue = ConfigurationUtils.getDouble(parameters, "otdx", null); Double tdyValue = ConfigurationUtils.getDouble(parameters, "otdy", null); Double tdzValue = ConfigurationUtils.getDouble(parameters, "otdz", null); if (tdxValue != null || tdzValue != null || tdyValue != null) { targetDirectionOverride = new Vector( (tdxValue == null ? 0 : tdxValue), (tdyValue == null ? 0 : tdyValue), (tdzValue == null ? 0 : tdzValue)); } } public TargetingResult getResult() { return result; } public void getTargetEntities(CastContext context, double range, int targetCount, Collection<WeakReference<Entity>> entities) { List<Target> candidates = getAllTargetEntities(context, range); if (targetCount < 0) { targetCount = entities.size(); } for (int i = 0; i < targetCount && i < candidates.size(); i++) { Target target = candidates.get(i); entities.add(new WeakReference<Entity>(target.getEntity())); } } protected int breakBlockRecursively(CastContext context, Block block, int depth) { if (depth <= 0) return 0; // Play break FX Location blockLocation = block.getLocation(); Location effectLocation = blockLocation.add(0.5, 0.5, 0.5); context.playEffects("break", 1, context.getLocation(), null, effectLocation, null); // TODO: Re-examime this? UndoList undoList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(blockLocation); if (undoList != null) { undoList.add(block); } context.clearBreakable(block); context.clearReflective(block); block.setType(Material.AIR); int broken = 1; if (depth > broken) { broken += breakBlockRecursively(context, block.getRelative(BlockFace.UP), Math.min(targetBreakableDepth, depth - broken)); broken += breakBlockRecursively(context, block.getRelative(BlockFace.DOWN), Math.min(targetBreakableDepth, depth - broken)); broken += breakBlockRecursively(context, block.getRelative(BlockFace.EAST), Math.min(targetBreakableDepth, depth - broken)); broken += breakBlockRecursively(context, block.getRelative(BlockFace.WEST), Math.min(targetBreakableDepth, depth - broken)); broken += breakBlockRecursively(context, block.getRelative(BlockFace.NORTH), Math.min(targetBreakableDepth, depth - broken)); broken += breakBlockRecursively(context, block.getRelative(BlockFace.SOUTH), Math.min(targetBreakableDepth, depth - broken)); } return broken; } public int breakBlock(CastContext context, Block block, double amount) { if (amount <= 0) return 0; Double breakableAmount = context.getBreakable(block); if (breakableAmount == null) return 0; double breakable = (int)(amount > 1 ? amount : (context.getRandom().nextDouble() < amount ? 1 : 0)); if (breakable <= 0) return 0; return breakBlockRecursively(context, block, (int)Math.ceil(breakableAmount + breakable - 1)); } public static void track(Plugin plugin, Entity tracked) { tracked.setMetadata("tracking", new FixedMetadataValue(plugin, true)); } public static boolean checkTracking(Plugin plugin, Entity tracked, Entity target) { if (tracked == null || !tracked.hasMetadata("tracking")) { return false; } if (target != null) { tracked.setMetadata("hit", new FixedMetadataValue(plugin, new WeakReference<Entity>(target))); } else if (!tracked.hasMetadata("hit")) { tracked.setMetadata("hit", new FixedMetadataValue(plugin, null)); } return true; } }
package com.foodrater.verticles; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.mongo.MongoClient; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.core.logging.Logger; import io.vertx.ext.web.handler.CorsHandler; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; public class RestServerVerticle extends AbstractVerticle { private static final Logger LOGGER = LoggerFactory.getLogger(RestServerVerticle.class.getSimpleName()); private Map<String, JsonObject> products = new HashMap<>(); public static final String ADDRESS = "mongodb-persistor"; public static final String DEFAULT_MONGODB_CONFIG = "{" + " \"address\": \"" + ADDRESS + "\"," + " \"host\": \"localhost\"," + " \"port\": 27017," + " \"db_name\": \"bs\"," + " \"useObjectId\" : true" + "}"; MongoClient mongo; @Override public void start() { mongo = MongoClient.createShared(vertx, new JsonObject(DEFAULT_MONGODB_CONFIG)); LOGGER.info("MongoClient is started with this config: " + new JsonObject(DEFAULT_MONGODB_CONFIG).encodePrettily()); //setUpInitialData(); Router router = Router.router(vertx); // Needs to be added if you want to access your frontend on the same server CorsHandler corsHandler = CorsHandler.create("*"); corsHandler.allowedMethod(HttpMethod.GET); corsHandler.allowedMethod(HttpMethod.POST); corsHandler.allowedMethod(HttpMethod.PUT); corsHandler.allowedMethod(HttpMethod.DELETE); corsHandler.allowedHeader("Authorization"); corsHandler.allowedHeader("Content-Type"); corsHandler.allowedHeader("Access-Control-Allow-Origin"); corsHandler.allowedHeader("Access-Control-Allow-Headers"); router.route().handler(corsHandler); router.route().handler(BodyHandler.create()); router.get("/products/:productID").handler(this::handleGetProduct); router.get("/products/search/:word").handler(this::searchProduct); router.put("/products/:productID").handler(this::handleAddProduct); router.get("/products").handler(this::handleListProducts); router.get("/initialize").handler(this::setUpInitialData); router.get("/myproducts/:UUID").handler(this::getAllProductsForUser); router.get("/users/:userID").handler(this::getUserInformation); router.get("/user/login").handler(this::getUserLogin); router.put("/user/register").handler(this::handleAddUser); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } private void getUserLogin(RoutingContext routingContext) { JsonObject user = routingContext.getBodyAsJson(); String userName = user.getString("username"); String pw = user.getString("pw"); HttpServerResponse response = routingContext.response(); if (userName.equals(null) || pw.equals(null) || userName.length() < 1 || pw.length() < 1) { sendError(400, response); } else { try { if (findUserInMongoDB(userName, pw) != null) { response.putHeader("content-type", "application/json").end((findUserInMongoDB(userName, pw)).encodePrettily()); } else { sendError(400, response); } } catch (InterruptedException e) { LOGGER.error("Couldn't find User."); sendError(400, response); } } } private JsonObject findUserInMongoDB(String userName, String pw) throws InterruptedException { JsonObject resultedUser = new JsonObject(); JsonObject query = new JsonObject(); query.put("userName", userName); query.put("pw", pw); CountDownLatch latch = new CountDownLatch(1); mongo.find("users", query, res -> { if (res.succeeded()) { for (JsonObject json : res.result()) { LOGGER.info("Found user:" + json.encodePrettily()); resultedUser.put(json.getString("uuid"), json); LOGGER.info("Result Json:" + resultedUser.encodePrettily()); } } latch.countDown(); }); latch.await(); LOGGER.info("Final result Json:" + resultedUser.encodePrettily()); return resultedUser; } private void handleAddUser(RoutingContext routingContext) { // add check, if user already exists HttpServerResponse response = routingContext.response(); JsonObject user = null; try { user = routingContext.getBodyAsJson(); } catch (Exception e) { sendError(400, response); } if (user == null) { sendError(400, response); } else { UUID uuid = new UUID(10000L, 100L); JsonObject newUser = new JsonObject(); newUser.put("UUID", uuid.toString()); insertUserInMongo(newUser); response.putHeader("content-type", "application/json").end(newUser.encodePrettily()); } } private void insertUserInMongo(JsonObject user) { mongo.insert("users", user, stringAsyncResult -> { if (stringAsyncResult.succeeded()) { LOGGER.info("Inserted user into mongoDB: " + user.encodePrettily()); } else { LOGGER.error("Could not insert user into mongoDB: " + user.encodePrettily()); } }); } private void getUserInformation(RoutingContext routingContext) { String uuid = routingContext.request().getParam("uuid"); HttpServerResponse response = routingContext.response(); JsonObject query = new JsonObject(); query.put("UUID", uuid); mongo.find("users", query, res -> { if (res.succeeded()) { for (JsonObject json : res.result()) { LOGGER.info("Found user:" + json.encodePrettily()); response.putHeader("content-type", "application/json").end(json.encodePrettily()); } } else { sendError(400, response); } }); } /** * response all products for user as json -> {prodId:{productjson1}, {productjson2}, ... } * * @param routingContext incoming RotingContext with param UUID */ private void getAllProductsForUser(RoutingContext routingContext) { String uuid = routingContext.request().getParam("UUID"); JsonObject query = new JsonObject().put("UUID", uuid); HttpServerResponse response = routingContext.response(); JsonObject allProducts = new JsonObject(); mongo.find("users", query, res -> { if (res.succeeded()) { for (JsonObject userJson : res.result()) { JsonObject query2 = new JsonObject().put("productID", userJson.getString("productID")); mongo.find("products", query2, res2 -> { if (res2.succeeded()) { for (JsonObject product : res2.result()) { allProducts.put(userJson.getString("productID"), product); } } }); } response.putHeader("content-type", "application/json").end(allProducts.encodePrettily()); } else { sendError(400, response); } }); } /** * response all products with name inside as json * { {product1}, {product2}, {product3}.. } * * @param routingContext incoming RotingContext with param search-word */ private void searchProduct(RoutingContext routingContext) { String word = routingContext.request().getParam("word"); JsonObject query = new JsonObject().put("name", "/" + word + "/"); //LOGGER.info("Search in mongodb for this query: " + query.encodePrettily()); HttpServerResponse response = routingContext.response(); JsonObject fittingProducts = new JsonObject(); CountDownLatch latch = new CountDownLatch(1); mongo.find("products", query, res -> { if (res.succeeded()) { for (JsonObject foundedProduct : res.result()) { LOGGER.info("Found Product with search: " + foundedProduct.encodePrettily()); fittingProducts.put(foundedProduct.getJsonObject("product").getString("id"), foundedProduct); latch.countDown(); } try { latch.await(); } catch (InterruptedException e) { LOGGER.error("Couldn't find any with: " + word); sendError(400, response); } LOGGER.info("Reached that point" + fittingProducts.encodePrettily()); response.putHeader("content-type", "application/json").end(fittingProducts.encodePrettily()); } }); } private void setUpInitialData(RoutingContext routingContext) { addProduct(new JsonObject().put("id", "prod3568").put("name", "Egg Whisk").put("price", 3.99).put("weight", 150)); addProduct(new JsonObject().put("id", "prod7340").put("name", "Tea Cosy").put("price", 5.99).put("weight", 100)); addProduct(new JsonObject().put("id", "prod8643").put("name", "Spatula").put("price", 1.00).put("weight", 80)); insertUserInMongo(new JsonObject().put("uuid", (new UUID(10L, 1000L)).toString()).put("userName", "Sebastian").put("pw", "123abc")); // + average rating and amount of ratings HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "application/json").end("initialized"); } private void handleGetProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { //JsonObject product = products.get(productID); JsonObject product = findProductInMongoDB(productID); if (product == null) { sendError(404, response); } else { response.putHeader("content-type", "application/json").end(product.encode()); } } } private JsonObject findProductInMongoDB(String productID) { JsonObject query = new JsonObject(); query.put(productID + ".id", productID); JsonObject result = new JsonObject(); CountDownLatch latch = new CountDownLatch(1); LOGGER.info("Trying to find " + query.encodePrettily()); mongo.find("products", query, res -> { if (res.succeeded()) { for (JsonObject json : res.result()) { LOGGER.info("Found product:" + json.encodePrettily()); result.put("product", json); LOGGER.info("Result Json:" + result.encodePrettily()); } latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { LOGGER.error("latch error: " + e.getMessage()); } LOGGER.info("Final result Json:" + result.encodePrettily()); return result; } private void handleAddProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { JsonObject product = routingContext.getBodyAsJson(); // change product to user if (product == null) { sendError(400, response); } else { products.put(productID, product); JsonObject productAsJson = new JsonObject(); productAsJson.put(productID, product); insertInMongo(productAsJson); response.end(); } } } private void insertInMongo(JsonObject productAsJson) { // calculate average rating + update product database averageRating + update user database add userproducts : {productId : , userRating : } mongo.insert(("products"), productAsJson, res -> { if (res.succeeded()) { String id = res.result(); } else { res.cause().printStackTrace(); } }); } private void handleListProducts(RoutingContext routingContext) { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily()); } private void sendError(int statusCode, HttpServerResponse response) { response.setStatusCode(statusCode).end(); } private void addProduct(JsonObject product) { products.put(product.getString("id"), product); JsonObject jsonObject = new JsonObject(); jsonObject.put(product.getString("id"), product); LOGGER.info("JsonObject to insert: " + jsonObject.encodePrettily()); insertInMongo(jsonObject); } }
package urSQL.RuntimeDatabaseProcessor.Rutine; import java.util.Iterator; import java.util.LinkedList; import urSQL.RuntimeDatabaseProcessor.ReferencialIntegrityManager; import urSQL.RuntimeDatabaseProcessor.Components.Component; import urSQL.StoredDataManager.StoreDataManager; import urSQL.System.ResultSet; import urSQL.System.TableRegister; import urSQL.SystemCatalog.SystemCatalog; public class RoutineDML extends Routine { /** * Constant for the SQL Word SELECT */ public static String CONSTANT_SELECT = "SELECT"; /** * Constant for the SQL Word Insert */ public static String CONSTANT_INSERT = "INSERT"; /** * Constant for the SQL Word DELETE */ public static String CONSTANT_DELETE = "DELETE"; /** * Constant for the SQL Word SET */ public static String CONSTANT_SET = "SET"; public RoutineDML(String pCommand, LinkedList<Component> pComponents) { super(pCommand, pComponents); } public RoutineDML(String pCommand) { super(pCommand, new LinkedList<>()); } @Override public ResultSet execute() { // Final response to the queried ResultSet resultPartial = null; // Plan Execution - Relational Algebra ResultSet resultFinalExtreme = this.runPlan(); // Data Review ReferencialIntegrityManager referencialIM = new ReferencialIntegrityManager(); //referencialIM.makeReview(resultPartial); if(this._Command.equalsIgnoreCase(CONSTANT_DELETE)) { // Data Execution this.deleteRows(resultPartial); } if(this._Command.equalsIgnoreCase(CONSTANT_INSERT)) { // Data Execution this.insertRows(resultPartial); } if(this._Command.equalsIgnoreCase(CONSTANT_SET)) { // Data Execution this.updateRows(resultPartial); } if(this._Command.equalsIgnoreCase(CONSTANT_SELECT)) { resultFinalExtreme = resultPartial; } return (resultFinalExtreme); } private ResultSet insertRows(ResultSet pResultSet) { // Disk Data Manager StoreDataManager sDm = new StoreDataManager(); // Iterator for the Registers Iterator< TableRegister > it = pResultSet.getTableData().getData().iterator(); while(it.hasNext()) { //sDm.insertRow(SystemCatalog.getInstance().getCurrentDatabase(), metadata, data); } return null; } private ResultSet deleteRows(ResultSet pResultSet) { // Table Name String tableName = pResultSet.getTableMetadata().getTableName(); // Primary Key Index int pkIndex = pResultSet.getTableMetadata().indexByName(pResultSet.getTableMetadata().getPrimaryKey().getName()); // Disk Data Manager StoreDataManager sDm = new StoreDataManager(); // Iterator for the Registers Iterator< TableRegister > it = pResultSet.getTableData().getData().iterator(); while(it.hasNext()) { sDm.deleteRow(SystemCatalog.getInstance().getCurrentDatabase(), tableName, it.next().getRegister().get(pkIndex)); } return null; } private ResultSet updateRows(ResultSet pResultSet) { // Table Name String tableName = pResultSet.getTableMetadata().getTableName(); // Primary Key Index int pkIndex = pResultSet.getTableMetadata().indexByName(pResultSet.getTableMetadata().getPrimaryKey().getName()); // Disk Data Manager StoreDataManager sDm = new StoreDataManager(); // Iterator for the Registers Iterator< TableRegister > it = pResultSet.getTableData().getData().iterator(); // Temp TableRegister tmp = null; while(it.hasNext()) { tmp = it.next(); //sDm.updateRegister(SystemCatalog.getInstance().getCurrentDatabase(), tableName, tmp.getRegister().get(pkIndex), tmp.getRegister()); } return null; } }
package com.gmail.nossr50.commands.mc; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.SkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Database; import com.gmail.nossr50.util.Leaderboard; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Skills; public class MctopCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String usage = ChatColor.RED + "Proper usage is /mctop [skill] [page]"; //TODO: Needs more locale. if (!Config.getInstance().getUseMySQL()) { switch (args.length) { case 0: flatfileDisplay(1, "ALL", sender); return true; case 1: if (Misc.isInt(args[0])) { flatfileDisplay(Integer.valueOf(args[0]), "ALL", sender); } else if (Skills.isSkill(args[0])) { flatfileDisplay(1, args[0].toUpperCase(), sender); } else { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid")); } return true; case 2: if (!Skills.isSkill(args[0])) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid")); return true; } if (Misc.isInt(args[1])) { flatfileDisplay(Integer.valueOf(args[1]), args[0].toUpperCase(), sender); } else { sender.sendMessage(usage); } return true; default: sender.sendMessage(usage); return true; } } String powerlevel = "taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing"; switch (args.length) { case 0: sqlDisplay(1, powerlevel, sender); return true; case 1: if (Misc.isInt(args[0])) { sqlDisplay(Integer.valueOf(args[0]), powerlevel, sender); } else if (Skills.isSkill(args[0])) { sqlDisplay(1, args[0].toLowerCase(), sender); } else { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid")); } return true; case 2: if (!Skills.isSkill(args[0])) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid")); return true; } if (Misc.isInt(args[1])) { sqlDisplay(Integer.valueOf(args[1]), args[0].toLowerCase(), sender); } else { sender.sendMessage(usage); } return true; default: sender.sendMessage(usage); return true; } } private void flatfileDisplay(int page, String skill, CommandSender sender) { Leaderboard.updateLeaderboards(); //Make sure we have the latest information SkillType skillType = SkillType.getSkill(skill); String[] info = Leaderboard.retrieveInfo(skillType, page); if (skill.equals("ALL")) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); } else { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", new Object[] { Misc.getCapitalized(skill) })); } int n = (page * 10) - 9; // Position for (String x : info) { if (x != null) { String digit = String.valueOf(n); if (n < 10) { digit = "0" + digit; } String[] splitx = x.split(":"); // Format: 1. Playername - skill value sender.sendMessage(digit + ". " + ChatColor.GREEN + splitx[1] + " - " + ChatColor.WHITE + splitx[0]); n++; } } sender.sendMessage(ChatColor.GOLD+"Tip: Use "+ChatColor.RED+"/mcrank"+ChatColor.GOLD+" to view all of your personal rankings!"); } private void sqlDisplay(int page, String query, CommandSender sender) { String tablePrefix = Config.getInstance().getMySQLTablePrefix(); Database database = mcMMO.getPlayerDatabase(); HashMap<Integer, ArrayList<String>> userslist = database.read("SELECT s." + query + ", u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u WHERE (s.user_id = u.id) AND s." + query + " > 0 ORDER BY s." + query + " DESC LIMIT "+((page * 10) - 10)+",10"); if (query.equals("taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing")) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); } else { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", new Object[] { Misc.getCapitalized(query) })); } int place = (page * 10) - 9; for (int i = 1; i <= 10; i++) { if(userslist.get(i) == null) { break; } sender.sendMessage(String.valueOf(place) + ". " + ChatColor.GREEN + userslist.get(i).get(1) + " - " + ChatColor.WHITE + userslist.get(i).get(0)); place++; } sender.sendMessage(ChatColor.GOLD+"Tip: Use "+ChatColor.RED+"/mcrank"+ChatColor.GOLD+" to view all of your personal rankings!"); } }
package ai.subut.kurjun.db.file; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.TxMaker; /** * File based db. This db stores records in a key value pairs. * */ public class FileDb implements Closeable { private final File file; protected final TxMaker txMaker; /** * Constructs file based db backed by supplied file. * * @param dbFile * @throws IOException */ public FileDb( String dbFile ) throws IOException { this( dbFile, false ); } FileDb( String dbFile, boolean readOnly ) throws IOException { if ( dbFile == null || dbFile.isEmpty() ) { throw new IllegalArgumentException( "File db path can not be empty" ); } Path path = Paths.get( dbFile ); // ensure parent dirs do exist Files.createDirectories( path.getParent() ); this.file = path.toFile(); DBMaker dbMaker = DBMaker.newFileDB( file ); if ( readOnly ) { dbMaker.readOnly(); } // TODO: Check on standalone env of temporary CL swapping // By using this setter CL swapping can be avoided. ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); this.txMaker = dbMaker .closeOnJvmShutdown() .mmapFileEnableIfSupported() .snapshotEnable() .makeTxMaker(); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Gets underlying db file. * * @return file to underlying db file */ public File getFile() { return file; } /** * Checks if association exists for the key in a map with supplied name. * * @param mapName name of the map to check * @param key key to check association for * @return {@code true} if map contains association for the key; {@code false} otherwise */ public boolean contains( String mapName, Object key ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { return checkNameExists( mapName, db ) && db.getHashMap( mapName ).containsKey( key ); } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Gets value for the key in a map with supplied name. * * @param <T> type of the value * @param mapName name of the map to get value from * @param key the key to look for * @param clazz type of the returned value * @return value mapped to supplied key; {@code null} if no value is mapped */ public <T> T get( String mapName, Object key, Class<T> clazz ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { if ( checkNameExists( mapName, db ) ) { return ( T ) db.getHashMap( mapName ).get( key ); } } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } return null; } /** * Gets a readonly snapshot view of the map with supplied name. * * @param <K> type of map keys * @param <V> type of map values * @param mapName name of the map to get * @return readonly view of the map */ public <K, V> Map<K, V> get( String mapName ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); Map<K, V> result = new HashMap<>(); DB db = txMaker.makeTx(); try { if ( checkNameExists( mapName, db ) ) { Map<K, V> snapshot = ( Map<K, V> ) db.getHashMap( mapName ).snapshot(); result.putAll( snapshot ); } } finally { db.close(); } return Collections.unmodifiableMap( result ); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Associated the key to the given value in a map with supplied name. * * @param <T> type of the value * @param mapName name of the map to put mapping to * @param key key value * @param value value to be associated with the key * @return the previous value associated with key, or null if there was no mapping for key */ public <T> T put( String mapName, Object key, T value ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { T put = ( T ) db.getHashMap( mapName ).put( key, value ); db.commit(); return put; } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Removes mapping for the key in a map with supplied name. * * @param <T> type of the value * @param mapName map name * @param key key value to remove mapping for * @return the previous value associated with key, or null if there was no mapping for key */ public <T> T remove( String mapName, Object key ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { T removed = ( T ) db.getHashMap( mapName ).remove( key ); db.commit(); return removed; } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } @Override public void close() throws IOException { if ( txMaker != null ) { txMaker.close(); } } private boolean checkNameExists( String name, DB db ) { try { // this method is preferred to others like 'exists()' because it does use locks db.checkNameNotExists( name ); return false; } catch ( IllegalArgumentException ex ) { return true; } } }
package com.google.api.gax.core; import java.io.InputStream; import java.util.Properties; /** * Provides meta-data properties stored in a properties file. */ public class PropertiesProvider { private static final Properties gaxProperties = new Properties(); private static final String GAX_PROPERTY_FILE = "/com/google/api/gax/gax.properties"; private static final String DEFAULT_VERSION = ""; /** * Returns the current version of GAX */ public static String getGaxVersion() { String gaxVersion = loadGaxProperty("version"); return gaxVersion != null ? gaxVersion : DEFAULT_VERSION; } /** * Returns the current version of gRPC */ public static String getGrpcVersion() { String grpcVersion = loadGaxProperty("grpc_version"); return grpcVersion != null ? grpcVersion : DEFAULT_VERSION; } /** * Utility method of retrieving the property value of the given key from a property file in the * package. * * @param loadedClass The class used to get the resource path * @param propertyFilePath The relative file path to the property file * @param key Key string of the property */ public static String loadProperty(Class<?> loadedClass, String propertyFilePath, String key) { try { InputStream inputStream = loadedClass.getResourceAsStream(propertyFilePath); if (inputStream != null) { Properties properties = new Properties(); properties.load(inputStream); return properties.getProperty(key); } else { printMissingProperties(loadedClass, propertyFilePath); } } catch (Exception e) { e.printStackTrace(System.err); } return null; } private static String loadGaxProperty(String key) { try { if (gaxProperties.isEmpty()) { InputStream inputStream = PropertiesProvider.class.getResourceAsStream(GAX_PROPERTY_FILE); if (inputStream != null) { gaxProperties.load(inputStream); } else { printMissingProperties(PropertiesProvider.class, GAX_PROPERTY_FILE); return null; } } return gaxProperties.getProperty(key); } catch (Exception e) { e.printStackTrace(System.err); } return null; } private static void printMissingProperties(Class<?> loadedClass, String propertyFilePath) { System.err.format( "Warning: Failed to open properties resource at '%s' of the given class '%s'\n", propertyFilePath, loadedClass.getName()); } }
package com.google.sps.firebase; import com.google.appengine.api.utils.SystemProperty; import com.google.auth.appengine.AppEngineCredentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.ThreadManager; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; // Only create app one time public class FirebaseAppManager { private static FirebaseApp app = null; private static GoogleCredentials getCredentials() throws IOException { if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) { List<String> scopes = Arrays.asList( "https: "https: return AppEngineCredentials.newBuilder().setScopes(scopes).build(); } else { // Local development server return GoogleCredentials.getApplicationDefault(); } } public static FirebaseApp getApp() throws IOException { if (app == null) { FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(getCredentials()) .setDatabaseUrl("https://fulfillment-deco-step-2020.firebaseio.com") .setProjectId("fulfillment-deco-step-2020") .setThreadManager( new ThreadManager() { @Override protected void releaseExecutor(FirebaseApp app, ExecutorService executor) { executor.shutdownNow(); } @Override protected ThreadFactory getThreadFactory() { // TODO Auto-generated method stub return com.google.appengine.api.ThreadManager.backgroundThreadFactory(); } @Override protected ExecutorService getExecutor(FirebaseApp app) { // TODO Auto-generated method stub return Executors.newCachedThreadPool( com.google.appengine.api.ThreadManager.backgroundThreadFactory()); } }) .build(); app = FirebaseApp.initializeApp(options); } return app; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.laytonsmith.aliasengine.functions; import com.laytonsmith.aliasengine.functions.exceptions.CancelCommandException; import com.laytonsmith.aliasengine.functions.exceptions.ConfigRuntimeException; import com.laytonsmith.aliasengine.Constructs.CArray; import com.laytonsmith.aliasengine.Constructs.CString; import com.laytonsmith.aliasengine.Constructs.CVoid; import com.laytonsmith.aliasengine.Constructs.Construct; import com.laytonsmith.aliasengine.Static; import com.laytonsmith.aliasengine.functions.Exceptions.ExceptionType; import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.logging.Level; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * I'm So Meta, Even This Acronym * @author Layton */ public class Meta { public static String docs() { return "These functions provide a way to run other commands"; } @api public static class runas implements Function { public String getName() { return "runas"; } public Integer[] numArgs() { return new Integer[]{2}; } public Construct exec(int line_num, File f, final CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException { if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') { throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')", ExceptionType.FormatException, line_num, f); } String cmd = args[1].val().substring(1); if (args[0] instanceof CArray) { CArray u = (CArray) args[0]; for (int i = 0; i < u.size(); i++) { exec(line_num, f, p, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]}); } return new CVoid(line_num, f); } if (args[0].val().equals("~op")) { Boolean isOp = p.isOp(); if(!isOp){ p.setOp(true); } if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { if (p instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[1].val().trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim()); } } //m.chat(cmd); Static.getServer().dispatchCommand(p, cmd); p.setOp(isOp); } else { Player m = Static.getServer().getPlayer(args[0].val()); if (m != null && m.isOnline()) { if (p instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim()); } //m.chat(cmd); Static.getServer().dispatchCommand(m, cmd); } else { throw new ConfigRuntimeException("The player " + args[0].val() + " is not online", ExceptionType.PlayerOfflineException, line_num, f); } } return new CVoid(line_num, f); } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.PlayerOfflineException}; } public String docs() { return "void {player, command} Runs a command as a particular user. The special user '~op' is a user that runs as op. Be careful with this very powerful function." + " Commands cannot be run as an offline player. Returns void. If the first argument is an array of usernames, the command" + " will be run in the context of each user in the array."; } public boolean isRestricted() { return true; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.0.1"; } public Boolean runAsync() { return false; } } @api public static class run implements Function { public String getName() { return "run"; } public Integer[] numArgs() { return new Integer[]{1}; } public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException { if (args[0].val() == null || args[0].val().length() <= 0 || args[0].val().charAt(0) != '/') { throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')", ExceptionType.FormatException, line_num, f); } String cmd = args[0].val().substring(1); if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { if (p instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim()); } } //p.chat(cmd); Static.getServer().dispatchCommand(p, cmd); return new CVoid(line_num, f); } public String docs() { return "void {var1} Runs a command as the current player. Useful for running commands in a loop. Note that this accepts commands like from the " + "chat; with a forward slash in front."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.0.1"; } public Boolean runAsync() { return false; } } @api public static class g implements Function { public String getName() { return "g"; } public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException { for (int i = 0; i < args.length; i++) { args[i].val(); } return new CVoid(line_num, f); } public String docs() { return "string {func1, [func2...]} Groups any number of functions together, and returns void. "; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.0.1"; } public Boolean runAsync() { return null; } } @api public static class p implements Function { public String getName() { return "p"; } public Integer[] numArgs() { return new Integer[]{1}; } public String docs() { return "mixed {c} Used internally by the compiler."; } public ExceptionType[] thrown() { return null; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.1.2"; } public Boolean runAsync() { return null; } public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws ConfigRuntimeException { return Static.resolveConstruct(args[0].val(), line_num, f); } } @api public static class eval implements Function { public String getName() { return "eval"; } public Integer[] numArgs() { return new Integer[]{1}; } public String docs() { return "string {script_string} Executes arbitrary MScript. Note that this function is very experimental, and is subject to changing or " + "removal."; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return true; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.1.0"; } public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException { return new CVoid(line_num, f); } //Doesn't matter, run out of state anyways public Boolean runAsync() { return null; } } @api public static class call_alias implements Function { public String getName() { return "call_alias"; } public Integer[] numArgs() { return new Integer[]{1}; } public String docs() { return "void {cmd} Allows a CommandHelper alias to be called from within another alias. Typically this is not possible, as" + " a script that runs \"/jail = /jail\" for instance, would simply be calling whatever plugin that actually" + " provides the jail functionality's /jail command. However, using this function makes the command loop back" + " to CommandHelper only."; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public String since() { return "3.2.0"; } public Boolean runAsync() { return null; } public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws ConfigRuntimeException { Static.getAliasCore().removePlayerReference(p); Static.getAliasCore().alias(args[0].val(), p, null); Static.getAliasCore().addPlayerReference(p); return new CVoid(line_num, f); } } }
package org.atennert.connector.reader; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.TooManyListenersException; import java.util.concurrent.BlockingQueue; import org.atennert.connector.IDistributor; import org.atennert.connector.IEventListener; import org.atennert.connector.packets.Packet; import org.atennert.connector.reader.ComConnector.ConnectionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages the connection to the EnOcean transceiver. It uses RXTX to * read and send messages.<br> * <br> * While reading and writing is not active, it listens for updates of the serial * ports and forwards changes to registered port listeners. The received bytes * are changed to integers and put in a queue. The messages to send are taken * from a queue in form of {@link Packet} instances. * * @author Andreas Tennert */ public class ComConnector implements Runnable, IDistributor<ConnectionStatus> { /** * Values for informing listeners about current connection status. */ public enum ConnectionStatus { OPENED, CLOSED, OPEN_FAILED } private static final int READ_WRITE_MODE_WAIT_TIME = 500; private static CommPortIdentifier serialPortId; @SuppressWarnings("rawtypes") private static Enumeration enumComm; private SerialPort serialPort; private InputStream inputStream; private OutputStream outputStream; private Boolean serialPortOpen = false; private final int baudrate = 57600; private final int dataBits = SerialPort.DATABITS_8; private final int stopBits = SerialPort.STOPBITS_1; private final int parity = SerialPort.PARITY_NONE; private String portName = null; /** read/write mode is supposed to be active */ private volatile boolean doRun; private static final Logger log = LoggerFactory.getLogger(ComConnector.class); private final List<IEventListener<ConnectionStatus>> statusListeners = new ArrayList<IEventListener<ConnectionStatus>>(); private ConnectionStatus status; private final BlockingQueue<Integer> messageByteQueue; private final BlockingQueue<Packet> sendPacketQueue; private final PortUpdater portUpdater; /** * @param messageByteQueue queue for forwarding of message parts * @param sendPacketQueue queue for packets to send away */ public ComConnector(BlockingQueue<Integer> messageByteQueue, BlockingQueue<Packet> sendPacketQueue) { this.messageByteQueue = messageByteQueue; this.sendPacketQueue = sendPacketQueue; // start port updater for continuous updates on serial port changes portUpdater = new PortUpdater(); portUpdater.start(); status = ConnectionStatus.CLOSED; } @Override public void addListener(IEventListener<ConnectionStatus> listener) { synchronized ( statusListeners ) { statusListeners.add(listener); listener.onEvent(status); } } @Override public void removeListener(IEventListener<ConnectionStatus> listener) { synchronized ( statusListeners ) { statusListeners.remove(listener); } } private void updateListeners(ConnectionStatus status) { synchronized ( statusListeners ) { this.status = status; for ( final IEventListener<ConnectionStatus> listener : statusListeners ) { listener.onEvent(status); } } } /** * Stop the read/write mode (ComConnector thread). */ public void stopThread() { doRun = false; } /** * @return the port updater, that sends updates on changes of available * serial ports */ public IDistributor<List<String>> getPortUpdater() { return portUpdater; } /** * Thread loop for managing the read/write mode. */ @Override public void run() { log.debug("Starting connector thread."); // stop serial port updates and activate read/write mode portUpdater.interrupt(); messageByteQueue.clear(); doRun = true; if ( openPort(portName) == true ) { log.debug("Connector thread initialized."); updateListeners(ConnectionStatus.OPENED); // read/write mode is activated, wait for stop request while ( doRun ) { try { Thread.sleep(READ_WRITE_MODE_WAIT_TIME); } catch ( final InterruptedException e ) { } } // stop read/write mode and start port change updates closePort(); updateListeners(ConnectionStatus.CLOSED); } else { updateListeners(ConnectionStatus.OPEN_FAILED); } portUpdater.start(); log.debug("Connector thread stopped."); } /** * @return all currently available serial ports */ private List<String> getPortNames() { final List<String> portNames = new ArrayList<String>(); enumComm = CommPortIdentifier.getPortIdentifiers(); while ( enumComm.hasMoreElements() ) { serialPortId = (CommPortIdentifier)enumComm.nextElement(); portNames.add(serialPortId.getName()); } return portNames; } /** * Set the serial port to which the EnOcean transceiver is connected. * * @param portName new serial port to use * @return <code>true</code> if the given port was valid and therefore set, * <code>false</code> otherwise */ public boolean setSerialPort(String portName) { if ( portName != null && !doRun && getPortNames().contains(portName) ) { this.portName = portName; return true; } log.error("Unable to set port " + portName + "!"); return false; } /** * Open the serial port connection. * * @param portName * @return serial port open */ private boolean openPort(String portName) { if ( portName == null ) { return false; } Boolean foundPort = false; if ( serialPortOpen != false ) { log.error("Serial port already opened!"); return false; } log.debug("Opening serial port."); enumComm = CommPortIdentifier.getPortIdentifiers(); while ( enumComm.hasMoreElements() ) { serialPortId = (CommPortIdentifier)enumComm.nextElement(); if ( portName.contentEquals(serialPortId.getName()) ) { foundPort = true; break; } } if ( foundPort != true ) { log.error("Could not find serial port: " + portName); return false; } try { serialPort = (SerialPort)serialPortId.open("Open and send", 100); inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); ( new Thread(new SerialPortWriter()) ).start(); serialPort.addEventListener(new SerialPortListener()); serialPort.notifyOnDataAvailable(true); serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity); } catch ( final PortInUseException e ) { log.error("Port is in use!"); } catch ( final IOException e ) { log.error("No access to InputStream!"); } catch ( final TooManyListenersException e ) { log.error("TooManyListenersException for serial port!"); } catch ( final UnsupportedCommOperationException e ) { log.error("Unable to set interface parameters!"); } log.debug("Opened port " + portName + "."); serialPortOpen = true; return true; } /** * Close the serial port */ private void closePort() { if ( serialPortOpen == true ) { log.debug("Closing serial port."); try { inputStream.close(); } catch ( final IOException e ) { log.error(e.getMessage()); } serialPort.close(); serialPortOpen = false; } else { log.error("Serial port already closed."); } } /** * Read data from the serial port, change the read bytes to integers and put * them in the queue for received data. */ private void readData() { try { final byte[] data = new byte[150]; int num; while ( inputStream.available() > 0 ) { num = inputStream.read(data, 0, data.length); for ( int i = 0; i < num; i++ ) { messageByteQueue.add(new Integer( ( data[i] & 0x7F ) + ( data[i] < 0 ? 128 : 0 ))); } } } catch ( final IOException e ) { log.error("Error while reading incoming data!"); } } /** * This event listener gets notified about incoming data. */ private class SerialPortListener implements SerialPortEventListener { @Override public void serialEvent(SerialPortEvent event) { if ( event.getEventType() == SerialPortEvent.DATA_AVAILABLE ) { readData(); } } } /** * This class takes packets from the send queue, transforms them to byte * messages and sends them away via the EnOcean transceiver. */ private class SerialPortWriter implements Runnable { @Override public void run() { Packet packet; while ( doRun ) { try { Thread.sleep(READ_WRITE_MODE_WAIT_TIME); } catch ( final InterruptedException e ) { } while ( ( packet = sendPacketQueue.poll() ) != null ) { try { outputStream.write(PacketEncoder.encodePacket(packet)); } catch ( final IOException e ) { log.error("Error while sending packet: " + packet); } } } } } /** * This class repeatedly checks for the available serial ports. If one or * more ports changed it sends an update to all registered port listeners. */ private class PortUpdater extends Thread implements IDistributor<List<String>> { /** list of currently available ports */ private List<String> ports = new ArrayList<String>(); /** list of port listeners */ private final List<IEventListener<List<String>>> listeners = new ArrayList<IEventListener<List<String>>>(); @Override public void addListener(IEventListener<List<String>> listener) { synchronized ( ports ) { listeners.add(listener); listener.onEvent(ports); } } @Override public void removeListener(IEventListener<List<String>> listener) { synchronized ( ports ) { listeners.remove(listener); } } /** * Send the a list of serial ports to all registered listeners. * * @param ports new list of serial ports */ private void distributeEvent(List<String> ports) { for ( final IEventListener<List<String>> l : listeners ) { l.onEvent(ports); } } @Override public void run() { log.debug("PortUpdater thread started."); while ( !isInterrupted() ) { synchronized ( ports ) { final List<String> ports = getPortNames(); if ( ports.size() != this.ports.size() || !this.ports.containsAll(ports) ) { this.ports = ports; distributeEvent(this.ports); } } try { // update list every second sleep(1000); } catch ( final InterruptedException e ) { interrupt(); } } log.debug("PortUpdater thread stopped."); } } }
package com.lothrazar.cyclic.registry; import com.lothrazar.cyclic.ConfigManager; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.block.battery.ItemBlockBattery; import com.lothrazar.cyclic.block.cable.CableWrench; import com.lothrazar.cyclic.block.expcollect.ExpItemGain; import com.lothrazar.cyclic.block.scaffolding.ItemScaffolding; import com.lothrazar.cyclic.block.tank.ItemBlockTank; import com.lothrazar.cyclic.item.EnderBagItem; import com.lothrazar.cyclic.item.EnderWingItem; import com.lothrazar.cyclic.item.EnderWingSp; import com.lothrazar.cyclic.item.EvokerFangItem; import com.lothrazar.cyclic.item.FireScepter; import com.lothrazar.cyclic.item.GemstoneItem; import com.lothrazar.cyclic.item.HeartItem; import com.lothrazar.cyclic.item.HeartToxicItem; import com.lothrazar.cyclic.item.IceWand; import com.lothrazar.cyclic.item.ItemCaveFinder; import com.lothrazar.cyclic.item.LeverRemote; import com.lothrazar.cyclic.item.LightningScepter; import com.lothrazar.cyclic.item.MattockItem; import com.lothrazar.cyclic.item.PeatItem; import com.lothrazar.cyclic.item.ShearsMaterial; import com.lothrazar.cyclic.item.SleepingMatItem; import com.lothrazar.cyclic.item.SnowScepter; import com.lothrazar.cyclic.item.StirrupsItem; import com.lothrazar.cyclic.item.WaterSpreaderItem; import com.lothrazar.cyclic.item.WrenchItem; import com.lothrazar.cyclic.item.bauble.AirAntiGravity; import com.lothrazar.cyclic.item.bauble.AutoTorchItem; import com.lothrazar.cyclic.item.bauble.CharmAntidote; import com.lothrazar.cyclic.item.bauble.CharmFire; import com.lothrazar.cyclic.item.bauble.CharmOverpowered; import com.lothrazar.cyclic.item.bauble.CharmVoid; import com.lothrazar.cyclic.item.bauble.CharmWither; import com.lothrazar.cyclic.item.bauble.GloveItem; import com.lothrazar.cyclic.item.boomerang.BoomerangItem; import com.lothrazar.cyclic.item.boomerang.BoomerangItem.Boomer; import com.lothrazar.cyclic.item.builder.BuildStyle; import com.lothrazar.cyclic.item.builder.BuilderItem; import com.lothrazar.cyclic.item.endereye.ItemEnderEyeReuse; import com.lothrazar.cyclic.item.enderpearl.EnderPearlMount; import com.lothrazar.cyclic.item.enderpearl.EnderPearlReuse; import com.lothrazar.cyclic.item.findspawner.ItemProjectileDungeon; import com.lothrazar.cyclic.item.horse.ItemHorseEmeraldJump; import com.lothrazar.cyclic.item.horse.ItemHorseHealthDiamondCarrot; import com.lothrazar.cyclic.item.horse.ItemHorseLapisVariant; import com.lothrazar.cyclic.item.horse.ItemHorseRedstoneSpeed; import com.lothrazar.cyclic.item.horse.ItemHorseToxic; import com.lothrazar.cyclic.item.magicnet.ItemMagicNet; import com.lothrazar.cyclic.item.magicnet.ItemMobContainer; import com.lothrazar.cyclic.item.random.RandomizerItem; import com.lothrazar.cyclic.item.scythe.ScytheBrush; import com.lothrazar.cyclic.item.scythe.ScytheForage; import com.lothrazar.cyclic.item.scythe.ScytheLeaves; import com.lothrazar.cyclic.item.torchthrow.ItemTorchThrower; import com.lothrazar.cyclic.item.transporter.TileTransporterEmptyItem; import com.lothrazar.cyclic.item.transporter.TileTransporterItem; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ArmorItem; import net.minecraft.item.AxeItem; import net.minecraft.item.BlockItem; import net.minecraft.item.HoeItem; import net.minecraft.item.Item; import net.minecraft.item.PickaxeItem; import net.minecraft.item.ShovelItem; import net.minecraft.item.SwordItem; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.ObjectHolder; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class ItemRegistry { @ObjectHolder(ModCyclic.MODID + ":gem_amber") public static Item gem_amber; @ObjectHolder(ModCyclic.MODID + ":biomass") public static Item biomass; @ObjectHolder(ModCyclic.MODID + ":cable_wrench") public static CableWrench cable_wrench; @ObjectHolder(ModCyclic.MODID + ":antigravity") public static Item antigravity; @ObjectHolder(ModCyclic.MODID + ":build_scepter") public static Item build_scepter; @ObjectHolder(ModCyclic.MODID + ":spawner_seeker") public static Item spawner_seeker; @ObjectHolder(ModCyclic.MODID + ":gem_obsidian") public static Item gem_obsidian; @ObjectHolder(ModCyclic.MODID + ":lapis_carrot_variant") public static Item lapis_carrot_variant; @ObjectHolder(ModCyclic.MODID + ":boomerang_damage") public static Item boomerang_damage; @ObjectHolder(ModCyclic.MODID + ":boomerang_carry") public static Item boomerang_carry; @ObjectHolder(ModCyclic.MODID + ":boomerang_stun") public static Item boomerang_stun; @ObjectHolder(ModCyclic.MODID + ":emerald_carrot_jump") public static Item emerald_carrot_jump; @ObjectHolder(ModCyclic.MODID + ":redstone_carrot_speed") public static Item redstone_carrot_speed; @ObjectHolder(ModCyclic.MODID + ":diamond_carrot_health") public static Item diamond_carrot_health; @ObjectHolder(ModCyclic.MODID + ":torch_launcher") public static ItemTorchThrower torch_launcher; @ObjectHolder(ModCyclic.MODID + ":scaffold_replace") public static ItemScaffolding item_scaffold_replace; @ObjectHolder(ModCyclic.MODID + ":scaffold_fragile") public static ItemScaffolding item_scaffold_fragile; @ObjectHolder(ModCyclic.MODID + ":scaffold_responsive") public static ItemScaffolding item_scaffold_responsive; @ObjectHolder(ModCyclic.MODID + ":mob_container") public static ItemMobContainer mob_container; @ObjectHolder(ModCyclic.MODID + ":wrench") public static WrenchItem wrench; @ObjectHolder(ModCyclic.MODID + ":peat_fuel") public static PeatItem peat_fuel; @ObjectHolder(ModCyclic.MODID + ":peat_fuel_enriched") public static PeatItem peat_fuel_enriched; @ObjectHolder(ModCyclic.MODID + ":experience_food") public static Item experience_food; @ObjectHolder(ModCyclic.MODID + ":magic_net") public static Item magic_net; @ObjectHolder(ModCyclic.MODID + ":tile_transporter") public static Item tile_transporter; @ObjectHolder(ModCyclic.MODID + ":tile_transporter_empty") public static Item tile_transporterempty; @ObjectHolder(ModCyclic.MODID + ":toxic_carrot") public static Item toxic_carrot; @SubscribeEvent public static void onItemsRegistry(RegistryEvent.Register<Item> event) { IForgeRegistry<Item> r = event.getRegistry(); // blocks r.register(new BlockItem(BlockRegistry.fan, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("fan")); r.register(new BlockItem(BlockRegistry.peat_generator, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("peat_generator")); r.register(new BlockItem(BlockRegistry.peat_unbaked, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("peat_unbaked")); r.register(new BlockItem(BlockRegistry.peat_baked, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("peat_baked")); r.register(new BlockItem(BlockRegistry.soundproofing, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("soundproofing")); r.register(new BlockItem(BlockRegistry.solidifier, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("solidifier")); r.register(new BlockItem(BlockRegistry.melter, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("melter")); r.register(new BlockItem(BlockRegistry.structure, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("structure")); r.register(new BlockItem(BlockRegistry.placer, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("placer")); r.register(new BlockItem(BlockRegistry.anvil, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("anvil")); r.register(new ItemScaffolding(BlockRegistry.scaffold_replace, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("scaffold_replace")); r.register(new ItemScaffolding(BlockRegistry.scaffold_fragile, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("scaffold_fragile")); r.register(new ItemScaffolding(BlockRegistry.scaffold_responsive, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("scaffold_responsive")); r.register(new ItemBlockTank(BlockRegistry.tank, new Item.Properties().group( MaterialRegistry.itemGroup)).setRegistryName("tank")); r.register(new BlockItem(BlockRegistry.spikes_iron, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("spikes_iron")); r.register(new BlockItem(BlockRegistry.spikes_curse, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("spikes_curse")); r.register(new BlockItem(BlockRegistry.spikes_fire, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("spikes_fire")); r.register(new BlockItem(BlockRegistry.breaker, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("breaker")); r.register(new BlockItem(BlockRegistry.collector, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("collector")); r.register(new BlockItem(BlockRegistry.dark_glass, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("dark_glass")); r.register(new ItemBlockBattery(BlockRegistry.battery, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("battery")); r.register(new BlockItem(BlockRegistry.experience_pylon, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("experience_pylon")); r.register(new BlockItem(BlockRegistry.harvester, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("harvester")); r.register(new BlockItem(BlockRegistry.trash, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("trash")); r.register(new BlockItem(BlockRegistry.energy_pipe, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("energy_pipe")); r.register(new BlockItem(BlockRegistry.item_pipe, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("item_pipe")); r.register(new BlockItem(BlockRegistry.fluid_pipe, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("fluid_pipe")); r.register(new CableWrench(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("cable_wrench")); // resources r.register(new ExpItemGain(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("experience_food")); r.register(new GemstoneItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("gem_obsidian")); r.register(new GemstoneItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("gem_amber")); r.register(new PeatItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("peat_fuel")); r.register(new PeatItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("peat_fuel_enriched")); r.register(new PeatItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("biomass")); // basic tools r.register(new MattockItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(9000)).setRegistryName("mattock")); r.register(new SleepingMatItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("sleeping_mat")); r.register(new ShearsMaterial(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(1024 * 1024)).setRegistryName("shears_obsidian")); r.register(new ShearsMaterial(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(64)).setRegistryName("shears_flint")); r.register(new WrenchItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("wrench")); r.register(new ScytheBrush(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("scythe_brush")); r.register(new ScytheForage(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("scythe_forage")); r.register(new ScytheLeaves(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("scythe_leaves")); r.register(new StirrupsItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("stirrups")); r.register(new LeverRemote(new Item.Properties().group(MaterialRegistry.itemGroup).maxStackSize(1)).setRegistryName("lever_remote")); r.register(new BuilderItem(new Item.Properties().group(MaterialRegistry.itemGroup), BuildStyle.NORMAL).setRegistryName("build_scepter")); r.register(new BuilderItem(new Item.Properties().group(MaterialRegistry.itemGroup), BuildStyle.REPLACE).setRegistryName("replace_scepter")); r.register(new BuilderItem(new Item.Properties().group(MaterialRegistry.itemGroup), BuildStyle.OFFSET).setRegistryName("offset_scepter")); r.register(new RandomizerItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("randomize_scepter")); r.register(new BoomerangItem(Boomer.STUN, new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("boomerang_stun")); r.register(new BoomerangItem(Boomer.CARRY, new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("boomerang_carry")); r.register(new BoomerangItem(Boomer.DAMAGE, new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("boomerang_damage")); // magic tools r.register(new SnowScepter(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("ice_scepter")); r.register(new FireScepter(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("fire_scepter")); r.register(new LightningScepter(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("lightning_scepter")); r.register(new EnderBagItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("ender_bag")); r.register(new WaterSpreaderItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("spell_water")); r.register(new IceWand(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("spell_ice")); r.register(new ItemTorchThrower(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("torch_launcher")); r.register(new AutoTorchItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256 * 4)).setRegistryName("charm_torch")); r.register(new EnderWingItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("charm_home")); r.register(new EnderWingSp(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("charm_world")); r.register(new EvokerFangItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("evoker_fang")); r.register(new ItemEnderEyeReuse(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("ender_eye_reuse")); r.register(new EnderPearlReuse(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("ender_pearl_reuse")); r.register(new EnderPearlMount(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("ender_pearl_mounted")); r.register(new ItemProjectileDungeon(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("spawner_seeker")); r.register(new ItemCaveFinder(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("spelunker")); r.register(new ItemMagicNet(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("magic_net")); r.register(new ItemMobContainer(new Item.Properties().maxStackSize(1)).setRegistryName("mob_container")); r.register(new TileTransporterEmptyItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("tile_transporter_empty")); r.register(new TileTransporterItem(new Item.Properties()).setRegistryName("tile_transporter")); if (ConfigManager.GLOVE.get()) { r.register(new GloveItem(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("glove_climb")); } if (ConfigManager.CHARMS.get()) { r.register(new AirAntiGravity(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(1024 * 4)).setRegistryName("antigravity")); r.register(new CharmVoid(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(64)).setRegistryName("charm_void")); r.register(new CharmAntidote(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(64)).setRegistryName("charm_antidote")); r.register(new CharmFire(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(64)).setRegistryName("charm_fire")); r.register(new CharmWither(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(64)).setRegistryName("charm_wither")); r.register(new CharmOverpowered(new Item.Properties().group(MaterialRegistry.itemGroup).maxDamage(256)).setRegistryName("charm_ultimate")); } if (ConfigManager.CARROTS.get()) { r.register(new ItemHorseHealthDiamondCarrot(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("diamond_carrot_health")); r.register(new ItemHorseRedstoneSpeed(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("redstone_carrot_speed")); r.register(new ItemHorseEmeraldJump(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_carrot_jump")); r.register(new ItemHorseLapisVariant(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("lapis_carrot_variant")); r.register(new ItemHorseToxic(new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("toxic_carrot")); } if (ConfigManager.GEMGEAR.get()) { r.register(new SwordItem(MaterialRegistry.ToolMats.GEMOBSIDIAN, 3, -2.4F, (new Item.Properties()).group(MaterialRegistry.itemGroup)).setRegistryName("crystal_sword")); r.register(new PickaxeItem(MaterialRegistry.ToolMats.GEMOBSIDIAN, 1, -2.8F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_pickaxe")); r.register(new AxeItem(MaterialRegistry.ToolMats.GEMOBSIDIAN, 5.0F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_axe")); r.register(new HoeItem(MaterialRegistry.ToolMats.GEMOBSIDIAN, 0.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_hoe")); r.register(new ShovelItem(MaterialRegistry.ToolMats.GEMOBSIDIAN, 1.5F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_shovel")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.GEMOBSIDIAN, EquipmentSlotType.FEET, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_boots")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.GEMOBSIDIAN, EquipmentSlotType.HEAD, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_helmet")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.GEMOBSIDIAN, EquipmentSlotType.CHEST, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_chestplate")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.GEMOBSIDIAN, EquipmentSlotType.LEGS, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("crystal_leggings")); } if (ConfigManager.EMERALD.get()) { r.register(new SwordItem(MaterialRegistry.ToolMats.EMERALD, 3, -2.4F, (new Item.Properties()).group(MaterialRegistry.itemGroup)).setRegistryName("emerald_sword")); r.register(new PickaxeItem(MaterialRegistry.ToolMats.EMERALD, 1, -2.8F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_pickaxe")); r.register(new AxeItem(MaterialRegistry.ToolMats.EMERALD, 5.0F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_axe")); r.register(new HoeItem(MaterialRegistry.ToolMats.EMERALD, 0.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_hoe")); r.register(new ShovelItem(MaterialRegistry.ToolMats.EMERALD, 1.5F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_shovel")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.EMERALD, EquipmentSlotType.FEET, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_boots")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.EMERALD, EquipmentSlotType.HEAD, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_helmet")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.EMERALD, EquipmentSlotType.CHEST, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_chestplate")); r.register(new ArmorItem(MaterialRegistry.ArmorMats.EMERALD, EquipmentSlotType.LEGS, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("emerald_leggings")); } if (ConfigManager.SANDSTONE.get()) { r.register(new SwordItem(MaterialRegistry.ToolMats.SANDSTONE, 3, -2.4F, (new Item.Properties()).group(MaterialRegistry.itemGroup)).setRegistryName("sandstone_sword")); r.register(new PickaxeItem(MaterialRegistry.ToolMats.SANDSTONE, 1, -2.8F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("sandstone_pickaxe")); r.register(new AxeItem(MaterialRegistry.ToolMats.SANDSTONE, 5.0F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("sandstone_axe")); r.register(new HoeItem(MaterialRegistry.ToolMats.SANDSTONE, 0.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("sandstone_hoe")); r.register(new ShovelItem(MaterialRegistry.ToolMats.SANDSTONE, 1.5F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("sandstone_shovel")); } if (ConfigManager.NETHERBRICK.get()) { r.register(new SwordItem(MaterialRegistry.ToolMats.NETHERBRICK, 3, -2.4F, (new Item.Properties()).group(MaterialRegistry.itemGroup)).setRegistryName("netherbrick_sword")); r.register(new PickaxeItem(MaterialRegistry.ToolMats.NETHERBRICK, 1, -2.8F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("netherbrick_pickaxe")); r.register(new AxeItem(MaterialRegistry.ToolMats.NETHERBRICK, 5.0F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("netherbrick_axe")); r.register(new HoeItem(MaterialRegistry.ToolMats.NETHERBRICK, 0.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("netherbrick_hoe")); r.register(new ShovelItem(MaterialRegistry.ToolMats.NETHERBRICK, 1.5F, -3.0F, new Item.Properties().group(MaterialRegistry.itemGroup)).setRegistryName("netherbrick_shovel")); } if (ConfigManager.HEARTS.get()) { r.register(new HeartItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxStackSize(16)).setRegistryName("heart")); r.register(new HeartToxicItem(new Item.Properties().group(MaterialRegistry.itemGroup).maxStackSize(16)).setRegistryName("heart_empty")); } } }
package engg2800.usb.event.listener; import engg2800.image.TransmittedImage; import engg2800.image.processing.ByteArrayToBufferedImage; import jssc.SerialPort; import jssc.SerialPortEvent; import jssc.SerialPortEventListener; import jssc.SerialPortException; import engg2800.ui.WindowFrame; import java.awt.image.BufferedImage; /** * Read Transmission from Serial COMS Port * @author Aaron Hayes */ public class SerialPortReader implements SerialPortEventListener { private SerialPort serialPort = null; private WindowFrame windowFrame; private static final int MASK = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR; public static final int WIDTH = 200; public static final int HEIGHT = 160; private byte[] byteMap; private byte[] lastEight; private int currentX; private int currentY; private boolean readingImage = false; private int count; public SerialPortReader(WindowFrame wf) { windowFrame = wf; byteMap = new byte[WIDTH * HEIGHT]; lastEight = new byte[8]; currentX = 0; currentY = 0; count = 0; } /** * Read Data from Serial Port on event * @param event SerialPortEvent */ public void serialEvent(SerialPortEvent event) { if (windowFrame.getSerialPortConnection().getStatus()) { if (event.isRXCHAR()) { try { byte buffer[] = serialPort.readBytes(32); if (buffer != null) { for (byte aBuffer : buffer) { if (readingImage) { //int p = buffer[b] & 0xFF; //System.out.println(p + " (" + currentX + ", " + currentY + ")"); /*byteMap[(currentY * WIDTH) + currentX] = aBuffer; currentX++; if (currentX >= WIDTH) { currentX = 0; currentY++; if (currentY >= HEIGHT) { uploadImage(); break; } }*/ byteMap[count++] = aBuffer; if (count >= (WIDTH * HEIGHT)) { uploadImage(); } updateLastByte(aBuffer); } else { updateLastByte(aBuffer); } } } } catch (SerialPortException e) { e.printStackTrace(); } } } } /** * Add received byte to lst * @param b byte */ private void updateLastByte(byte b) { lastEight[7] = lastEight[6]; lastEight[6] = lastEight[5]; lastEight[5] = lastEight[4]; lastEight[4] = lastEight[3]; lastEight[3] = lastEight[2]; lastEight[2] = lastEight[1]; lastEight[1] = lastEight[0]; lastEight[0] = b; checkLastEight(); } /** * Check the last eight bytes for start/stop signal */ private void checkLastEight() { /* check for start signal */ if(lastEight[7] == (byte) 0xFF && lastEight[6] == (byte) 0x00 && lastEight[5] == (byte) 0xFF && lastEight[4] == (byte) 0x00 && lastEight[3] == (byte) 0xFF && lastEight[2] == (byte) 0x00 && lastEight[1] == (byte) 0xFF && lastEight[0] == (byte) 0x00) { readingImage = true; return; } /* check for stop signal */ if(lastEight[7] == (byte) 0x00 && lastEight[6] == (byte) 0xFF && lastEight[5] == (byte) 0x00 && lastEight[4] == (byte) 0xFF && lastEight[3] == (byte) 0x00 && lastEight[2] == (byte) 0xFF && lastEight[1] == (byte) 0x00 && lastEight[0] == (byte) 0xFF) { if (readingImage) { fillImage(); uploadImage(); } else { reset(); } } } /** * Got stop signal from engg2800.image, fill in missing pixels. */ private void fillImage() { //for (int i = 0; i < WIDTH * HEIGHT; i++) { } /** * Convert imageMap into single engg2800.image and send to screen */ private void uploadImage() { //BufferedImage bufferedImage = JoinBufferedImages.stitchArray(imageMap, TransmittedImage.IMG_WIDTH, TransmittedImage.IMG_HEIGHT); BufferedImage bufferedImage = ByteArrayToBufferedImage.Convert(byteMap, WIDTH, HEIGHT); windowFrame.addImage(new TransmittedImage(bufferedImage, WIDTH, HEIGHT)); reset(); } /** * Reset variables to beginning of an engg2800.image */ private void reset() { currentY = 0; currentX = 0; count = 0; for (int i = 0; i < WIDTH * HEIGHT; i++) { byteMap[i] = 0; } readingImage = false; } /** * Close the serial Port */ public void closePort() { if (serialPort != null) { try { if (serialPort.isOpened()) { serialPort.closePort(); } } catch (SerialPortException e) { e.printStackTrace(); } } } /** * Open a new serial port * @param port Serial Port Connection */ public void openPort(String port) { serialPort = new SerialPort(port); try { serialPort.openPort(); serialPort.setParams(SerialPort.BAUDRATE_19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE); serialPort.setEventsMask(MASK); serialPort.addEventListener(this); } catch (SerialPortException e) { e.printStackTrace(); } } }
package com.mcjty.rftools; import com.mcjty.rftools.blocks.teleporter.GlobalCoordinate; import com.mcjty.rftools.blocks.teleporter.TeleportDestination; import com.mcjty.rftools.blocks.teleporter.TeleportDestinations; import com.mcjty.rftools.blocks.teleporter.TeleportationTools; import com.mcjty.rftools.network.PacketHandler; import com.mcjty.rftools.network.PacketSendBuffsToClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; import net.minecraftforge.common.IExtendedEntityProperties; import java.util.*; public class PlayerExtendedProperties implements IExtendedEntityProperties { public static final String ID = "rftoolsTimedTeleport"; public static final int BUFF_MAXTICKS = 180; private int buffTimeout; private int target; private int teleportTimeout; private Entity entity = null; private boolean globalSyncNeeded = true; // Here we mirror the flags out of capabilities so that we can restore them. private boolean oldAllowFlying = false; private boolean allowFlying = false; private final Map<PlayerBuff,Integer> buffs = new HashMap<PlayerBuff, Integer>(); public PlayerExtendedProperties() { target = -1; teleportTimeout = -1; buffTimeout = 0; globalSyncNeeded = true; } public boolean isTeleporting() { return target != -1 && teleportTimeout >= 0; } private void syncBuffs() { PacketHandler.INSTANCE.sendTo(new PacketSendBuffsToClient(buffs), (EntityPlayerMP) entity); } private void performBuffs() { // Perform all buffs that we can perform here (not potion effects and also not // passive effects like feather falling. EntityPlayer player = (EntityPlayer) entity; boolean enableFlight = false; for (PlayerBuff buff : buffs.keySet()) { if (buff == PlayerBuff.BUFF_FLIGHT) { enableFlight = true; } } boolean oldAllow = player.capabilities.allowFlying; if (enableFlight) { if (!allowFlying) { // We were not already allowing flying. oldAllowFlying = player.capabilities.allowFlying; allowFlying = true; } player.capabilities.allowFlying = true; } else { if (allowFlying) { // We were flying before. player.capabilities.allowFlying = oldAllowFlying; if (player.capabilities.isCreativeMode) { player.capabilities.allowFlying = true; } allowFlying = false; } } if (player.capabilities.allowFlying != oldAllow) { if (!player.capabilities.allowFlying) { player.capabilities.isFlying = false; } player.sendPlayerAbilities(); } } public static PlayerExtendedProperties getProperties(EntityPlayer player) { IExtendedEntityProperties properties = player.getExtendedProperties(ID); return (PlayerExtendedProperties) properties; } public static void addBuff(EntityPlayer player, PlayerBuff buff, int ticks) { IExtendedEntityProperties properties = player.getExtendedProperties(ID); PlayerExtendedProperties playerExtendedProperties = (PlayerExtendedProperties) properties; playerExtendedProperties.addBuff(buff, ticks); } public void addBuff(PlayerBuff buff, int ticks) { //. We add a bit to the ticks to make sure we can live long enough. buffs.put(buff, ticks + 5); syncBuffs(); performBuffs(); } public Map<PlayerBuff, Integer> getBuffs() { return buffs; } public boolean hasBuff(PlayerBuff buff) { return buffs.containsKey(buff); } public void startTeleport(int target, int ticks) { this.target = target; this.teleportTimeout = ticks; } public void tick() { tickTeleport(); tickBuffs(); } private void tickBuffs() { buffTimeout if (buffTimeout <= 0) { buffTimeout = BUFF_MAXTICKS; Map<PlayerBuff,Integer> copyBuffs = new HashMap<PlayerBuff, Integer>(buffs); buffs.clear(); boolean syncNeeded = false; for (Map.Entry<PlayerBuff, Integer> entry : copyBuffs.entrySet()) { int timeout = entry.getValue(); timeout -= BUFF_MAXTICKS; if (timeout > 0) { buffs.put(entry.getKey(), timeout); } else { syncNeeded = true; } } if (syncNeeded) { syncBuffs(); performBuffs(); globalSyncNeeded = false; } } if (globalSyncNeeded) { globalSyncNeeded = false; syncBuffs(); performBuffs(); } } private void tickTeleport() { if (teleportTimeout < 0) { return; } teleportTimeout if (teleportTimeout <= 0) { EntityPlayer player = (EntityPlayer) entity; TeleportDestinations destinations = TeleportDestinations.getDestinations(entity.worldObj); GlobalCoordinate coordinate = destinations.getCoordinateForId(target); if (coordinate == null) { RFTools.message(player, EnumChatFormatting.RED + "Something went wrong! The target has disappeared!"); TeleportationTools.applyEffectForSeverity(player, 3); return; } TeleportDestination destination = destinations.getDestination(coordinate); TeleportationTools.performTeleport((EntityPlayer) entity, destination, 0, 10); teleportTimeout = -1; target = -1; } } @Override public void saveNBTData(NBTTagCompound compound) { compound.setInteger("target", target); compound.setInteger("ticks", teleportTimeout); compound.setInteger("buffTicks", buffTimeout); compound.setBoolean("allowFlying", allowFlying); compound.setBoolean("oldAllowFlying", oldAllowFlying); int[] buffArray = new int[buffs.size()]; int[] timeoutArray = new int[buffs.size()]; int idx = 0; for (Map.Entry<PlayerBuff, Integer> entry : buffs.entrySet()) { PlayerBuff buff = entry.getKey(); buffArray[idx] = buff.ordinal(); timeoutArray[idx] = entry.getValue(); idx++; } compound.setIntArray("buffs", buffArray); compound.setIntArray("buffTimeouts", timeoutArray); } @Override public void loadNBTData(NBTTagCompound compound) { if (compound.hasKey("target")) { target = compound.getInteger("target"); } else { target = -1; } if (compound.hasKey("ticks")) { teleportTimeout = compound.getInteger("ticks"); } else { teleportTimeout = -1; } buffTimeout = compound.getInteger("buffTicks"); int[] buffArray = compound.getIntArray("buffs"); int[] timeoutArray = compound.getIntArray("buffTimeouts"); buffs.clear(); for (int i = 0 ; i < buffArray.length ; i++) { int buffIdx = buffArray[i]; buffs.put(PlayerBuff.values()[buffIdx], timeoutArray[i]); } allowFlying = compound.getBoolean("allowFlying"); oldAllowFlying = compound.getBoolean("oldAllowFlying"); globalSyncNeeded = true; } @Override public void init(Entity entity, World world) { this.entity = entity; globalSyncNeeded = true; } }
package org.jaexcel.framework.JAEX.engine; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class EngineTest extends TestCase { /** * Create the test case * * @param testName * name of the test case */ public EngineTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(EngineTest.class); } /** * Test with default settings */ public void testBasicConfiguration() { assertEquals(true, false); } /** * Test with propagation type is HORIZONTAL */ public void testPropagationTypeHorizontal() { assertEquals(true, false); } /** * Test with propagation type is VERTICAL */ public void testPropagationTypeVertical() { assertEquals(true, false); } /** * Test with different ROW & CELL */ public void testRowCellSpecified() { assertEquals(true, false); } /** * Test with cascade type is CASCADE_LEVEL_ONE */ public void testCascadeTypeLevelOne() { assertEquals(true, false); } /** * Test with cascade type is CASCADE_LEVEL_TWO */ public void testCascadeTypeLevelTwo() { assertEquals(true, false); } /** * Test with cascade type is CASCADE_FULL */ public void testCascadeTypeFull() { assertEquals(true, false); } /** * Test an empty object */ public void testObjectEmpty() { assertEquals(true, false); } /** * Test an null object */ public void testObjectNulll() { assertEquals(true, false); } /** * Test an empty list */ public void testListEmpty() { assertEquals(true, false); } /** * Test an null list */ public void testListNulll() { assertEquals(true, false); } }
package com.openfin.desktop.demo; import com.openfin.desktop.*; import com.openfin.desktop.System; import com.openfin.desktop.animation.AnimationTransitions; import com.openfin.desktop.animation.PositionTransition; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.StringTokenizer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static junit.framework.Assert.*; import static junit.framework.TestCase.fail; public class OpenFinWindowTest { private static Logger logger = LoggerFactory.getLogger(JUnitDemo.class.getName()); private static DesktopConnection desktopConnection; private static final String DESKTOP_UUID = "DESKTOP_UUID"; private static int windowUuidCounter = 0; //set this to around 2000ms in order to see the chromium windows private final long SLEEP_FOR_HUMAN_OBSERVATION = 3000L; private static CountDownLatch openFinDisconnectedLatch = new CountDownLatch(1); @BeforeClass public static void setup() throws Exception { setupDesktopConnection(); } @AfterClass public static void teardown() throws Exception { printf("teardown"); if (desktopConnection.isConnected()) { teardownDesktopConnection(); } else { printf("Not connected, no need to teardown"); } } private static void setupDesktopConnection() throws Exception { CountDownLatch openFinConnectedLatch = new CountDownLatch(1); // if RVM needs to download the version of Runtime specified, waitTime may need to be increased for slow download int waitTime = 60; String swaiTime = java.lang.System.getProperty("com.openfin.demo.runtime.connect.wait.time"); if (swaiTime != null) { waitTime = Integer.parseInt(swaiTime); } desktopConnection = null; desktopConnection = new DesktopConnection(DESKTOP_UUID); desktopConnection.setAdditionalRuntimeArguments(" --v=1 "); // turn on Chromium debug log String desktopVersion = java.lang.System.getProperty("com.openfin.demo.runtime.version"); if (desktopVersion == null) { desktopVersion = "alpha"; } desktopConnection.connectToVersion(desktopVersion, new DesktopStateListener() { @Override public void onReady() { printf("Connected to OpenFin runtime"); openFinConnectedLatch.countDown(); openFinDisconnectedLatch = new CountDownLatch(1); } @Override public void onError(String reason) { printf("Connection failed: %s", reason); openFinDisconnectedLatch.countDown(); } @Override public void onMessage(String message) { printf("openfin message: %s", message); } @Override public void onOutgoingMessage(String message) { printf("openfin outgoing message: %s", message); } }, waitTime);//this timeout (in 4.40.2.9) is ignored printf("waiting for desktop to connect"); openFinConnectedLatch.await(waitTime, TimeUnit.SECONDS); if (desktopConnection.isConnected()) { printf("desktop connected"); } else { throw new RuntimeException("failed to initialise desktop connection"); } } private static void teardownDesktopConnection() throws Exception { printf("teardownDesktopConnection"); new System(desktopConnection).exit(); openFinDisconnectedLatch.await(20, TimeUnit.SECONDS); assertFalse(desktopConnection.isConnected()); printf("desktop connection closed"); } private Application openWindow(String uuid, String url) throws Exception { //default options for all test windows int top = 10; int left = 10; int width = 200; int height = 300; boolean withFrame = true; boolean resizable = true; return openWindow(uuid, url, left, top, width, height, withFrame, resizable); } private Application openWindow(String uuid, String url, int left, int top, int width, int height, boolean withFrame, boolean resizable) throws Exception { final WindowOptions windowOptions = new WindowOptions(); windowOptions.setAutoShow(true); windowOptions.setDefaultLeft(left); windowOptions.setDefaultTop(top); windowOptions.setDefaultHeight(height); windowOptions.setDefaultWidth(width); windowOptions.setFrame(withFrame); windowOptions.setResizable(resizable); ApplicationOptions applicationOptions = new ApplicationOptions(uuid, uuid, url); applicationOptions.setMainWindowOptions(windowOptions); //used to block JUnit thread until OpenFin has iniitialised CountDownLatch windowCreatedLatch = new CountDownLatch(1); //if this reference gets set, something went wrong creating the window final AtomicReference<String> failedReason = new AtomicReference<String>(); printf("creating new chromium window (uuid: %s) (left: %s) (top: %s) (width: %s) (height: %s) (withFrame: %s) (resizable: %s)", uuid, left, top, width, height, withFrame, resizable); Application application = new Application(applicationOptions, desktopConnection, new AckListener() { @Override public void onSuccess(Ack ack) { try { Application application = (Application) ack.getSource(); application.run(); printf("window running: %s", application.getOptions().getUUID()); application.getWindow().setBounds(left, top, width, height, new AckListener() { @Override public void onSuccess(Ack ack) { printf("successfully set bounds (uuid: %s) (left: %s) (top: %s) (width: %s) (height: %s)", uuid, left, top, width, height); } @Override public void onError(Ack ack) { printf("failed to set window bounds (uuid: %s)", uuid); } }); printf("explicity setting bounds (uuid: %s) (left: %s) (top: %s) (width: %s) (height: %s)", uuid, left, top, width, height); } catch (Exception e) { failedReason.set("failed to run window: " + ack.getReason()); } finally { windowCreatedLatch.countDown(); } } @Override public void onError(Ack ack) { try { failedReason.set("failed to open window: " + ack.getReason()); } finally { windowCreatedLatch.countDown(); } } }); //wait for OpenFin callback windowCreatedLatch.await(20, TimeUnit.SECONDS); if (failedReason.get() != null) { throw new RuntimeException(failedReason.get()); } else { return application; } } private static synchronized String nextTestUuid() { return String.format("test_uuid_%s", windowUuidCounter++); } @Test public void canStopAndRestartOpenFinDesktopConnection() throws Exception { //setupDesktopConnection() called from setup() teardownDesktopConnection(); setupDesktopConnection(); //teardownDesktopConnection() will be caled from teardown() } @Test public void canOpenAndCloseMultipleWindowsWithDifferentUUIDS() throws Exception { Application application1 = openWindow(nextTestUuid(), "http: Application application2 = openWindow(nextTestUuid(), "http: Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION);//allow the windows time to appear application1.close(); application2.close(); } @Test public void cannotOpenMultipleWindowsWithSameUUID() throws Exception { Application application1 = null; Application application2 = null; try { String uuid = nextTestUuid(); application1 = openWindow(uuid, "http: application2 = openWindow(uuid, "http: //above lines should throw an exception and not get past here fail(); } catch (Exception e) { assertTrue(e.getMessage().contains("Application with specified UUID already exists")); } finally { if (application1 != null) application1.close(); if (application2 != null) application2.close(); } } @Test public void windowMoves() throws Exception { Application application = openWindow(nextTestUuid(), "http: //set the initial position of the window and check CountDownLatch moveLatch = new CountDownLatch(1); application.getWindow().moveTo(10, 20, new AckListener() { @Override public void onSuccess(Ack ack) { moveLatch.countDown(); } @Override public void onError(Ack ack) { } }); moveLatch.await(5, TimeUnit.SECONDS); WindowBounds initialBounds = getWindowBounds(application.getWindow()); printf("initial bounds top:%s left:%s", initialBounds.getTop(), initialBounds.getLeft()); assertEquals(10, initialBounds.getLeft().intValue()); assertEquals(20, initialBounds.getTop().intValue()); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); //move the window and check again application.getWindow().moveTo(100, 200); WindowBounds movedBounds = getWindowBounds(application.getWindow()); printf("moved bounds top:%s left:%s", movedBounds.getTop(), movedBounds.getLeft()); assertEquals(100, movedBounds.getLeft().intValue()); assertEquals(200, movedBounds.getTop().intValue()); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); } @Test public void windowMovesWithAnimation() throws Exception { Application application = openWindow(nextTestUuid(), "http: //set the initial position of the window and check CountDownLatch moveLatch = new CountDownLatch(1); application.getWindow().moveTo(10, 20, new AckListener() { @Override public void onSuccess(Ack ack) { moveLatch.countDown(); } @Override public void onError(Ack ack) { } }); moveLatch.await(5, TimeUnit.SECONDS); WindowBounds initialBounds = getWindowBounds(application.getWindow()); printf("initial bounds top:%s left:%s", initialBounds.getTop(), initialBounds.getLeft()); assertEquals(10, initialBounds.getLeft().intValue()); assertEquals(20, initialBounds.getTop().intValue()); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); //move the window and check again CountDownLatch transitionLatch = new CountDownLatch(1); AnimationTransitions transitions = new AnimationTransitions(); transitions.setPosition(new PositionTransition(100, 200, 2000));//duration in millisecods application.getWindow().animate(transitions, null, new AckListener() { @Override public void onSuccess(Ack ack) { transitionLatch.countDown(); } @Override public void onError(Ack ack) { //noop } }); transitionLatch.await(20, TimeUnit.SECONDS); WindowBounds movedBounds = getWindowBounds(application.getWindow()); printf("moved bounds top:%s left:%s", movedBounds.getTop(), movedBounds.getLeft()); assertEquals(100, movedBounds.getLeft().intValue()); assertEquals(200, movedBounds.getTop().intValue()); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); } @Test public void windowEventListenersWork() throws Exception { Application application = openWindow(nextTestUuid(), "http: String events = "blurred bounds-changed bounds-changing closed close-requested disabled-frame-bounds-changed disabled-frame-bounds-changing focused frame-disabled frame-enabled group-changed hidden maximized minimized restored shown"; AtomicReference<String> eventTypeRecieved = new AtomicReference<String>(); CountDownLatch onMinimiseEventLatch = new CountDownLatch(1); //register even handlers for all event types StringTokenizer tokenizer = new StringTokenizer(events); while (tokenizer.hasMoreTokens()) { String event = tokenizer.nextToken().trim(); application.getWindow().addEventListener( event, actionEvent -> { printf("eventReceived: %s", actionEvent.getType()); String type = actionEvent.getType(); eventTypeRecieved.set(type); if ("minimized".equals(type)) { onMinimiseEventLatch.countDown(); } }, new AckListener() { @Override public void onSuccess(Ack ack) { printf("window '%s' onSuccess: %s", event, ack); } @Override public void onError(Ack ack) { printf("window '%s' onError: %s", event, ack); } } ); printf("added listener for event: %s", event); } //generate a minimized event to check that we get notification in the listener above application.getWindow().minimize(); onMinimiseEventLatch.await(20, TimeUnit.SECONDS); assertEquals("minimized event not recieved", "minimized", eventTypeRecieved.get()); } @Ignore("Cross app docking not supported") @Test public void windowsInShameGroupMoveTogether() throws Exception { final int width = 600, height = 900; //place two application windows next to each other Application applicationA = openWindow(nextTestUuid(), "http: Application applicationB = openWindow(nextTestUuid(), "http: //bind the windows in the same group so that they move togther applicationA.getWindow().joinGroup(applicationB.getWindow(), new AckListener() { @Override public void onSuccess(Ack ack) { printf("window A joined group"); } @Override public void onError(Ack ack) { printf("failed to join group"); } }); //move window A and check that B has followed it final int moveLefPositiontBy = 100; final int appBLeftStart = getWindowBounds(applicationB.getWindow()).getLeft(); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); applicationA.getWindow().moveBy(moveLefPositiontBy, 0, new AckListener() { @Override public void onSuccess(Ack ack) { printf("moved window A"); } @Override public void onError(Ack ack) { printf("failed to move window A"); } }); Thread.sleep(SLEEP_FOR_HUMAN_OBSERVATION); final int appBLeftEnd = getWindowBounds(applicationB.getWindow()).getLeft(); assertEquals("the window for app B did not follow the move for app A", appBLeftStart + moveLefPositiontBy, appBLeftEnd); } @Test public void notificationEventListenersWork() throws Exception { //record/wait for event CountDownLatch onCloseEventLatch = new CountDownLatch(1); AtomicReference<String> eventTypeRecieved = new AtomicReference<>(); NotificationOptions options = new NotificationOptions("http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/views/notification.html"); options.setTimeout(1000); options.setMessageText("testing"); new Notification(options, new NotificationListener() { @Override public void onClick(Ack ack) { eventTypeRecieved.set("onClick"); } @Override public void onClose(Ack ack) { eventTypeRecieved.set("onClose"); onCloseEventLatch.countDown(); } @Override public void onDismiss(Ack ack) { eventTypeRecieved.set("onDismiss"); } @Override public void onError(Ack ack) { eventTypeRecieved.set("onError"); } @Override public void onMessage(Ack ack) { eventTypeRecieved.set("onMessage"); } @Override public void onShow(Ack ack) { eventTypeRecieved.set("onShow"); } }, this.desktopConnection, null); //wait for the onClose notification to arrive onCloseEventLatch.await(20, TimeUnit.SECONDS); assertEquals("onClose", eventTypeRecieved.get()); } private WindowBounds getWindowBounds(Window window) throws Exception { final AtomicReference<WindowBounds> atomicRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); window.getBounds(windowBounds -> { atomicRef.set(windowBounds); latch.countDown(); }, null); latch.await(20, TimeUnit.SECONDS); WindowBounds windowBounds = atomicRef.get(); assertNotNull("failed to get bounds for window", windowBounds); return windowBounds; } private static void printf(String s, Object... args) { logger.info(String.format(s, args)); } }
package org.unitime.timetable.solver.interactive; import java.io.Serializable; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import net.sf.cpsolver.coursett.heuristics.TimetableComparator; import net.sf.cpsolver.coursett.model.Lecture; import net.sf.cpsolver.coursett.model.Placement; import net.sf.cpsolver.coursett.model.TimeLocation; import net.sf.cpsolver.coursett.model.TimetableModel; import net.sf.cpsolver.ifs.solver.Solver; import org.unitime.timetable.model.PreferenceLevel; /** * @author Tomas Muller */ public class Suggestions implements Serializable { private static final long serialVersionUID = 1L; private transient Solver iSolver = null; private transient TimetableModel iModel = null; private transient Lecture iLecture = null; private long iTimeOut = 5000; private boolean iSameRoom = false; private boolean iSameTime = false; private boolean iAllTheSame = true; private boolean iAllowBreakHard = false; private int iDepth = 2; private TreeSet iSuggestions = new TreeSet(); private transient Vector iHints = new Vector(); private boolean iTimeoutReached = false; private long iNrCombinationsConsidered = 0; private long iNrSolutions = 0; private Suggestion iCurrentSuggestion = null; private Suggestion iEmptySuggestion = null; private TreeSet iAllAssignments = null; private Vector iConfTable = null; private int iNrTries; private Vector iOriginalHints = null; private int iLimit = 100; private String iFilterText = null; private boolean iTryAllAssignments = true; private boolean iComputeSuggestions = true; private boolean iComputeConfTable = true; private int iMinRoomSize = -1; private int iMaxRoomSize = -1; public Suggestions(Solver solver, SuggestionsModel model) { iSolver = solver; iModel = (TimetableModel)iSolver.currentSolution().getModel(); iDepth = model.getDepth(); iTimeOut = model.getTimeout(); iAllTheSame = model.isAllTheSame(); iSameTime = (model.getFilter()==SuggestionsModel.sFilterSameTime); iSameRoom = (model.getFilter()==SuggestionsModel.sFilterSameRoom); iAllowBreakHard = model.getAllowBreakHard(); iHints = new Vector(model.getHints().size()); iOriginalHints = model.getHints(); iTryAllAssignments = model.getDisplayPlacements(); iComputeSuggestions = model.getDisplaySuggestions(); iComputeConfTable = model.getDisplayConfTable(); iLimit = model.getLimit(); if (iLimit<=0) { iComputeSuggestions=false; iTryAllAssignments=false; } iMinRoomSize = model.getMinRoomSize(); iMaxRoomSize = model.getMaxRoomSize(); iFilterText = (model.getFilterText()==null?null:model.getFilterText().trim().toUpperCase()); for (Lecture lecture: iModel.variables()) { if (lecture.getClassId().equals(model.getClassId())) { iLecture = lecture; break; } } for (Enumeration e=model.getHints().elements();e.hasMoreElements();) { Hint h = (Hint)e.nextElement(); Placement p = h.getPlacement(iModel); if (p==null) continue; //if (!h.hasInfo()) h.setInfo(iSolver, p); iHints.add(p); } if (iLecture!=null) compute(); } public boolean match(Placement p) { if (iMinRoomSize>=0 && p.getRoomSize()<iMinRoomSize) return false; if (iMaxRoomSize>=0 && p.getRoomSize()>iMaxRoomSize) return false; if (iFilterText==null || iFilterText.length()==0) return true; StringTokenizer stk = new StringTokenizer(iFilterText); while (stk.hasMoreTokens()) { String token = stk.nextToken(); if (p.getName().toUpperCase().indexOf(token)<0) return false; } return true; } public Vector getHints() { return iOriginalHints; } public void compute() { if (iComputeSuggestions) computeSuggestions(); if (iTryAllAssignments) computeTryAllAssignments(); if (iComputeConfTable) computeConfTable(); iCurrentSuggestion = tryAssignment((Placement)null); Hashtable initialAssignments = new Hashtable(); for (Lecture lec: iModel.assignedVariables()) { initialAssignments.put(lec,lec.getAssignment()); } iEmptySuggestion = new Suggestion(iSolver, initialAssignments, new Vector(), new Vector()); computeNrTries(); } public TreeSet getSuggestions() { return iSuggestions; } public void computeSuggestions() { iSuggestions.clear(); iTimeoutReached = false; iNrCombinationsConsidered = 0; iNrSolutions = 0; synchronized (iSolver.currentSolution()) { Vector unAssignedVariables = new Vector(iModel.unassignedVariables()); Hashtable initialAssignments = new Hashtable(); for (Lecture lec: iModel.assignedVariables()) { initialAssignments.put(lec,lec.getAssignment()); } Hashtable conflictsToResolve = new Hashtable(); Vector resolvedLectures = new Vector(); if (iHints!=null) { for (Enumeration e=iHints.elements();e.hasMoreElements();) { Placement plac = (Placement)e.nextElement(); Lecture lect = (Lecture)plac.variable(); Set conflicts = iModel.conflictValues(plac); for (Iterator i=conflicts.iterator();i.hasNext();) { Placement conflictPlacement = (Placement)i.next(); conflictsToResolve.put(conflictPlacement.variable(),conflictPlacement); conflictPlacement.variable().unassign(0); } resolvedLectures.add(lect.getClassId()); conflictsToResolve.remove(lect); lect.assign(0,plac); } } Vector initialLectures = new Vector(1); if (!resolvedLectures.contains(iLecture.getClassId())) initialLectures.add(iLecture); backtrack(System.currentTimeMillis(), initialLectures, resolvedLectures, conflictsToResolve, initialAssignments, iDepth); for (Enumeration e=unAssignedVariables.elements();e.hasMoreElements();) { Lecture lect = (Lecture)e.nextElement(); if (lect.getAssignment()!=null) lect.unassign(0); } for (Iterator i=initialAssignments.values().iterator();i.hasNext();) { Placement plac = (Placement)i.next(); Lecture lect = (Lecture)plac.variable(); if (!plac.equals(lect.getAssignment())) lect.assign(0,plac); } } } public Suggestion tryAssignment(Hint hint) { return tryAssignment(hint.getPlacement(iModel)); } public Suggestion tryAssignment(Placement placement) { Suggestion ret = null; synchronized (iSolver.currentSolution()) { Vector unAssignedVariables = new Vector(iModel.unassignedVariables()); Hashtable initialAssignments = new Hashtable(); for (Lecture lec: iModel.assignedVariables()) { initialAssignments.put(lec,lec.getAssignment()); } Hashtable conflictsToResolve = new Hashtable(); Vector resolvedLectures = new Vector(); if (iHints!=null) { for (Enumeration e=iHints.elements();e.hasMoreElements();) { Placement plac = (Placement)e.nextElement(); Lecture lect = (Lecture)plac.variable(); if (placement!=null && placement.variable().equals(lect)) continue; Set conflicts = iModel.conflictValues(plac); if (conflicts.contains(plac)) return null; for (Iterator i=conflicts.iterator();i.hasNext();) { Placement conflictPlacement = (Placement)i.next(); conflictsToResolve.put(conflictPlacement.variable(),conflictPlacement); conflictPlacement.variable().unassign(0); } resolvedLectures.add(lect.getClassId()); conflictsToResolve.remove(lect); lect.assign(0,plac); } } if (placement!=null) { Lecture lect = (Lecture)placement.variable(); Set conflicts = iModel.conflictValues(placement); if (conflicts.contains(placement)) return null; for (Iterator i=conflicts.iterator();i.hasNext();) { Placement conflictPlacement = (Placement)i.next(); conflictsToResolve.put(conflictPlacement.variable(),conflictPlacement); conflictPlacement.variable().unassign(0); } resolvedLectures.add(lect.getClassId()); conflictsToResolve.remove(lect); lect.assign(0,placement); } ret = new Suggestion(iSolver, initialAssignments, resolvedLectures, conflictsToResolve.values()); if (placement!=null) ret.setHint(new Hint(iSolver, placement)); if (iHints!=null) { for (Enumeration e=iHints.elements();e.hasMoreElements();) { Placement plac = (Placement)e.nextElement(); Lecture lect = (Lecture)plac.variable(); if (lect.getAssignment()!=null) lect.unassign(0); } } for (Enumeration e=unAssignedVariables.elements();e.hasMoreElements();) { Lecture lect = (Lecture)e.nextElement(); if (lect.getAssignment()!=null) lect.unassign(0); } if (placement!=null) placement.variable().unassign(0); for (Iterator i=initialAssignments.values().iterator();i.hasNext();) { Placement plac = (Placement)i.next(); Lecture lect = (Lecture)plac.variable(); if (!plac.equals(lect.getAssignment())) lect.assign(0,plac); } } return ret; } public Suggestion currentSuggestion() { return iCurrentSuggestion; } public Suggestion emptySuggestion() { return iEmptySuggestion; } private TreeSet<PlacementValue> values(Lecture lecture) { TreeSet<PlacementValue> vals = new TreeSet(); if (lecture.equals(iLecture)) { for (Placement p: (lecture.allowBreakHard() || !iAllowBreakHard?lecture.values():lecture.computeValues(true))) { if (match(p)) vals.add(new PlacementValue(p)); } } else { if (lecture.allowBreakHard() || !iAllowBreakHard) { for (Placement x: lecture.values()) { vals.add(new PlacementValue(x)); } } else { for (Placement x: lecture.computeValues(true)) { vals.add(new PlacementValue(x)); } } } return vals; } public boolean containsCommited(TimetableModel model, Collection values) { if (model.hasConstantVariables()) { for (Iterator i=values.iterator();i.hasNext();) { Placement placement = (Placement)i.next(); Lecture lecture = (Lecture)placement.variable(); if (lecture.isCommitted()) return true; } } return false; } private void backtrack(long startTime, Vector initialLectures, Vector resolvedLectures, Hashtable conflictsToResolve, Hashtable initialAssignments, int depth) { iNrCombinationsConsidered++; int nrUnassigned = conflictsToResolve.size(); if ((initialLectures==null || initialLectures.isEmpty()) && nrUnassigned==0) { if (iSuggestions.size()==iLimit) { if (((Suggestion)iSuggestions.last()).isBetter(iSolver)) return; } iSuggestions.add(new Suggestion(iSolver,initialAssignments,resolvedLectures, conflictsToResolve.values())); iNrSolutions++; if (iSuggestions.size()>iLimit) iSuggestions.remove(iSuggestions.last()); return; } if (depth<=0) return; if (iTimeOut>0 && System.currentTimeMillis()-startTime>iTimeOut) { iTimeoutReached = true; return; } if (iSuggestions.size()==iLimit && ((Suggestion)iSuggestions.last()).getValue()<getBound(conflictsToResolve)) { return; //BOUND } for (Enumeration e1=(initialLectures!=null && !initialLectures.isEmpty()?initialLectures.elements():conflictsToResolve.keys());e1.hasMoreElements();) { Lecture lecture = (Lecture)e1.nextElement(); if (resolvedLectures.contains(lecture.getClassId())) continue; resolvedLectures.add(lecture.getClassId()); for (Iterator e2=values(lecture).iterator();e2.hasNext();) { PlacementValue placementValue = (PlacementValue)e2.next(); Placement placement = placementValue.getPlacement(); if (placement.equals(lecture.getAssignment())) continue; if (!iAllowBreakHard && placement.isHard()) continue; if (iSameTime && lecture.getAssignment()!=null && !placement.getTimeLocation().equals(((Placement)lecture.getAssignment()).getTimeLocation())) continue; if (iSameRoom && lecture.getAssignment()!=null && !placement.sameRooms((Placement)lecture.getAssignment())) continue; if (iAllTheSame && iSameTime && lecture.getAssignment()==null) { Placement ini = (Placement)initialAssignments.get(lecture); if (ini!=null && !placement.sameTime(ini)) continue; } if (iAllTheSame && iSameRoom && lecture.getAssignment()==null) { Placement ini = (Placement)initialAssignments.get(lecture); if (ini!=null && !placement.sameRooms(ini)) continue; } Set conflicts = iModel.conflictValues(placement); if (conflicts!=null && (nrUnassigned+conflicts.size()>depth)) continue; if (containsCommited(iModel, conflicts)) continue; if (conflicts.contains(placement)) continue; boolean containException = false; if (conflicts!=null) { for (Iterator i=conflicts.iterator();!containException && i.hasNext();) { Placement c = (Placement)i.next(); if (resolvedLectures.contains(((Lecture)c.variable()).getClassId())) containException = true; } } if (containException) continue; Placement cur = (Placement)lecture.getAssignment(); if (conflicts!=null) { for (Iterator i=conflicts.iterator();!containException && i.hasNext();) { Placement c = (Placement)i.next(); c.variable().unassign(0); } } lecture.assign(0, placement); for (Iterator i=conflicts.iterator();!containException && i.hasNext();) { Placement c = (Placement)i.next(); conflictsToResolve.put(c.variable(),c); } Placement resolvedConf = (Placement)conflictsToResolve.remove(lecture); backtrack(startTime, null, resolvedLectures, conflictsToResolve, initialAssignments, depth-1); if (cur==null) lecture.unassign(0); else lecture.assign(0, cur); if (conflicts!=null) { for (Iterator i=conflicts.iterator();i.hasNext();) { Placement p = (Placement)i.next(); p.variable().assign(0, p); conflictsToResolve.remove(p.variable()); } } if (resolvedConf!=null) conflictsToResolve.put(lecture, resolvedConf); } resolvedLectures.remove(lecture.getClassId()); } } public boolean getTimeoutReached() { return iTimeoutReached; } public long getNrCombinationsConsidered() { return iNrCombinationsConsidered; } public long getNrSolutions() { return iNrSolutions; } public void computeConfTable() { iConfTable = new Vector(); for (TimeLocation t: iLecture.timeLocations()) { if (!iAllowBreakHard && PreferenceLevel.sProhibited.equals(PreferenceLevel.int2prolog(t.getPreference()))) continue; if (t.getPreference()>500) continue; iConfTable.add(new Suggestion(iSolver,iLecture,t)); } } public void computeTryAllAssignments() { iAllAssignments = new TreeSet(); for (Placement p: iLecture.values()) { if (p.equals(iLecture.getAssignment())) continue; if (p.isHard() && !iAllowBreakHard) continue; if (!match(p)) continue; if (iSameTime && iLecture.getAssignment()!=null && !p.getTimeLocation().equals(((Placement)iLecture.getAssignment()).getTimeLocation())) continue; if (iSameRoom && iLecture.getAssignment()!=null && !p.sameRooms((Placement)iLecture.getAssignment())) continue; if (iAllAssignments.size()==iLimit && ((Suggestion)iAllAssignments.last()).isBetter(iSolver)) continue; Suggestion s = tryAssignment(p); if (s != null) iAllAssignments.add(s); if (iAllAssignments.size()>iLimit) iAllAssignments.remove(iAllAssignments.last()); } } public TreeSet tryAllAssignments() { return iAllAssignments; } public int getNrTries() { return iNrTries; } public Vector getConfTable() { return iConfTable; } public void computeNrTries() { Placement placement = (Placement)iLecture.getAssignment(); if (iSameTime && placement!=null) iNrTries = iLecture.nrValues(placement.getTimeLocation())-1; else if (iSameRoom && placement!=null) { if (placement.isMultiRoom()) { iNrTries = iLecture.nrValues(placement.getRoomLocations())-1; } else { iNrTries = iLecture.nrValues(placement.getRoomLocation())-1; } } else iNrTries = iLecture.nrValues()-(placement==null?0:1); } public String toString() { return "Suggestions{\n"+ " suggestions = "+getSuggestions()+"\n"+ " timeoutReached = "+getTimeoutReached()+"\n"+ " nrCombinationsConsidered = "+getNrCombinationsConsidered()+"\n"+ " nrSolutions = "+getNrSolutions()+"\n"+ " currentSuggestion = "+currentSuggestion()+"\n"+ " tryAssignments = "+tryAllAssignments()+"\n"+ " nrTries = "+getNrTries()+"\n"+ " emptySuggestion = "+emptySuggestion()+"\n"+ " hints = "+getHints()+"\n"+ " confTable = "+getConfTable()+"\n"+ "}"; } public double getBound(Hashtable conflictsToResolve) { TimetableComparator cmp = (TimetableComparator)iSolver.getSolutionComparator(); double value = cmp.currentValue(iSolver.currentSolution()); for (Enumeration e=conflictsToResolve.keys();e.hasMoreElements();) { Lecture lect = (Lecture)e.nextElement(); PlacementValue val = values(lect).first(); value += val.getValue(); } return value; } public class PlacementValue implements Comparable<PlacementValue> { private Placement iPlacement; private double iValue; public PlacementValue(Placement placement) { iPlacement = placement; iValue = ((TimetableComparator)iSolver.getSolutionComparator()).value(placement, iSolver.getPerturbationsCounter()); } public Placement getPlacement() { return iPlacement; } public double getValue() { return iValue; } public int compareTo(PlacementValue p) { int cmp = Double.compare(getValue(), p.getValue()); if (cmp!=0) return cmp; return Double.compare(getPlacement().getId(), p.getPlacement().getId()); } } }
package info.justaway; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Build; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.lang.Thread.UncaughtExceptionHandler; public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler { private static final String BUG_FILE = "BUG"; private static final String MAIL_TO = "mailto:s.aska.org@gmail.com,teshi04@gmail.com"; private static Context sContext; private static PackageInfo sPackageInfo; private static ActivityManager.MemoryInfo sMemoryInfo = new ActivityManager.MemoryInfo(); private UncaughtExceptionHandler mDefaultUEH; @SuppressWarnings("ConstantConditions") public MyUncaughtExceptionHandler(Context context) { sContext = context; try { sPackageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); } mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } public void uncaughtException(Thread th, Throwable t) { saveState(t); mDefaultUEH.uncaughtException(th, t); } private void saveState(Throwable error) { try { PrintWriter writer = new PrintWriter(sContext.openFileOutput(BUG_FILE, Context.MODE_PRIVATE)); if (sPackageInfo != null) { writer.printf("[BUG][%s] versionName:%s, versionCode:%d\n", sPackageInfo.packageName, sPackageInfo.versionName, sPackageInfo.versionCode); } else { writer.printf("[BUG][Unknown]\n"); } try { writer .printf("Runtime Memory: total: %dKB, free: %dKB, used: %dKB\n", Runtime .getRuntime().totalMemory() / 1024, Runtime.getRuntime().freeMemory() / 1024, (Runtime.getRuntime() .totalMemory() - Runtime.getRuntime().freeMemory()) / 1024); } catch (Exception e) { e.printStackTrace(); } try { ((ActivityManager) sContext.getSystemService(Context.ACTIVITY_SERVICE)) .getMemoryInfo(sMemoryInfo); writer.printf("availMem: %dKB, lowMemory: %b\n", sMemoryInfo.availMem / 1024, sMemoryInfo.lowMemory); } catch (Exception e) { e.printStackTrace(); } writer.printf("DEVICE: %s\n", Build.DEVICE); writer.printf("MODEL: %s\n", Build.MODEL); writer.printf("VERSION.SDK: %s\n", Build.VERSION.SDK_INT); writer.println(""); error.printStackTrace(writer); writer.close(); } catch (Exception e) { e.printStackTrace(); } } public static void showBugReportDialogIfExist(final Activity activity) { File bugFile = activity.getFileStreamPath(BUG_FILE); if (!bugFile.exists()) return; File writeFile = activity.getFileStreamPath(BUG_FILE + ".txt"); boolean result = bugFile.renameTo(writeFile); if (!result) { return; } final StringBuilder body = new StringBuilder(); String firstLine = null; try { BufferedReader br = new BufferedReader(new FileReader(writeFile)); String line; while ((line = br.readLine()) != null) { if (firstLine == null) { firstLine = line; } else { body.append(line).append("\n"); } } br.close(); } catch (Exception e) { e.printStackTrace(); } final String subject = firstLine; new AlertDialog.Builder(activity).setTitle("").setMessage("") .setPositiveButton("", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { activity.startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(MAIL_TO)) .putExtra(Intent.EXTRA_SUBJECT, subject).putExtra(Intent.EXTRA_TEXT, body.toString())); } }).setNegativeButton("", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); } }
package com.parrit.controllers; import com.parrit.entities.Workspace; import com.parrit.repositories.WorkspaceRepository; import com.parrit.services.PairingHistoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class WorkspaceController { private WorkspaceRepository workspaceRepository; private PairingHistoryService pairingHistoryService; @Autowired public WorkspaceController(WorkspaceRepository workspaceRepository, PairingHistoryService pairingHistoryService) { this.workspaceRepository = workspaceRepository; this.pairingHistoryService = pairingHistoryService; } // // // @RequestMapping(path = "/", method = RequestMethod.GET) public String getWorkspaceNames(Model model) { model.addAttribute("workspaceNames", workspaceRepository.getAllWorkspaceNames()); return "dashboard"; } @RequestMapping(path = "/{workspaceName:.+}", method = RequestMethod.GET) public String getWorkspace(@PathVariable String workspaceName, Model model) { Workspace workspace = workspaceRepository.findByName(workspaceName); model.addAttribute("workspace", workspace); return "workspace"; } // // // @RequestMapping(path = "/api/workspace", method = RequestMethod.POST, consumes = {"application/json"}) @ResponseBody public ResponseEntity<Workspace> saveWorkspace(@RequestBody Workspace workspace) { return new ResponseEntity<>(workspaceRepository.save(workspace), HttpStatus.OK); } @RequestMapping(path = "/api/workspace/new", method = RequestMethod.POST, consumes = {"application/json"}) @ResponseBody public ResponseEntity<List<String>> createWorkspace(@RequestBody String name) { Workspace workspace = new Workspace(); workspace.setName(name); workspaceRepository.save(workspace); return new ResponseEntity<>(workspaceRepository.getAllWorkspaceNames(), HttpStatus.OK); } @RequestMapping(path = "/api/workspace/pairing", method = RequestMethod.POST, consumes = {"application/json"}) @ResponseBody public void savePairing(@RequestBody Workspace workspace) { pairingHistoryService.savePairing(workspace); } @RequestMapping(path = "/api/workspace/delete/{id}", method = RequestMethod.POST, consumes = {"application/json"}) @ResponseBody public void delete(@PathVariable long id) { workspaceRepository.delete(id); } }
package com.programmaticallyspeaking.tinyws; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class Server { public static final String ServerName = "TinyWS Server"; public static final String ServerVersion = "0.0.1"; //TODO: Get from resource private static final String HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final int SupportedVersion = 13; private final Executor mainExecutor; private final Executor handlerExecutor; private final Options options; private final Logger logger; private ServerSocket serverSocket; private Map<String, WebSocketHandler> handlers = new HashMap<>(); public Server(Executor mainExecutor, Executor handlerExecutor, Options options) { this.mainExecutor = mainExecutor; this.handlerExecutor = handlerExecutor; this.options = options; this.logger = new Logger() { public void log(LogLevel level, String message, Throwable error) { if (isEnabledAt(level)) { try { options.logger.log(level, message, error); } catch (Exception ignore) { // ignore logging errors } } } @Override public boolean isEnabledAt(LogLevel level) { return options.logger != null && options.logger.isEnabledAt(level); } }; } public void addHandler(String endpoint, WebSocketHandler handler) { if (serverSocket != null) throw new IllegalStateException("Please add handlers before starting the server."); handlers.put(endpoint, handler); } public void start() throws IOException { Integer backlog = options.backlog; serverSocket = backlog == null ? new ServerSocket(options.port) : new ServerSocket(options.port, backlog); mainExecutor.execute(this::acceptInLoop); } public void stop() { if (serverSocket == null) return; try { serverSocket.close(); } catch (IOException e) { logger.log(LogLevel.WARN, "Failed to close server socket.", e); } serverSocket = null; } private void acceptInLoop() { try { if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, "Receiving WebSocket clients at " + serverSocket.getLocalSocketAddress(), null); while (true) { Socket clientSocket = serverSocket.accept(); BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> wrappedHandlerExecutor = (handler, fun) -> { if (handler != null) handlerExecutor.execute(() -> fun.accept(handler)); }; mainExecutor.execute(new ClientHandler(clientSocket, handlers::get, wrappedHandlerExecutor, logger)); } } catch (SocketException e) { logger.log(LogLevel.DEBUG, "Server socket was closed, probably because the server was stopped.", e); } catch (Exception ex) { logger.log(LogLevel.ERROR, "Error accepting a client socket.", ex); } } private static class ClientHandler implements Runnable { private final Socket clientSocket; private final OutputStream out; private final InputStream in; private final Function<String, WebSocketHandler> handlerLookup; private final BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor; private final Logger logger; private final PayloadCoder payloadCoder; private final FrameWriter frameWriter; private WebSocketHandler handler; private volatile boolean isClosed; // potentially set from handler thread ClientHandler(Socket clientSocket, Function<String, WebSocketHandler> handlerLookup, BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor, Logger logger) throws IOException { this.clientSocket = clientSocket; out = clientSocket.getOutputStream(); in = clientSocket.getInputStream(); this.handlerLookup = handlerLookup; this.handlerExecutor = handlerExecutor; this.logger = logger; payloadCoder = new PayloadCoder(); frameWriter = new FrameWriter(out, payloadCoder); } @Override public void run() { try { communicate(); } catch (WebSocketError ex) { if (logger.isEnabledAt(LogLevel.DEBUG)) { String msg = String.format("Closing with code %d (%s)%s", ex.code, ex.reason, ex.debugDetails != null ? (" because: " + ex.debugDetails) : ""); logger.log(LogLevel.DEBUG, msg, null); } doIgnoringExceptions(() -> frameWriter.writeCloseFrame(ex.code, ex.reason)); handlerExecutor.accept(handler, h -> h.onClosedByClient(ex.code, ex.reason)); } catch (IllegalArgumentException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s sent a malformed request.", clientSocket.getRemoteSocketAddress()), null); sendBadRequestResponse(); } catch (FileNotFoundException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s requested an unknown endpoint.", clientSocket.getRemoteSocketAddress()), null); sendNotFoundResponse(); } catch (SocketException ex) { if (!isClosed) { logger.log(LogLevel.ERROR, "Client socket error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } } catch (Exception ex) { logger.log(LogLevel.ERROR, "Client communication error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } abort(); } private void abort() { if (isClosed) return; doIgnoringExceptions(clientSocket::close); isClosed = true; } private void communicate() throws IOException, NoSuchAlgorithmException { Headers headers = Headers.read(in); if (!headers.isProperUpgrade()) throw new IllegalArgumentException("Handshake has malformed upgrade."); if (headers.version() != SupportedVersion) throw new IllegalArgumentException("Bad version, must be: " + SupportedVersion); String endpoint = headers.endpoint; if (endpoint == null) throw new IllegalArgumentException("Missing endpoint."); handler = handlerLookup.apply(endpoint); if (handler == null) throw new FileNotFoundException("Unknown endpoint: " + endpoint); if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, String.format("New WebSocket client from %s at endpoint '%s'.", clientSocket.getRemoteSocketAddress(), endpoint), null); handlerExecutor.accept(handler, h -> h.onOpened(new WebSocketClientImpl(frameWriter, this::abort))); String key = headers.key(); String responseKey = createResponseKey(key); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, String.format("Opening handshake key is '%s', sending response key '%s'.", key, responseKey), null); sendHandshakeResponse(responseKey); List<Frame> frameBatch = new ArrayList<>(); while (true) { frameBatch.add(Frame.read(in)); handleBatch(frameBatch); } } private void handleBatch(List<Frame> frameBatch) throws IOException { Frame firstFrame = frameBatch.get(0); if (firstFrame.opCode == 0) throw WebSocketError.protocolError("Continuation frame with nothing to continue."); Frame lastOne = frameBatch.get(frameBatch.size() - 1); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, lastOne.toString(), null); if (!lastOne.isFin) return; if (firstFrame != lastOne) { if (lastOne.isControl()) { // Interleaved control frame frameBatch.remove(frameBatch.size() - 1); handleResultFrame(lastOne); return; } else if (lastOne.opCode > 0) { throw WebSocketError.protocolError("Continuation frame must have opcode 0."); } } Frame result; if (frameBatch.size() > 1) { // Combine payloads! int totalLength = frameBatch.stream().mapToInt(f -> f.payloadData.length).sum(); byte[] allTheData = new byte[totalLength]; int offs = 0; for (Frame frame : frameBatch) { System.arraycopy(frame.payloadData, 0, allTheData, offs, frame.payloadData.length); offs += frame.payloadData.length; } result = new Frame(firstFrame.opCode, allTheData, true); } else result = lastOne; frameBatch.clear(); handleResultFrame(result); } private void handleResultFrame(Frame result) throws IOException { switch (result.opCode) { case 1: String data = payloadCoder.decode(result.payloadData); handlerExecutor.accept(handler, h -> h.onTextMessage(data)); break; case 2: handlerExecutor.accept(handler, h -> h.onBinaryData(result.payloadData)); break; case 8: CloseData cd = result.toCloseData(payloadCoder); if (cd.hasInvalidCode()) throw WebSocketError.protocolError("Invalid close frame code: " + cd.code); // 1000 is normal close int i = cd.code != null ? cd.code : 1000; throw new WebSocketError(i, "", null); case 9: // Ping, send pong! logger.log(LogLevel.TRACE, "Got ping frame, sending pong.", null); frameWriter.writePongFrame(result.payloadData); break; case 10: // Pong is ignored logger.log(LogLevel.TRACE, "Ignoring unsolicited pong frame.", null); break; default: throw WebSocketError.protocolError("Invalid opcode: " + result.opCode); } } private void outputLine(PrintWriter writer, String data) { System.out.println("> " + data); writer.print(data); writer.print("\r\n"); } private void sendHandshakeResponse(String responseKey) { Map<String, String> headers = new HashMap<String, String>() {{ put("Upgrade", "websocket"); put("Connection", "upgrade"); put("Sec-WebSocket-Accept", responseKey); }}; sendResponse(101, "Switching Protocols", headers); } private void sendBadRequestResponse() { // Advertise supported version regardless of what was bad. A bit lazy, but simple. Map<String, String> headers = new HashMap<String, String>() {{ put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); }}; sendResponse(400, "Bad Request", headers); } private void sendNotFoundResponse() { sendResponse(404, "Not Found", Collections.emptyMap()); } private void sendResponse(int statusCode, String reason, Map<String, String> headers) { PrintWriter writer = new PrintWriter(out, false); outputLine(writer, "HTTP/1.1 " + statusCode + " " + reason); for (Map.Entry<String, String> entry : headers.entrySet()) { outputLine(writer, entry.getKey() + ": " + entry.getValue()); } // https://tools.ietf.org/html/rfc7231#section-7.4.2 outputLine(writer, String.format("Server: %s %s", ServerName, ServerVersion)); // Headers added when we don't do a connection upgrade to WebSocket! if (statusCode >= 200) { // https://tools.ietf.org/html/rfc7230#section-6.1 outputLine(writer, "Connection: close"); // https://tools.ietf.org/html/rfc7230#section-3.3.2 outputLine(writer, "Content-Length: 0"); } outputLine(writer, ""); writer.flush(); // Note: Do NOT close the writer, as the stream must remain open } } private static class Frame { final int opCode; final byte[] payloadData; final boolean isFin; public String toString() { return String.format("Frame[opcode=%d, control=%b, payload length=%d, fragmented=%b]", opCode, isControl(), payloadData.length, !isFin); } boolean isControl() { return (opCode & 8) == 8; } private Frame(int opCode, byte[] payloadData, boolean isFin) { this.opCode = opCode; this.payloadData = payloadData; this.isFin = isFin; } private static int readUnsignedByte(InputStream in) throws IOException { int b = in.read(); if (b < 0) throw new IOException("End of stream"); return b; } private static int toUnsigned(byte b) { int result = b; if (result < 0) result += 256; return result; } private static byte[] readBytes(InputStream in, int len) throws IOException { byte[] buf = new byte[len]; int totalRead = 0; int offs = 0; while (totalRead < len) { int readLen = in.read(buf, offs, len - offs); if (readLen < 0) break; totalRead += readLen; offs += readLen; } if (totalRead != len) throw new IOException("Expected to read " + len + " bytes but read " + totalRead); return buf; } private static long toLong(byte[] data, int offset, int len) { long result = 0; for (int i = offset, j = offset + len; i < j; i++) { result = (result << 8) + toUnsigned(data[i]); } return result; } private static long toLong(byte[] data) { return toLong(data, 0, data.length); } static Frame read(InputStream in) throws IOException { int firstByte = readUnsignedByte(in); boolean isFin = (firstByte & 128) == 128; boolean hasZeroReserved = (firstByte & 112) == 0; if (!hasZeroReserved) throw WebSocketError.protocolError("Non-zero reserved bits in 1st byte: " + (firstByte & 112)); int opCode = (firstByte & 15); boolean isControlFrame = (opCode & 8) == 8; int secondByte = readUnsignedByte(in); boolean isMasked = (secondByte & 128) == 128; int len = (secondByte & 127); if (isControlFrame) { if (len > 125) throw WebSocketError.protocolError("Control frame length exceeding 125 bytes."); if (!isFin) throw WebSocketError.protocolError("Fragmented control frame."); } if (len == 126) { // 2 bytes of extended len long tmp = toLong(readBytes(in, 2)); len = (int) tmp; } else if (len == 127) { // 8 bytes of extended len long tmp = toLong(readBytes(in, 8)); if (tmp > Integer.MAX_VALUE) throw WebSocketError.protocolError("Frame length greater than 0x7fffffff not supported."); len = (int) tmp; } byte[] maskingKey = isMasked ? readBytes(in, 4) : null; byte[] payloadData = unmaskIfNeededInPlace(readBytes(in, len), maskingKey); return new Frame(opCode, payloadData, isFin); } private static byte[] unmaskIfNeededInPlace(byte[] bytes, byte[] maskingKey) { if (maskingKey != null) { for (int i = 0; i < bytes.length; i++) { int j = i % 4; bytes[i] = (byte) (bytes[i] ^ maskingKey[j]); } } return bytes; } CloseData toCloseData(PayloadCoder payloadCoder) throws WebSocketError { if (opCode != 8) throw new IllegalStateException("Not a close frame: " + opCode); if (payloadData.length == 0) return new CloseData(null, null); if (payloadData.length == 1) throw WebSocketError.protocolError("Invalid close frame payload length (1)."); int code = (int) toLong(payloadData, 0, 2); String reason = payloadData.length > 2 ? payloadCoder.decode(payloadData, 2, payloadData.length - 2) : null; return new CloseData(code, reason); } } private static class CloseData { private final Integer code; private final String reason; CloseData(Integer code, String reason) { this.code = code; this.reason = reason; } boolean hasInvalidCode() { if (code == null) return false; // no code isn't invalid if (code < 1000 || code >= 5000) return true; if (code >= 3000) return false; // 3000-3999 and 4000-4999 are valid return code == 1004 || code == 1005 || code == 1006 || code > 1011; } } static class Headers { private final Map<String, String> headers; final String endpoint; private Headers(Map<String, String> headers, String endpoint) { this.headers = headers; this.endpoint = endpoint; } boolean isProperUpgrade() { return "websocket".equalsIgnoreCase(headers.get("Upgrade")) && "Upgrade".equalsIgnoreCase(headers.get("Connection")); } int version() { String versionStr = headers.get("Sec-WebSocket-Version"); try { return Integer.parseInt(versionStr); } catch (Exception ignore) { return 0; } } String key() { String key = headers.get("Sec-WebSocket-Key"); if (key == null) throw new IllegalArgumentException("Missing Sec-WebSocket-Key in handshake."); return key; } static Headers read(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String inputLine, endpoint = null; Map<String, String> headers = new HashMap<>(); while (!"".equals((inputLine = reader.readLine()))) { if (inputLine.startsWith("GET ")) { String[] parts = inputLine.split(" ", 3); if (parts.length != 3) throw new IOException("Unexpected GET line: " + inputLine); endpoint = parts[1]; } String[] keyValue = inputLine.split(":", 2); if (keyValue.length != 2) continue; System.out.println("< " + inputLine); headers.put(keyValue[0], keyValue[1].trim()); } // Note: Do NOT close the reader, because the stream must remain open! return new Headers(headers, endpoint); } } static class PayloadCoder { private final Charset charset = StandardCharsets.UTF_8; private final CharsetDecoder decoder = charset.newDecoder(); String decode(byte[] bytes) throws WebSocketError { return decode(bytes, 0, bytes.length); } /** * Decodes the given byte data as UTF-8 and returns the result as a string. * * @param bytes the byte array * @param offset offset into the array where to start decoding * @param len length of data to decode * @return the decoded string * @throws WebSocketError (1007) thrown if the data are not valid UTF-8 */ synchronized String decode(byte[] bytes, int offset, int len) throws WebSocketError { decoder.reset(); try { CharBuffer buf = decoder.decode(ByteBuffer.wrap(bytes, offset, len)); return buf.toString(); } catch (Exception ex) { throw WebSocketError.invalidFramePayloadData(); } } byte[] encode(String s) { return s.getBytes(charset); } } static class WebSocketError extends IOException { final int code; final String reason; final String debugDetails; WebSocketError(int code, String reason, String debugDetails) { this.code = code; this.reason = reason; this.debugDetails = debugDetails; } static WebSocketError protocolError(String debugDetails) { return new WebSocketError(1002, "Protocol error", debugDetails); } static WebSocketError invalidFramePayloadData() { return new WebSocketError(1007, "Invalid frame payload data", null); } } static class FrameWriter { private final OutputStream out; private final PayloadCoder payloadCoder; FrameWriter(OutputStream out, PayloadCoder payloadCoder) { this.out = out; this.payloadCoder = payloadCoder; } void writeCloseFrame(int code, String reason) throws IOException { byte[] s = payloadCoder.encode(reason); byte[] numBytes = numberToBytes(code, 2); byte[] combined = new byte[numBytes.length + s.length]; System.arraycopy(numBytes, 0, combined, 0, 2); System.arraycopy(s, 0, combined, 2, s.length); writeFrame(8, combined); } void writeTextFrame(String text) throws IOException { byte[] s = payloadCoder.encode(text); writeFrame(1, s); } void writeBinaryFrame(byte[] data) throws IOException { writeFrame(2, data); } void writePongFrame(byte[] data) throws IOException { writeFrame(10, data); } /** * Writes a frame to the output stream. Since FrameWriter is handed out to potentially different threads, * this method is synchronized. * * @param opCode the opcode of the frame * @param data frame data * @throws IOException thrown if writing to the socket fails */ synchronized void writeFrame(int opCode, byte[] data) throws IOException { int firstByte = 128 | opCode; // FIN + opCode int dataLen = data.length; int secondByte; int extraLengthBytes = 0; if (dataLen < 126) { secondByte = dataLen; // no masking } else if (dataLen < 65536) { secondByte = 126; extraLengthBytes = 2; } else { secondByte = 127; extraLengthBytes = 8; } out.write(firstByte); out.write(secondByte); if (extraLengthBytes > 0) { out.write(numberToBytes(data.length, extraLengthBytes)); } out.write(data); out.flush(); } } private static class WebSocketClientImpl implements WebSocketClient { private final FrameWriter writer; private final Runnable closeCallback; WebSocketClientImpl(FrameWriter writer, Runnable closeCallback) { this.writer = writer; this.closeCallback = closeCallback; } public void close(int code, String reason) throws IOException { writer.writeCloseFrame(code, reason); closeCallback.run(); } public void sendTextMessage(String text) throws IOException { writer.writeTextFrame(text); } public void sendBinaryData(byte[] data) throws IOException { writer.writeBinaryFrame(data); } } static byte[] numberToBytes(int number, int len) { byte[] array = new byte[len]; // Start from the end (network byte order), assume array is filled with zeros. for (int i = len - 1; i >= 0; i array[i] = (byte) (number & 0xff); number = number >> 8; } return array; } static String createResponseKey(String key) throws NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] rawBytes = (key + HANDSHAKE_GUID).getBytes(); byte[] result = sha1.digest(rawBytes); return Base64.getEncoder().encodeToString(result); } private static void doIgnoringExceptions(RunnableThatThrows runnable) { try { runnable.run(); } catch (Exception ex) { // ignore } } private interface RunnableThatThrows { void run() throws Exception; } public static class Options { Integer backlog; int port; Logger logger; private Options(int port) { this.port = port; } public static Options withPort(int port) { return new Options(port); } public Options withBacklog(int backlog) { if (backlog < 0) throw new IllegalArgumentException("Backlog must be >= 0"); this.backlog = backlog; return this; } public Options withLogger(Logger logger) { this.logger = logger; return this; } } public enum LogLevel { TRACE(0), DEBUG(10), INFO(20), WARN(50), ERROR(100); public final int level; LogLevel(int level) { this.level = level; } } public interface Logger { void log(LogLevel level, String message, Throwable error); boolean isEnabledAt(LogLevel level); } public interface WebSocketClient { void close(int code, String reason) throws IOException; void sendTextMessage(String text) throws IOException; void sendBinaryData(byte[] data) throws IOException; // TODO: Get user-agent, query string params } public interface WebSocketHandler { void onOpened(WebSocketClient client); void onClosedByClient(int code, String reason); void onFailure(Throwable t); void onTextMessage(String text); void onBinaryData(byte[] data); } }
package com.semantico.rigel.filters; import java.util.Collection; import org.apache.solr.common.SolrDocument; import com.google.common.collect.ImmutableClassToInstanceMap; import com.semantico.rigel.FieldDataSource; import com.semantico.rigel.SolrDocDataSource; import com.semantico.rigel.fields.Field; import com.semantico.rigel.fields.MultivaluedFieldAdaptable; import com.semantico.rigel.fields.MultivaluedFieldAdaptor; import static com.google.common.base.Preconditions.*; public abstract class FieldBasedTerm<T> extends BasicTerm { protected final Field<T> field; public FieldBasedTerm(Field<T> field) { checkNotNull(field); this.field = field; } /* * Handles getting the value out of the solr doc and deals with multivalued fields, * subclasses implement the decide function */ @Override public boolean apply(SolrDocument doc) { if (field instanceof MultivaluedFieldAdaptable) { Collection<T> actuals = getFieldValue(new MultivaluedFieldAdaptor<T>((MultivaluedFieldAdaptable<T>)field), doc); if (actuals == null) { return false; } for (T actual : actuals) { if (decide(actual)) { return true; } } return false; } else { T actual = getFieldValue(field, doc); if (actual == null) { return false; } return decide(actual); } } protected abstract boolean decide(T actual); /** * Helper method to wrap the solr doc up in a context & get the value using the field */ private <R> R getFieldValue(Field<R> field, SolrDocument doc) { ImmutableClassToInstanceMap.Builder<FieldDataSource<?>> context = ImmutableClassToInstanceMap.builder(); context.put(SolrDocDataSource.class, new SolrDocDataSource(doc)); return field.getValue(context.build()); } }
package com.speed.ob.transforms; import com.speed.ob.Config; import com.speed.ob.api.ClassStore; import com.speed.ob.api.ObfuscatorTransform; import com.speed.ob.util.NameGenerator; import jdk.internal.org.objectweb.asm.Opcodes; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.RemappingClassAdapter; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class ClassNameTransform extends ObfuscatorTransform implements Opcodes { private Map<String, String> namesMap = new HashMap<>(); private NameGenerator nameGenerator = new NameGenerator(); private boolean excludeMains; private List<String> excludedClasses; private boolean keepPackages; class ClassRemapper extends Remapper { @Override public String map(String type) { LOGGER.finest("To remap: " + type + " or not to"); if (!namesMap.containsKey(type)) { return type; } String newName = namesMap.get(type); LOGGER.finest("Remapping: " + type + " to " + newName); return newName; } } public ClassNameTransform(Config config) { super(config); excludeMains = config.getBoolean("ClassNameTransform.exclude_mains"); LOGGER.finer("Exclude mains: " + excludeMains); excludedClasses = config.getList("ClassNameTransform.excludes"); LOGGER.finer("Excluding " + excludedClasses.size() + " classes"); keepPackages = config.getBoolean("ClassNameTransform.keep_packages"); LOGGER.finer("Keeping packages:" + keepPackages); } public void fixMethodAccess(ClassStore store) { for (ClassNode node : store.nodes()) { if (excludedClasses.contains(node.name)) { continue; } if ((node.access & ACC_PUBLIC) == 0) { node.access |= ACC_PUBLIC; } for (MethodNode mn : (List<MethodNode>) node.methods) { if ((mn.access & ACC_PUBLIC) == 0) { mn.access |= ACC_PUBLIC; } } } } public void run(ClassStore store, Config config) { //generate map of old names -> new names outer: for (ClassNode node : store.nodes()) { LOGGER.fine("Processing class: " + node.name); boolean hasMain = false; if (excludeMains) { for (MethodNode mn : (List<MethodNode>) node.methods) { if (mn.name.equals("main") && mn.desc.equals("([Ljava/lang/String;)V")) { LOGGER.fine("Not renaming " + node.name + ", has a main method"); //continue outer; hasMain = true; break; } } } if (excludedClasses != null && excludedClasses.contains(node.name)) { LOGGER.fine("Not renaming " + node.name + ", is excluded"); continue; } String newName; int ind = node.name.lastIndexOf('/'); if (excludeMains && hasMain) { if (ind > -1) { newName = node.name.substring(ind + 1); } else { newName = node.name; } } else { if (keepPackages && ind > -1) { newName = node.name.substring(0, ind) + '/' + nameGenerator.next(); } else { newName = nameGenerator.next(); } } LOGGER.finer("Renaming " + node.name + " to " + newName); namesMap.put(node.name, newName); } Iterator<ClassNode> iterator = store.nodes().iterator(); HashMap<String, ClassNode> newClasses = new HashMap<>(); while (iterator.hasNext()) { ClassNode cn = iterator.next(); ClassNode node = new ClassNode(); RemappingClassAdapter remapping = new RemappingClassAdapter(node, new ClassRemapper()); cn.accept(remapping); newClasses.put(node.name, node); } store.set(newClasses); } public void results() { for (String s : namesMap.keySet()) { LOGGER.fine(s + " replaced with " + namesMap.get(s)); } LOGGER.info("Renamed " + namesMap.size() + " values"); } }
package com.trivago.triava.tcache.util; import java.lang.management.ManagementFactory; import java.util.Set; import javax.cache.CacheException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.trivago.triava.tcache.eviction.Cache; import com.trivago.triava.tcache.eviction.TCacheJSR107; /** * Utility functions to register MBean objects. Concrete implementations for Configuration and * Statistics are excluded and are implemented in subclasses. * <p> * Implementation note: Modeled after the JSR107 RI * * @author cesken * */ public abstract class TCacheMBean { private final static MBeanServer mBeanServer; abstract public String objectNameType(); abstract public Object getMBean(TCacheJSR107<?, ?> jsr107cache); static { String agentId = System.getProperty("org.jsr107.tck.management.agentId"); if (agentId == null) { mBeanServer = ManagementFactory.getPlatformMBeanServer(); } else { mBeanServer = MBeanServerFactory.createMBeanServer(agentId); } } public void register(Cache<?,?> cache) { TCacheJSR107<?, ?> jsr107cache = cache.jsr107cache(); // these can change during runtime, so always look it up ObjectName registeredObjectName = calculateObjectName(jsr107cache, objectNameType()); if (isRegistered(registeredObjectName)) { // Do not register twice. Actually this contains a race condition due to a // check-then-act "isRegistered() => registerMBean()" action, but it should not be // a problem for us, because there are never two caches with the same name alive at the // same time. return; } try { mBeanServer.registerMBean(getMBean(jsr107cache), registeredObjectName); } catch (Exception e) { throw new CacheException("Error registering cache MXBeans for CacheManager " + registeredObjectName + " . Error was " + e.getMessage(), e); } } public void unregister(Cache<?, ?> cache) { TCacheJSR107<?, ?> jsr107cache = cache.jsr107cache(); ObjectName objectName = calculateObjectName(jsr107cache, objectNameType()); Set<ObjectName> registeredObjectNames = mBeanServer.queryNames(objectName, null); // should just be one for (ObjectName registeredObjectName : registeredObjectNames) { try { mBeanServer.unregisterMBean(registeredObjectName); } catch (Exception e) { throw new CacheException("Error unregistering object instance " + registeredObjectName + " . Error was " + e.getMessage(), e); } } } /** * Creates an object name using the scheme * "javax.cache:type=Cache&lt;Statistics|Configuration&gt;,CacheManager=&lt;cacheManagerName&gt;,name=&lt;cacheName&gt;" * <p> * Implementation note: Method modeled after the JSR107 RI */ private static ObjectName calculateObjectName(javax.cache.Cache<?, ?> cache, String objectNameType) { String cacheManagerName = mbeanSafe(cache.getCacheManager().getURI().toString()); String cacheName = mbeanSafe(cache.getName()); try { /** * TODO JSR107 There seems to be a naming mismatch. * - The RI uses "type=CacheConfiguration" and "type=CacheStatistics" * - The API docs of CacheManager.enableManagement() specify "type=Cache" and "type=CacheStatistics" */ return new ObjectName("javax.cache:type=Cache" + objectNameType + ",CacheManager=" + cacheManagerName + ",Cache=" + cacheName); } catch (MalformedObjectNameException e) { throw new CacheException("Illegal ObjectName for Management Bean. " + "CacheManager=[" + cacheManagerName + "], Cache=[" + cacheName + "] type=[" + objectNameType + "]", e); } } /** * Checks whether an ObjectName is already registered. * * @throws CacheException - all exceptions are wrapped in CacheException */ static boolean isRegistered(ObjectName objectName) { Set<ObjectName> registeredObjectNames = mBeanServer.queryNames(objectName, null); return !registeredObjectNames.isEmpty(); } /** * Filter out invalid ObjectName characters from string. * * @param string input string * @return A valid JMX ObjectName attribute value. */ private static String mbeanSafe(String string) { return string == null ? "" : string.replaceAll(",|:|=|\n", "."); } }
package com.mikepenz.materialdrawer; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.FrameLayout; import com.mikepenz.fastadapter.FastAdapter; import com.mikepenz.fastadapter.adapters.FooterAdapter; import com.mikepenz.fastadapter.adapters.HeaderAdapter; import com.mikepenz.fastadapter.adapters.ItemAdapter; import com.mikepenz.materialdrawer.holder.ImageHolder; import com.mikepenz.materialdrawer.holder.StringHolder; import com.mikepenz.materialdrawer.model.ContainerDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.Badgeable; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.Iconable; import com.mikepenz.materialdrawer.model.interfaces.Nameable; import com.mikepenz.materialize.Materialize; import com.mikepenz.materialize.view.ScrimInsetsRelativeLayout; import java.util.ArrayList; import java.util.List; public class Drawer { /** * BUNDLE param to store the selection */ protected static final String BUNDLE_SELECTION = "_selection"; protected static final String BUNDLE_SELECTION_APPENDED = "_selection_appended"; protected static final String BUNDLE_STICKY_FOOTER_SELECTION = "bundle_sticky_footer_selection"; protected static final String BUNDLE_STICKY_FOOTER_SELECTION_APPENDED = "bundle_sticky_footer_selection_appended"; protected static final String BUNDLE_DRAWER_CONTENT_SWITCHED = "bundle_drawer_content_switched"; protected static final String BUNDLE_DRAWER_CONTENT_SWITCHED_APPENDED = "bundle_drawer_content_switched_appended"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ protected static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; protected final DrawerBuilder mDrawerBuilder; private FrameLayout mContentView; /** * the protected Constructor for the result * * @param drawerBuilder */ protected Drawer(DrawerBuilder drawerBuilder) { this.mDrawerBuilder = drawerBuilder; } /** * the protected getter of the mDrawerBuilder * only used internally to prevent the default behavior of some public methods * * @return */ protected DrawerBuilder getDrawerBuilder() { return this.mDrawerBuilder; } /** * Get the DrawerLayout of the current drawer * * @return */ public DrawerLayout getDrawerLayout() { return this.mDrawerBuilder.mDrawerLayout; } /** * Sets the toolbar which should be used in combination with the drawer * This will handle the ActionBarDrawerToggle for you. * Do not set this if you are in a sub activity and want to handle the back arrow on your own * * @param activity * @param toolbar the toolbar which is used in combination with the drawer */ public void setToolbar(@NonNull Activity activity, @NonNull Toolbar toolbar) { setToolbar(activity, toolbar, false); } /** * Sets the toolbar which should be used in combination with the drawer * This will handle the ActionBarDrawerToggle for you. * Do not set this if you are in a sub activity and want to handle the back arrow on your own * * @param activity * @param toolbar the toolbar which is used in combination with the drawer * @param recreateActionBarDrawerToggle defines if the ActionBarDrawerToggle needs to be recreated with the new set Toolbar */ public void setToolbar(@NonNull Activity activity, @NonNull Toolbar toolbar, boolean recreateActionBarDrawerToggle) { this.mDrawerBuilder.mToolbar = toolbar; this.mDrawerBuilder.handleDrawerNavigation(activity, recreateActionBarDrawerToggle); } /** * Add a custom ActionBarDrawerToggle which will be used in combination with this drawer. * * @param actionBarDrawerToggle */ public void setActionBarDrawerToggle(@NonNull ActionBarDrawerToggle actionBarDrawerToggle) { this.mDrawerBuilder.mActionBarDrawerToggleEnabled = true; this.mDrawerBuilder.mActionBarDrawerToggle = actionBarDrawerToggle; this.mDrawerBuilder.handleDrawerNavigation(null, false); } /** * Open the drawer */ public void openDrawer() { if (mDrawerBuilder.mDrawerLayout != null && mDrawerBuilder.mSliderLayout != null) { mDrawerBuilder.mDrawerLayout.openDrawer(mDrawerBuilder.mDrawerGravity); } } /** * close the drawer */ public void closeDrawer() { if (mDrawerBuilder.mDrawerLayout != null) { mDrawerBuilder.mDrawerLayout.closeDrawer(mDrawerBuilder.mDrawerGravity); } } /** * Get the current state of the drawer. * True if the drawer is currently open. * * @return */ public boolean isDrawerOpen() { if (mDrawerBuilder.mDrawerLayout != null && mDrawerBuilder.mSliderLayout != null) { return mDrawerBuilder.mDrawerLayout.isDrawerOpen(mDrawerBuilder.mDrawerGravity); } return false; } /** * set the insetsFrameLayout to display the content in fullscreen * under the statusBar and navigationBar * * @param fullscreen */ public void setFullscreen(boolean fullscreen) { if (mDrawerBuilder.mMaterialize != null) { mDrawerBuilder.mMaterialize.setFullscreen(fullscreen); } } /** * get the Materialize object used to beautify your activity * * @return */ public Materialize getMaterialize() { return mDrawerBuilder.mMaterialize; } /** * gets the already generated MiniDrawer or creates a new one * * @return */ public MiniDrawer getMiniDrawer() { if (mDrawerBuilder.mMiniDrawer == null) { mDrawerBuilder.mMiniDrawer = new MiniDrawer().withDrawer(this).withAccountHeader(mDrawerBuilder.mAccountHeader); } return mDrawerBuilder.mMiniDrawer; } /** * get the slider layout of the current drawer. * This is the layout containing the ListView * * @return */ public ScrimInsetsRelativeLayout getSlider() { return mDrawerBuilder.mSliderLayout; } /** * get the container frameLayout of the current drawer * * @return */ public FrameLayout getContent() { if (mContentView == null && this.mDrawerBuilder.mDrawerLayout != null) { mContentView = (FrameLayout) this.mDrawerBuilder.mDrawerLayout.findViewById(R.id.content_layout); } return mContentView; } /** * get the listView of the current drawer * * @return */ public RecyclerView getRecyclerView() { return mDrawerBuilder.mRecyclerView; } /** * get the FastAdapter of the current drawer * * @return */ public FastAdapter<IDrawerItem> getAdapter() { return mDrawerBuilder.mAdapter; } /** * get the HeaderAdapter of the current drawer * * @return */ public HeaderAdapter<IDrawerItem> getHeaderAdapter() { return mDrawerBuilder.mHeaderAdapter; } /** * get the ItemAdapter of the current drawer * * @return */ public ItemAdapter<IDrawerItem> getItemAdapter() { return mDrawerBuilder.mItemAdapter; } /** * get the FooterAdapter of the current drawer * * @return */ public FooterAdapter<IDrawerItem> getFooterAdapter() { return mDrawerBuilder.mFooterAdapter; } /** * get all drawerItems of the current drawer * * @return */ public List<IDrawerItem> getDrawerItems() { return mDrawerBuilder.getItemAdapter().getAdapterItems(); } /** * get the Header View if set else NULL * * @return */ public View getHeader() { return mDrawerBuilder.mHeaderView; } /** * get the StickyHeader View if set else NULL * * @return */ public View getStickyHeader() { return mDrawerBuilder.mStickyHeaderView; } /** * method to replace a previous set header * * @param view */ public void setHeader(@NonNull View view) { setHeader(view, true, true); } /** * method to replace a previous set header * * @param view * @param divider */ public void setHeader(@NonNull View view, boolean divider) { setHeader(view, true, divider); } /** * method to replace a previous set header * * @param view * @param padding * @param divider */ public void setHeader(@NonNull View view, boolean padding, boolean divider) { mDrawerBuilder.getHeaderAdapter().clear(); if (padding) { mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withViewPosition(ContainerDrawerItem.Position.TOP)); } else { mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withViewPosition(ContainerDrawerItem.Position.NONE)); } } /** * method to remove the header of the list */ public void removeHeader() { mDrawerBuilder.getHeaderAdapter().clear(); } /** * get the Footer View if set else NULL * * @return */ public View getFooter() { return mDrawerBuilder.mFooterView; } /** * get the StickyFooter View if set else NULL * * @return */ public View getStickyFooter() { return mDrawerBuilder.mStickyFooterView; } /** * get the StickyFooter Shadow View if set else NULL * * @return */ private View getStickyFooterShadow() { return mDrawerBuilder.mStickyFooterShadowView; } /** * get the ActionBarDrawerToggle * * @return */ public ActionBarDrawerToggle getActionBarDrawerToggle() { return mDrawerBuilder.mActionBarDrawerToggle; } /** * calculates the position of an drawerItem. searching by it's identifier * * @param drawerItem * @return */ public int getPosition(@NonNull IDrawerItem drawerItem) { return getPosition(drawerItem.getIdentifier()); } /** * calculates the position of an drawerItem. searching by it's identifier * * @param identifier * @return */ public int getPosition(long identifier) { return DrawerUtils.getPositionByIdentifier(mDrawerBuilder, identifier); } /** * returns the DrawerItem by the given identifier * * @param identifier * @return */ public IDrawerItem getDrawerItem(long identifier) { return (IDrawerItem) getAdapter().getItem(getPosition(identifier)); } /** * returns the found drawerItem by the given tag * * @param tag * @return */ public IDrawerItem getDrawerItem(Object tag) { return DrawerUtils.getDrawerItem(getDrawerItems(), tag); } /** * calculates the position of an drawerItem. searching by it's identifier * * @param drawerItem * @return */ public int getStickyFooterPosition(@NonNull IDrawerItem drawerItem) { return getStickyFooterPosition(drawerItem.getIdentifier()); } /** * calculates the position of an drawerItem inside the footer. searching by it's identfier * * @param identifier * @return */ public int getStickyFooterPosition(long identifier) { return DrawerUtils.getStickyFooterPositionByIdentifier(mDrawerBuilder, identifier); } /** * get the current position of the selected drawer element * * @return */ public int getCurrentSelectedPosition() { return mDrawerBuilder.mAdapter.getSelections().size() == 0 ? -1 : mDrawerBuilder.mAdapter.getSelections().iterator().next(); } /** * get the current selected item identifier * * @return */ public long getCurrentSelection() { IDrawerItem drawerItem = mDrawerBuilder.getDrawerItem(getCurrentSelectedPosition()); if (drawerItem != null) { return drawerItem.getIdentifier(); } return -1; } /** * get the current position of the selected sticky footer element * * @return */ public int getCurrentStickyFooterSelectedPosition() { return mDrawerBuilder.mCurrentStickyFooterSelection; } /** * deselects all selected items */ public void deselect() { getAdapter().deselect(); } /** * deselects the item with the given identifier * * @param identifier the identifier to search for */ public void deselect(long identifier) { getAdapter().deselect(getPosition(identifier)); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param identifier the identifier to search for */ public boolean setSelection(long identifier) { return setSelectionAtPosition(getPosition(identifier), true); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param identifier the identifier to search for * @param fireOnClick true if the click listener should be called */ public boolean setSelection(long identifier, boolean fireOnClick) { return setSelectionAtPosition(getPosition(identifier), fireOnClick); } /** * set the current selection in the footer of the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param identifier the identifier to search for * @param fireOnClick true if the click listener should be called */ public void setStickyFooterSelection(long identifier, boolean fireOnClick) { setStickyFooterSelectionAtPosition(getStickyFooterPosition(identifier), fireOnClick); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param drawerItem the drawerItem to select (this requires a set identifier) */ public boolean setSelection(@NonNull IDrawerItem drawerItem) { return setSelectionAtPosition(getPosition(drawerItem), true); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param drawerItem the drawerItem to select (this requires a set identifier) * @param fireOnClick true if the click listener should be called */ public boolean setSelection(@NonNull IDrawerItem drawerItem, boolean fireOnClick) { return setSelectionAtPosition(getPosition(drawerItem), fireOnClick); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param position the position to select */ public boolean setSelectionAtPosition(int position) { return setSelectionAtPosition(position, true); } /* * set the current selection in the drawer * NOTE: this also deselects all other selections. if you do not want this. use the direct api of the adater .getAdapter().select(position, fireOnClick) * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param position * @param fireOnClick * @return true if the event was consumed */ public boolean setSelectionAtPosition(int position, boolean fireOnClick) { if (mDrawerBuilder.mRecyclerView != null) { mDrawerBuilder.mAdapter.deselect(); mDrawerBuilder.mAdapter.select(position, false); if (mDrawerBuilder.mOnDrawerItemClickListener != null && fireOnClick) { mDrawerBuilder.mOnDrawerItemClickListener.onItemClick(null, position, mDrawerBuilder.mAdapter.getItem(position)); } } return false; } /** * set the current selection in the footer of the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param position the position to select */ public void setStickyFooterSelectionAtPosition(int position) { setStickyFooterSelectionAtPosition(position, true); } /** * set the current selection in the footer of the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param position * @param fireOnClick */ public void setStickyFooterSelectionAtPosition(int position, boolean fireOnClick) { DrawerUtils.setStickyFooterSelection(mDrawerBuilder, position, fireOnClick); } /** * update a specific drawer item :D * automatically identified by its id * * @param drawerItem */ public void updateItem(@NonNull IDrawerItem drawerItem) { updateItemAtPosition(drawerItem, getPosition(drawerItem)); } /** * update the badge for a specific drawerItem * identified by its id * * @param identifier * @param badge */ public void updateBadge(long identifier, StringHolder badge) { IDrawerItem drawerItem = getDrawerItem(identifier); if (drawerItem instanceof Badgeable) { Badgeable badgeable = (Badgeable) drawerItem; badgeable.withBadge(badge); updateItem((IDrawerItem) badgeable); } } /** * update the name for a specific drawerItem * identified by its id * * @param identifier * @param name */ public void updateName(long identifier, StringHolder name) { IDrawerItem drawerItem = getDrawerItem(identifier); if (drawerItem instanceof Nameable) { Nameable pdi = (Nameable) drawerItem; pdi.withName(name); updateItem((IDrawerItem) pdi); } } /** * update the name for a specific drawerItem * identified by its id * * @param identifier * @param image */ public void updateIcon(long identifier, ImageHolder image) { IDrawerItem drawerItem = getDrawerItem(identifier); if (drawerItem instanceof Iconable) { Iconable pdi = (Iconable) drawerItem; pdi.withIcon(image); updateItem((IDrawerItem) pdi); } } /** * Update a drawerItem at a specific position * * @param drawerItem * @param position */ public void updateItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { if (mDrawerBuilder.checkDrawerItem(position, false)) { mDrawerBuilder.getItemAdapter().set(position, drawerItem); } } /** * Add a drawerItem at the end * * @param drawerItem */ public void addItem(@NonNull IDrawerItem drawerItem) { mDrawerBuilder.getItemAdapter().add(drawerItem); } /** * Add a drawerItem at a specific position * * @param drawerItem * @param position */ public void addItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { mDrawerBuilder.getItemAdapter().add(position, drawerItem); } /** * Set a drawerItem at a specific position * * @param drawerItem * @param position */ public void setItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { mDrawerBuilder.getItemAdapter().add(position, drawerItem); } /** * Remove a drawerItem at a specific position * * @param position */ public void removeItemByPosition(int position) { if (mDrawerBuilder.checkDrawerItem(position, false)) { mDrawerBuilder.getItemAdapter().remove(position); } } /** * Remove a drawerItem by the identifier * * @param identifier */ public void removeItem(long identifier) { int position = getPosition(identifier); if (mDrawerBuilder.checkDrawerItem(position, false)) { mDrawerBuilder.getItemAdapter().remove(position); } } /** * remove a list of drawerItems by ther identifiers * * @param identifiers */ public void removeItems(long... identifiers) { if (identifiers != null) { for (long identifier : identifiers) { removeItem(identifier); } } } /** * Removes all items from drawer */ public void removeAllItems() { mDrawerBuilder.getItemAdapter().clear(); } /** * add new Items to the current DrawerItem List * * @param drawerItems */ public void addItems(@NonNull IDrawerItem... drawerItems) { mDrawerBuilder.getItemAdapter().add(drawerItems); } /** * add new items to the current DrawerItem list at a specific position * * @param position * @param drawerItems */ public void addItemsAtPosition(int position, @NonNull IDrawerItem... drawerItems) { mDrawerBuilder.getItemAdapter().add(position, drawerItems); } /** * Replace the current DrawerItems with a new ArrayList of items * * @param drawerItems */ public void setItems(@NonNull List<IDrawerItem> drawerItems) { setItems(drawerItems, false); } /** * replace the current DrawerItems with the new ArrayList. * * @param drawerItems * @param switchedItems */ private void setItems(@NonNull List<IDrawerItem> drawerItems, boolean switchedItems) { //if we are currently at a switched list set the new reference if (originalDrawerItems != null && !switchedItems) { originalDrawerItems = drawerItems; } mDrawerBuilder.getItemAdapter().setNewList(drawerItems); } /** * update a specific footerDrawerItem :D * automatically identified by it's id * * @param drawerItem */ public void updateStickyFooterItem(@NonNull IDrawerItem drawerItem) { updateStickyFooterItemAtPosition(drawerItem, getStickyFooterPosition(drawerItem)); } /** * update a footerDrawerItem at a specific position * * @param drawerItem * @param position */ public void updateStickyFooterItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) { mDrawerBuilder.mStickyDrawerItems.set(position, drawerItem); } DrawerUtils.rebuildStickyFooterView(mDrawerBuilder); } /** * Add a footerDrawerItem at the end * * @param drawerItem */ public void addStickyFooterItem(@NonNull IDrawerItem drawerItem) { if (mDrawerBuilder.mStickyDrawerItems == null) { mDrawerBuilder.mStickyDrawerItems = new ArrayList<>(); } mDrawerBuilder.mStickyDrawerItems.add(drawerItem); DrawerUtils.rebuildStickyFooterView(mDrawerBuilder); } /** * Add a footerDrawerItem at a specific position * * @param drawerItem * @param position */ public void addStickyFooterItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { if (mDrawerBuilder.mStickyDrawerItems == null) { mDrawerBuilder.mStickyDrawerItems = new ArrayList<>(); } mDrawerBuilder.mStickyDrawerItems.add(position, drawerItem); DrawerUtils.rebuildStickyFooterView(mDrawerBuilder); } /** * Set a footerDrawerItem at a specific position * * @param drawerItem * @param position */ public void setStickyFooterItemAtPosition(@NonNull IDrawerItem drawerItem, int position) { if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) { mDrawerBuilder.mStickyDrawerItems.set(position, drawerItem); } DrawerUtils.rebuildStickyFooterView(mDrawerBuilder); } /** * Remove a footerDrawerItem at a specific position * * @param position */ public void removeStickyFooterItemAtPosition(int position) { if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) { mDrawerBuilder.mStickyDrawerItems.remove(position); } DrawerUtils.rebuildStickyFooterView(mDrawerBuilder); } /** * Removes all footerItems from drawer */ public void removeAllStickyFooterItems() { if (mDrawerBuilder.mStickyDrawerItems != null) { mDrawerBuilder.mStickyDrawerItems.clear(); } if (mDrawerBuilder.mStickyFooterView != null) { mDrawerBuilder.mStickyFooterView.setVisibility(View.GONE); } } /** * setter for the OnDrawerItemClickListener * * @param onDrawerItemClickListener */ public void setOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) { mDrawerBuilder.mOnDrawerItemClickListener = onDrawerItemClickListener; } public void setOnDrawerNavigationListener(OnDrawerNavigationListener onDrawerNavigationListener) { //WBE mDrawerBuilder.mOnDrawerNavigationListener = onDrawerNavigationListener; } /** * method to get the OnDrawerItemClickListener * * @return */ public OnDrawerItemClickListener getOnDrawerItemClickListener() { return mDrawerBuilder.mOnDrawerItemClickListener; } /** * method to get the OnDrawerNavigationListener * * @return */ public OnDrawerNavigationListener getOnDrawerNavigationListener() { //WBE return mDrawerBuilder.mOnDrawerNavigationListener; } /** * setter for the OnDrawerItemLongClickListener * * @param onDrawerItemLongClickListener */ public void setOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) { mDrawerBuilder.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener; } /** * method to get the OnDrawerItemLongClickListener * * @return */ public OnDrawerItemLongClickListener getOnDrawerItemLongClickListener() { return mDrawerBuilder.mOnDrawerItemLongClickListener; } //variables to store and remember the original list of the drawer private Drawer.OnDrawerItemClickListener originalOnDrawerItemClickListener; private Drawer.OnDrawerItemLongClickListener originalOnDrawerItemLongClickListener; private List<IDrawerItem> originalDrawerItems; private Bundle originalDrawerState; /** * information if the current drawer content is switched by alternative content (profileItems) * * @return */ public boolean switchedDrawerContent() { return !(originalOnDrawerItemClickListener == null && originalDrawerItems == null && originalDrawerState == null); } /** * get the original list of drawerItems * * @return */ public List<IDrawerItem> getOriginalDrawerItems() { return originalDrawerItems; } /** * method to switch the drawer content to new elements * * @param onDrawerItemClickListener * @param drawerItems * @param drawerSelection */ public void switchDrawerContent(@NonNull OnDrawerItemClickListener onDrawerItemClickListener, OnDrawerItemLongClickListener onDrawerItemLongClickListener, @NonNull List<IDrawerItem> drawerItems, int drawerSelection) { //just allow a single switched drawer if (!switchedDrawerContent()) { //save out previous values originalOnDrawerItemClickListener = getOnDrawerItemClickListener(); originalOnDrawerItemLongClickListener = getOnDrawerItemLongClickListener(); originalDrawerState = getAdapter().saveInstanceState(new Bundle()); getAdapter().collapse(); originalDrawerItems = getDrawerItems(); } //set the new items setOnDrawerItemClickListener(onDrawerItemClickListener); setOnDrawerItemLongClickListener(onDrawerItemLongClickListener); setItems(drawerItems, true); setSelectionAtPosition(drawerSelection, false); //hide stickyFooter and it's shadow if (getStickyFooter() != null) { getStickyFooter().setVisibility(View.GONE); } if (getStickyFooterShadow() != null) { getStickyFooterShadow().setVisibility(View.GONE); } } /** * helper method to reset to the original drawerContent */ public void resetDrawerContent() { if (switchedDrawerContent()) { //set the new items setOnDrawerItemClickListener(originalOnDrawerItemClickListener); setOnDrawerItemLongClickListener(originalOnDrawerItemLongClickListener); setItems(originalDrawerItems, true); getAdapter().withSavedInstanceState(originalDrawerState); //remove the references originalOnDrawerItemClickListener = null; originalOnDrawerItemLongClickListener = null; originalDrawerItems = null; originalDrawerState = null; //if we switch back scroll back to the top mDrawerBuilder.mRecyclerView.smoothScrollToPosition(0); //show the stickyFooter and it's shadow again if (getStickyFooter() != null) { getStickyFooter().setVisibility(View.VISIBLE); } if (getStickyFooterShadow() != null) { getStickyFooterShadow().setVisibility(View.VISIBLE); } //if we currently show the accountHeader selection list make sure to reset this attr if (mDrawerBuilder.mAccountHeader != null && mDrawerBuilder.mAccountHeader.mAccountHeaderBuilder != null) { mDrawerBuilder.mAccountHeader.mAccountHeaderBuilder.mSelectionListShown = false; } } } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState * @return */ public Bundle saveInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { if (!mDrawerBuilder.mAppended) { savedInstanceState = mDrawerBuilder.mAdapter.saveInstanceState(savedInstanceState, BUNDLE_SELECTION); savedInstanceState.putInt(BUNDLE_STICKY_FOOTER_SELECTION, mDrawerBuilder.mCurrentStickyFooterSelection); savedInstanceState.putBoolean(BUNDLE_DRAWER_CONTENT_SWITCHED, switchedDrawerContent()); } else { savedInstanceState = mDrawerBuilder.mAdapter.saveInstanceState(savedInstanceState, BUNDLE_SELECTION_APPENDED); savedInstanceState.putInt(BUNDLE_STICKY_FOOTER_SELECTION_APPENDED, mDrawerBuilder.mCurrentStickyFooterSelection); savedInstanceState.putBoolean(BUNDLE_DRAWER_CONTENT_SWITCHED_APPENDED, switchedDrawerContent()); } } return savedInstanceState; } public interface OnDrawerNavigationListener { /** * @param clickedView * @return true if the event was consumed */ boolean onNavigationClickListener(View clickedView); } public interface OnDrawerItemClickListener { /** * @param view * @param position * @param drawerItem * @return true if the event was consumed */ boolean onItemClick(View view, int position, IDrawerItem drawerItem); } public interface OnDrawerItemLongClickListener { /** * @param view * @param position * @param drawerItem * @return true if the event was consumed */ boolean onItemLongClick(View view, int position, IDrawerItem drawerItem); } public interface OnDrawerListener { /** * @param drawerView */ void onDrawerOpened(View drawerView); /** * @param drawerView */ void onDrawerClosed(View drawerView); /** * @param drawerView * @param slideOffset */ void onDrawerSlide(View drawerView, float slideOffset); } public interface OnDrawerItemSelectedListener { /** * @param parent * @param view * @param position * @param id * @param drawerItem */ void onItemSelected(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem); /** * @param parent */ void onNothingSelected(AdapterView<?> parent); } }
package net.aquadc.vkauth; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ProgressBar; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Locale; import java.util.Map; import static net.aquadc.vkauth.Util.dp; import static net.aquadc.vkauth.Util.explodeQueryString; @SuppressWarnings("WeakerAccess") /*pkg*/ final class VkOAuthDialogHolder { private static final String VK_EXTRA_CLIENT_ID = "client_id"; private static final String VK_EXTRA_SCOPE = "scope"; private static final String VK_EXTRA_API_VERSION = "version"; private static final String VK_EXTRA_REVOKE = "revoke"; private static final String VK_RESULT_INTENT_NAME = "com.vk.auth-token"; private static final String VK_EXTRA_TOKEN_DATA = "extra-token-data"; private static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; private static final String ERROR = "error"; private static final String CANCEL = "deliverResult"; /*pkg*/ final ViewGroup root; /*pkg*/ final View progress; /*pkg*/ final WebView webView; /*pkg*/ final Dialog dialog; /*pkg*/ final Bundle arguments; private final Host host; /*pkg*/ volatile String email; private int resultCode = Activity.RESULT_CANCELED; private Intent data; /*pkg*/ VkOAuthDialogHolder(Context context, Bundle arguments, Bundle savedInstanceState, Host host) { this.root = new FrameLayout(context); root.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); int tenDp = dp(context, 10); root.setPadding(tenDp, tenDp, tenDp, tenDp); this.progress = new ProgressBar(context); progress.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); root.addView(progress); webView = new WebView(context); webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); webView.setVisibility(View.INVISIBLE); root.addView(webView); dialog = new Dialog(context, R.style.VKAlertDialog); dialog.setContentView(root); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { dialog.getWindow().setStatusBarColor(Color.TRANSPARENT); } this.arguments = arguments; this.host = host; if (savedInstanceState != null) { email = savedInstanceState.getString("email"); } loadPage(); } @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"}) /*pkg*/ void loadPage() { try { Bundle parameters = arguments; int appId = parameters.getInt(VK_EXTRA_CLIENT_ID, 0); String scope = parameters.getString(VK_EXTRA_SCOPE); String apiVersion = parameters.getString(VK_EXTRA_API_VERSION); boolean revoke = parameters.getBoolean(VK_EXTRA_REVOKE, false); String urlToLoad = String.format(Locale.US, "https://oauth.vk.com/authorize?client_id=%s" + "&scope=%s" + "&redirect_uri=%s" + "&display=mobile" + "&v=%s" + "&response_type=token&revoke=%d", appId, URLEncoder.encode(scope, "UTF-8"), URLEncoder.encode(REDIRECT_URL, "UTF-8"), apiVersion, revoke ? 1 : 0); webView.setWebViewClient(new OAuthWebViewClient(host)); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); // spy for email, part 1 if (Build.VERSION.SDK_INT >= 19) { webView.addJavascriptInterface(new Object() { @JavascriptInterface public void setEmail(String email) { VkOAuthDialogHolder.this.email = email; } }, "SDK"); } webView.loadUrl(urlToLoad); webView.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } webView.setVerticalScrollBarEnabled(false); webView.setVisibility(View.INVISIBLE); webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER); progress.setVisibility(View.VISIBLE); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } /*pkg*/ void onSaveInstanceState(final Bundle outState) { outState.putString("email", email); } /*pkg*/ void deliverResultToActivity(Activity activity) { VkApp .getInstance(arguments.getInt(VK_EXTRA_CLIENT_ID)) .onActivityResult(arguments.getInt("request code"), resultCode, data, ((VkApp.VkAuthCallbackProvider) activity).getVkAuthCallback()); } private interface Host { VkOAuthDialogHolder getHolder(); void dismiss(); void setResultAndFinish(int result, Intent data); } public static final class NativeFragment extends android.app.DialogFragment implements Host { private VkOAuthDialogHolder holder; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { holder = new VkOAuthDialogHolder(getActivity(), getArguments(), savedInstanceState, this); return holder.dialog; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); holder.onSaveInstanceState(outState); } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); deliverResult(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); deliverResult(); } private void deliverResult() { android.app.Fragment target = getTargetFragment(); if (target == null) { holder.deliverResultToActivity(getActivity()); } else { Bundle arguments = getArguments(); target.onActivityResult(arguments.getInt("request code"), holder.resultCode, holder.data); } } @Override public VkOAuthDialogHolder getHolder() { return holder; } @Override public void setResultAndFinish(int result, Intent data) { holder.resultCode = result; holder.data = data; dismiss(); } } public static final class CompatFragment extends android.support.v4.app.DialogFragment implements Host { private VkOAuthDialogHolder holder; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { holder = new VkOAuthDialogHolder(getActivity(), getArguments(), savedInstanceState, this); return holder.dialog; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); holder.onSaveInstanceState(outState); } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); deliverResult(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); deliverResult(); } private void deliverResult() { android.support.v4.app.Fragment target = getTargetFragment(); if (target == null) { holder.deliverResultToActivity(getActivity()); } else { Bundle arguments = getArguments(); target.onActivityResult(arguments.getInt("request code"), holder.resultCode, holder.data); } } @Override public VkOAuthDialogHolder getHolder() { return holder; } @Override public void setResultAndFinish(int result, Intent data) { holder.resultCode = result; holder.data = data; dismiss(); } } private static final class OAuthWebViewClient extends WebViewClient implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { boolean canShowPage = true; final Host host; /*pkg*/ OAuthWebViewClient(Host host) { this.host = host; } boolean processUrl(String url) { if (url.startsWith(REDIRECT_URL)) { Intent data = new Intent(VK_RESULT_INTENT_NAME); String extraData = url.substring(url.indexOf(' data.putExtra(VK_EXTRA_TOKEN_DATA, extraData); Map<String, String> resultParams = explodeQueryString(extraData); if (resultParams != null && (resultParams.containsKey(ERROR) || resultParams.containsKey(CANCEL))) { host.setResultAndFinish(Activity.RESULT_CANCELED, data); } else { host.setResultAndFinish(Activity.RESULT_OK, data); } return true; } return false; } @Override @SuppressWarnings("deprecation") public boolean shouldOverrideUrlLoading(WebView view, String url) { if (processUrl(url)) return true; canShowPage = true; return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { processUrl(url); } @Override public void onPageFinished(WebView view, String url) { if (canShowPage) { VkOAuthDialogHolder holder = host.getHolder(); holder.progress.setVisibility(View.GONE); view.setVisibility(View.VISIBLE); // spy for email, part 2 if (Build.VERSION.SDK_INT >= 19) { String email = holder.email; if (email != null) { view.evaluateJavascript("document.forms[0].email.value = \"" + email.replace("\\", "\\\\").replace("\"", "\\\"") + "\"", null); } view.evaluateJavascript("document.forms[0].email.onkeyup = function() { SDK.setEmail(document.forms[0].email.value) }", null); } } } @Override @SuppressWarnings("deprecation") public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { canShowPage = false; AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()) .setMessage(view.getResources().getString(R.string.vk_webView_error) + '\n' + description) .setPositiveButton(R.string.vk_retry, this) .setNegativeButton(android.R.string.cancel, this) .setOnCancelListener(this); builder.show(); // was in try-catch O_o } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_NEGATIVE: host.dismiss(); break; case DialogInterface.BUTTON_POSITIVE: host.getHolder().loadPage(); break; default: throw new AssertionError(); } } @Override public void onCancel(DialogInterface dialog) { host.dismiss(); } } }
package com.mikepenz.materialdrawer; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import com.mikepenz.iconics.typeface.IIcon; import com.mikepenz.iconics.utils.Utils; import com.mikepenz.materialdrawer.accountswitcher.AccountHeader; import com.mikepenz.materialdrawer.adapter.BaseDrawerAdapter; import com.mikepenz.materialdrawer.adapter.DrawerAdapter; import com.mikepenz.materialdrawer.model.interfaces.Badgeable; import com.mikepenz.materialdrawer.model.interfaces.Checkable; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.Iconable; import com.mikepenz.materialdrawer.model.interfaces.Nameable; import java.util.ArrayList; import java.util.Collections; public class Drawer { private static final String BUNDLE_SELECTION = "bundle_selection"; // some internal vars // variable to check if a builder is only used once protected boolean mUsed = false; protected int mCurrentSelection = -1; // the activity to use protected Activity mActivity; protected ViewGroup mRootView; /** * Pass the activity you use the drawer in ;) * * @param activity * @return */ public Drawer withActivity(Activity activity) { this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content); this.mActivity = activity; return this; } // set actionbar Compatibility mode protected boolean mTranslucentActionBarCompatibility = false; /** * Just use this parameter if you really want to use a translucent statusbar with an * actionbar * * @param translucentActionBarCompatibility * @return */ public Drawer withTranslucentActionBarCompatibility(boolean translucentActionBarCompatibility) { this.mTranslucentActionBarCompatibility = translucentActionBarCompatibility; return this; } // set non translucent statusbar mode protected boolean mTranslucentStatusBar = true; /** * Set or disable this if you use a translucent statusbar * * @param translucentStatusBar * @return */ public Drawer withTranslucentStatusBar(boolean translucentStatusBar) { this.mTranslucentStatusBar = translucentStatusBar; return this; } /** * Set or disable this if you want to show the drawer below the toolbar. * Note this will add a margin above the drawer * * @param displayBelowToolbar * @return */ public Drawer withDisplayBelowToolbar(boolean displayBelowToolbar) { this.mTranslucentStatusBar = displayBelowToolbar; return this; } // the toolbar of the activity protected Toolbar mToolbar; /** * Pass the toolbar you would love to use with this drawer * * @param toolbar * @return */ public Drawer withToolbar(Toolbar toolbar) { this.mToolbar = toolbar; return this; } // the drawerLayout to use protected DrawerLayout mDrawerLayout; protected LinearLayout mSliderLayout; /** * You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml * * @param drawerLayout * @return */ public Drawer withDrawerLayout(DrawerLayout drawerLayout) { this.mDrawerLayout = drawerLayout; return this; } /** * You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub * * @param resLayout * @return */ public Drawer withDrawerLayout(int resLayout) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (resLayout != -1) { this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(resLayout, mRootView, false); } else { this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer, mRootView, false); } return this; } //the background color for the slider protected int mSliderBackgroundColor = -1; protected int mSliderBackgroundColorRes = -1; /** * set the background for the slider as color * * @param sliderBackgroundColor * @return */ public Drawer withSliderBackgroundColor(int sliderBackgroundColor) { this.mSliderBackgroundColor = sliderBackgroundColor; return this; } /** * set the background for the slider as resource * * @param sliderBackgroundColorRes * @return */ public Drawer withSliderBackgroundColorRes(int sliderBackgroundColorRes) { this.mSliderBackgroundColorRes = sliderBackgroundColorRes; return this; } //the width of the drawer protected int mDrawerWidth = -1; /** * set the drawer width as px * * @param drawerWidthPx * @return */ public Drawer withDrawerWidthPx(int drawerWidthPx) { this.mDrawerWidth = drawerWidthPx; return this; } /** * set the drawer width as dp * * @param drawerWidthDp * @return */ public Drawer withDrawerWidthDp(int drawerWidthDp) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } this.mDrawerWidth = Utils.convertDpToPx(mActivity, drawerWidthDp); return this; } /** * set the drawer width from resource * * @param drawerWidthRes * @return */ public Drawer withDrawerWidthRes(int drawerWidthRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } this.mDrawerWidth = mActivity.getResources().getDimensionPixelSize(drawerWidthRes); return this; } //the gravity of the drawer protected Integer mDrawerGravity = null; public Drawer withDrawerGravity(int gravity) { this.mDrawerGravity = gravity; return this; } //the account selection header to use protected AccountHeader.Result mAccountHeader; /** * set the accountHeader to use for this drawer instance * not this will overwrite the mHeaderView if set * * @param accountHeader * @return */ public Drawer withAccountHeader(AccountHeader.Result accountHeader) { this.mAccountHeader = accountHeader; //set the header offset mHeaderOffset = 1; return this; } // enable/disable the actionBarDrawerToggle animation protected boolean mAnimateActionBarDrawerToggle = false; /** * set this to enable/disable the actionBarDrawerToggle animation * * @param actionBarDrawerToggleAnimated * @return */ public Drawer withActionBarDrawerToggleAnimated(boolean actionBarDrawerToggleAnimated) { this.mAnimateActionBarDrawerToggle = actionBarDrawerToggleAnimated; return this; } // enable the drawer toggle / if withActionBarDrawerToggle we will autoGenerate it protected boolean mActionBarDrawerToggleEnabled = true; /** * set to true if you want a ActionBarDrawerToggle handled by the lib * * @param actionBarDrawerToggleEnabled * @return */ public Drawer withActionBarDrawerToggle(boolean actionBarDrawerToggleEnabled) { this.mActionBarDrawerToggleEnabled = actionBarDrawerToggleEnabled; return this; } // drawer toggle protected ActionBarDrawerToggle mActionBarDrawerToggle; /** * pass an ActionBarDrawerToggle you would love to use with this drawer * * @param actionBarDrawerToggle * @return */ public Drawer withActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) { this.mActionBarDrawerToggleEnabled = true; this.mActionBarDrawerToggle = actionBarDrawerToggle; return this; } // header view protected View mHeaderView; protected int mHeaderOffset = 0; protected boolean mHeaderDivider = true; protected boolean mHeaderClickable = false; /** * add a header layout from view * * @param headerView * @return */ public Drawer withHeader(View headerView) { this.mHeaderView = headerView; //set the header offset mHeaderOffset = 1; return this; } /** * add a header layout from res * * @param headerViewRes * @return */ public Drawer withHeader(int headerViewRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (headerViewRes != -1) { //i know there should be a root, bit i got none here this.mHeaderView = mActivity.getLayoutInflater().inflate(headerViewRes, null, false); //set the headerOffset :D mHeaderOffset = 1; } return this; } /** * set if the header is clickable * * @param headerClickable * @return */ public Drawer withHeaderClickable(boolean headerClickable) { this.mHeaderClickable = headerClickable; return this; } /** * this method allows you to disable the divider on the bottom of the header * * @param headerDivider * @return */ public Drawer withHeaderDivider(boolean headerDivider) { this.mHeaderDivider = headerDivider; return this; } // footer view protected View mFooterView; protected boolean mFooterDivider = true; protected boolean mFooterClickable = false; /** * add a footer layout from view * * @param footerView * @return */ public Drawer withFooter(View footerView) { this.mFooterView = footerView; return this; } /** * add a footer layout from res * * @param footerViewRes * @return */ public Drawer withFooter(int footerViewRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (footerViewRes != -1) { //i know there should be a root, bit i got none here this.mFooterView = mActivity.getLayoutInflater().inflate(footerViewRes, null, false); } return this; } /** * set if the footer is clickable * * @param footerClickable * @return */ public Drawer withFooterClickable(boolean footerClickable) { this.mFooterClickable = footerClickable; return this; } /** * this method allows you to disable the divider on top of the footer * * @param footerDivider * @return */ public Drawer withFooterDivider(boolean footerDivider) { this.mFooterDivider = footerDivider; return this; } // sticky view protected View mStickyFooterView; /** * add a sticky footer layout from view * this view will be always visible on the bottom * * @param stickyFooter * @return */ public Drawer withStickyFooter(View stickyFooter) { this.mStickyFooterView = stickyFooter; return this; } /** * add a sticky footer layout from res * this view will be always visible on the bottom * * @param stickyFooterRes * @return */ public Drawer withStickyFooter(int stickyFooterRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (stickyFooterRes != -1) { //i know there should be a root, bit i got none here this.mStickyFooterView = mActivity.getLayoutInflater().inflate(stickyFooterRes, null, false); } return this; } // fire onClick after build protected boolean mFireInitialOnClick = false; /** * enable this if you would love to receive a onClick event after the build method is called * to be able to show the initial layout. * * @param fireOnInitialOnClick * @return */ public Drawer withFireOnInitialOnClick(boolean fireOnInitialOnClick) { this.mFireInitialOnClick = fireOnInitialOnClick; return this; } // item to select protected int mSelectedItem = 0; /** * pass the item which should be selected on start * * @param selectedItem * @return */ public Drawer withSelectedItem(int selectedItem) { this.mSelectedItem = selectedItem; return this; } // an ListView to use within the drawer :D protected ListView mListView; /** * Set the list which is added within the slider * * @param listView * @return */ public Drawer withListView(ListView listView) { this.mListView = listView; return this; } // an adapter to use for the list protected BaseDrawerAdapter mAdapter; /** * Set the adapter to be used with the list * * @param adapter * @return */ public Drawer withAdapter(BaseDrawerAdapter adapter) { this.mAdapter = adapter; return this; } // list in drawer protected ArrayList<IDrawerItem> mDrawerItems; /** * set the arrayList of DrawerItems for the drawer * * @param drawerItems * @return */ public Drawer withDrawerItems(ArrayList<IDrawerItem> drawerItems) { this.mDrawerItems = drawerItems; return this; } /** * add single ore more DrawerItems to the Drawer * * @param drawerItems * @return */ public Drawer addDrawerItems(IDrawerItem... drawerItems) { if (this.mDrawerItems == null) { this.mDrawerItems = new ArrayList<>(); } if (drawerItems != null) { Collections.addAll(this.mDrawerItems, drawerItems); } return this; } // close drawer on click protected boolean mCloseOnClick = true; /** * set if the drawer should autoClose if an item is clicked * * @param closeOnClick * @return this */ public Drawer withCloseOnClick(boolean closeOnClick) { this.mCloseOnClick = closeOnClick; return this; } // delay drawer close to prevent lag protected int mDelayOnDrawerClose = 150; /** * set the delay for the drawer close operation * this is a small hack to improve the responsivness if you open a new activity within the drawer onClick * else you will see some lag * you can disable this by passing -1 * * @param delayOnDrawerClose -1 to disable * @return this */ public Drawer withDelayOnDrawerClose(int delayOnDrawerClose) { this.mDelayOnDrawerClose = delayOnDrawerClose; return this; } // onDrawerListener protected OnDrawerListener mOnDrawerListener; /** * set the drawerListener * * @param onDrawerListener * @return this */ public Drawer withOnDrawerListener(OnDrawerListener onDrawerListener) { this.mOnDrawerListener = onDrawerListener; return this; } // onDrawerItemClickListeners protected OnDrawerItemClickListener mOnDrawerItemClickListener; /** * set the DrawerItemClickListener * * @param onDrawerItemClickListener * @return */ public Drawer withOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) { this.mOnDrawerItemClickListener = onDrawerItemClickListener; return this; } // onDrawerItemClickListeners protected OnDrawerItemLongClickListener mOnDrawerItemLongClickListener; /** * set the DrawerItemLongClickListener * * @param onDrawerItemLongClickListener * @return */ public Drawer withOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) { this.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener; return this; } // onDrawerItemClickListeners protected OnDrawerItemSelectedListener mOnDrawerItemSelectedListener; /** * set the ItemSelectedListener * * @param onDrawerItemSelectedListener * @return */ public Drawer withOnDrawerItemSelectedListener(OnDrawerItemSelectedListener onDrawerItemSelectedListener) { this.mOnDrawerItemSelectedListener = onDrawerItemSelectedListener; return this; } // savedInstance to restore state protected Bundle mSavedInstance; /** * create the drawer with the values of a savedInstance * * @param savedInstance * @return */ public Drawer withSavedInstance(Bundle savedInstance) { this.mSavedInstance = savedInstance; return this; } /** * Build everything and get a Result * * @return */ public Result build() { if (mUsed) { throw new RuntimeException("you must not reuse a Drawer builder"); } if (mActivity == null) { throw new RuntimeException("please pass an activity"); } //set that this builder was used. now you have to create a new one mUsed = true; // if the user has not set a drawerLayout use the default one :D if (mDrawerLayout == null) { withDrawerLayout(-1); } //get the drawer root ViewGroup drawerContentRoot = (ViewGroup) mDrawerLayout.getChildAt(0); //get the content view View contentView = mRootView.getChildAt(0); // remove the contentView mRootView.removeView(contentView); //add the contentView to the drawer content frameLayout drawerContentRoot.addView(contentView, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT )); //add the drawerLayout to the root mRootView.addView(mDrawerLayout, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT )); // create the ActionBarDrawerToggle if not set and enabled and if we have a toolbar if (mActionBarDrawerToggleEnabled && mActionBarDrawerToggle == null && mToolbar != null) { this.mActionBarDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerOpened(View drawerView) { if (mOnDrawerListener != null) { mOnDrawerListener.onDrawerOpened(drawerView); } super.onDrawerOpened(drawerView); } @Override public void onDrawerClosed(View drawerView) { if (mOnDrawerListener != null) { mOnDrawerListener.onDrawerClosed(drawerView); } super.onDrawerClosed(drawerView); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { if (!mAnimateActionBarDrawerToggle) { super.onDrawerSlide(drawerView, 0); } else { super.onDrawerSlide(drawerView, slideOffset); } } }; this.mActionBarDrawerToggle.syncState(); } //handle the ActionBarDrawerToggle if (mActionBarDrawerToggle != null) { mDrawerLayout.setDrawerListener(mActionBarDrawerToggle); } // get the slider view mSliderLayout = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false); // get the layout params DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams(); // if we've set a custom gravity set it if (mDrawerGravity != null) { params.gravity = mDrawerGravity; } // if this is a drawer from the right, change the margins :D params = processDrawerLayoutParams(params); // set the new layout params mSliderLayout.setLayoutParams(params); // set the background if (mSliderBackgroundColor != -1) { mSliderLayout.setBackgroundColor(mSliderBackgroundColor); } else if (mSliderBackgroundColorRes != -1) { mSliderLayout.setBackgroundColor(mActivity.getResources().getColor(mSliderBackgroundColorRes)); } // add the slider to the drawer mDrawerLayout.addView(mSliderLayout, 1); //create the content createContent(); //forget the reference to the activity mActivity = null; //create the result object Result result = new Result(this); //set the drawer for the accountHeader if set if (mAccountHeader != null) { mAccountHeader.setDrawer(result); } return result; } /** * the builder method to append a new drawer to an existing Drawer * * @param result the Drawer.Result of an existing Drawer * @return */ public Result append(Result result) { if (mUsed) { throw new RuntimeException("you must not reuse a Drawer builder"); } if (mDrawerGravity == null) { throw new RuntimeException("please set the gravity for the drawer"); } //set that this builder was used. now you have to create a new one mUsed = true; //get the drawer layout from the previous drawer mDrawerLayout = result.getDrawerLayout(); // get the slider view mSliderLayout = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false); // get the layout params DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams(); // set the gravity of this drawerGravity params.gravity = mDrawerGravity; // if this is a drawer from the right, change the margins :D params = processDrawerLayoutParams(params); // set the new params mSliderLayout.setLayoutParams(params); // add the slider to the drawer mDrawerLayout.addView(mSliderLayout, 1); //create the content createContent(); //forget the reference to the activity mActivity = null; return new Result(this); } /** * the helper method to create the content for the drawer */ private void createContent() { // if we have an adapter (either by defining a custom one or the included one add a list :D if (mListView == null) { mListView = new ListView(mActivity); mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); mListView.setDivider(null); mListView.setDrawSelectorOnTop(true); mListView.setClipToPadding(false); if (mTranslucentStatusBar) { mListView.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0); } } LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); params.weight = 1f; mSliderLayout.addView(mListView, params); // initialize list if there is an adapter or set items if (mDrawerItems != null && mAdapter == null) { mAdapter = new DrawerAdapter(mActivity, mDrawerItems); } //sticky footer view if (mStickyFooterView != null) { mSliderLayout.addView(mStickyFooterView); } //use the AccountHeader if set if (mAccountHeader != null) { mHeaderView = mAccountHeader.getView(); } // set the header (do this before the setAdapter because some devices will crash else if (mHeaderView != null) { if (mListView == null) { throw new RuntimeException("can't use a headerView without a listView"); } if (mHeaderDivider) { LinearLayout headerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_header, mListView, false); headerContainer.addView(mHeaderView, 0); mListView.addHeaderView(headerContainer, null, mHeaderClickable); mListView.setPadding(0, 0, 0, 0); //link the view including the container to the headerView field mHeaderView = headerContainer; } else { mListView.addHeaderView(mHeaderView, null, mHeaderClickable); mListView.setPadding(0, 0, 0, 0); } } // set the footer (do this before the setAdapter because some devices will crash else if (mFooterView != null) { if (mListView == null) { throw new RuntimeException("can't use a footerView without a listView"); } if (mFooterDivider) { LinearLayout footerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_footer, mListView, false); footerContainer.addView(mFooterView, 1); mListView.addFooterView(footerContainer, null, mFooterClickable); //link the view including the container to the footerView field mFooterView = footerContainer; } else { mListView.addFooterView(mFooterView, null, mFooterClickable); } } //after adding the header do the setAdapter and set the selection if (mAdapter != null) { //set the adapter on the listView mListView.setAdapter(mAdapter); //predefine selection (should be the first element if (mListView != null && (mSelectedItem + mHeaderOffset) > -1) { mListView.setSelection(mSelectedItem + mHeaderOffset); mListView.setItemChecked(mSelectedItem + mHeaderOffset, true); mCurrentSelection = mSelectedItem; } } // add the onDrawerItemClickListener if set mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { IDrawerItem i = getDrawerItem(position, true); if (mCloseOnClick) { if (mDelayOnDrawerClose > -1) { new Handler().postDelayed(new Runnable() { @Override public void run() { mDrawerLayout.closeDrawers(); } }, mDelayOnDrawerClose); } else { mDrawerLayout.closeDrawers(); } } if (i != null && i instanceof Checkable && !((Checkable) i).isCheckable()) { mListView.setSelection(mCurrentSelection + mHeaderOffset); mListView.setItemChecked(mCurrentSelection + mHeaderOffset, true); } else { mCurrentSelection = position - mHeaderOffset; } if (mOnDrawerItemClickListener != null) { mOnDrawerItemClickListener.onItemClick(parent, view, position, id, i); } } }); // add the onDrawerItemLongClickListener if set if (mOnDrawerItemLongClickListener != null) { mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return mOnDrawerItemLongClickListener.onItemLongClick(parent, view, position, id, getDrawerItem(position, true)); } }); } // add the onDrawerItemSelectedListener if set if (mOnDrawerItemSelectedListener != null) { mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mOnDrawerItemSelectedListener.onItemSelected(parent, view, position, id, getDrawerItem(position, true)); mCurrentSelection = position - mHeaderOffset; } @Override public void onNothingSelected(AdapterView<?> parent) { mOnDrawerItemSelectedListener.onNothingSelected(parent); } }); } if (mListView != null) { mListView.smoothScrollToPosition(0); } // try to restore all saved values again if (mSavedInstance != null) { int selection = mSavedInstance.getInt(BUNDLE_SELECTION, -1); if (selection != -1) { //predefine selection (should be the first element if (mListView != null && (selection) > -1) { mListView.setSelection(selection); mListView.setItemChecked(selection, true); mCurrentSelection = selection - mHeaderOffset; } } } // call initial onClick event to allow the dev to init the first view if (mFireInitialOnClick && mOnDrawerItemClickListener != null) { mOnDrawerItemClickListener.onItemClick(null, null, mCurrentSelection, mCurrentSelection, getDrawerItem(mCurrentSelection, false)); } } /** * get the drawerItem at a specific position * * @param position * @return */ private IDrawerItem getDrawerItem(int position, boolean includeOffset) { if (includeOffset) { if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) { return mDrawerItems.get(position - mHeaderOffset); } } else { if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) { return mDrawerItems.get(position); } } return null; } /** * check if the item is within the bounds of the list * * @param position * @param includeOffset * @return */ private boolean checkDrawerItem(int position, boolean includeOffset) { if (includeOffset) { if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) { return true; } } else { if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) { return true; } } return false; } /** * helper to extend the layoutParams of the drawer * * @param params * @return */ private DrawerLayout.LayoutParams processDrawerLayoutParams(DrawerLayout.LayoutParams params) { if (mDrawerGravity != null && (mDrawerGravity == Gravity.RIGHT || mDrawerGravity == Gravity.END)) { params.rightMargin = 0; if (Build.VERSION.SDK_INT >= 17) { params.setMarginEnd(0); } params.leftMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin); if (Build.VERSION.SDK_INT >= 17) { params.setMarginEnd(mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin)); } } if (mTranslucentActionBarCompatibility) { TypedValue tv = new TypedValue(); if (mActivity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { params.topMargin = TypedValue.complexToDimensionPixelSize(tv.data, mActivity.getResources().getDisplayMetrics()); } } if (mDrawerWidth > -1) { params.width = mDrawerWidth; } else { params.width = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_width); } return params; } public static class Result { private final Drawer mDrawer; private FrameLayout mContentView; /** * the protected Constructor for the result * * @param drawer */ protected Result(Drawer drawer) { this.mDrawer = drawer; } /** * get the drawerLayout of the current drawer * * @return */ public DrawerLayout getDrawerLayout() { return this.mDrawer.mDrawerLayout; } /** * open the drawer */ public void openDrawer() { if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) { mDrawer.mDrawerLayout.openDrawer(mDrawer.mSliderLayout); } } /** * close the drawer */ public void closeDrawer() { if (mDrawer.mDrawerLayout != null) { mDrawer.mDrawerLayout.closeDrawers(); } } /** * get the current state if the drawer is open * * @return */ public boolean isDrawerOpen() { if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) { return mDrawer.mDrawerLayout.isDrawerOpen(mDrawer.mSliderLayout); } return false; } /** * get the slider layout of the current drawer * * @return */ public LinearLayout getSlider() { return mDrawer.mSliderLayout; } /** * get the cootainer frameLayout of the current drawer * * @return */ public FrameLayout getContent() { if (mContentView == null) { mContentView = (FrameLayout) this.mDrawer.mDrawerLayout.findViewById(R.id.content_layout); } return mContentView; } /** * get the listView of the current drawer * * @return */ public ListView getListView() { return mDrawer.mListView; } /** * get the BaseDrawerAdapter of the current drawer * * @return */ public BaseDrawerAdapter getAdapter() { return mDrawer.mAdapter; } /** * get all drawerItems of the current drawer * * @return */ public ArrayList<IDrawerItem> getDrawerItems() { return mDrawer.mDrawerItems; } /** * get the Header View if set else NULL * * @return */ public View getHeader() { return mDrawer.mHeaderView; } /** * method to replace a previous set header * * @param view */ public void setHeader(View view) { if (getListView() != null) { BaseDrawerAdapter adapter = getAdapter(); getListView().setAdapter(null); if (getHeader() != null) { getListView().removeHeaderView(getHeader()); } getListView().addHeaderView(view); getListView().setAdapter(adapter); } } /** * get the Footer View if set else NULL * * @return */ public View getFooter() { return mDrawer.mFooterView; } /** * get the StickyFooter View if set else NULL * * @return */ public View getStickyFooter() { return mDrawer.mStickyFooterView; } /** * get the ActionBarDrawerToggle * * @return */ public ActionBarDrawerToggle getActionBarDrawerToggle() { return mDrawer.mActionBarDrawerToggle; } /** * calculates the position of an drawerItem. searching by it's identifier * * @param drawerItem * @return */ public int getPositionFromIdentifier(IDrawerItem drawerItem) { return getPositionFromIdentifier(drawerItem.getIdentifier()); } /** * calculates the position of an drawerItem. searching by it's identifier * * @param identifier * @return */ public int getPositionFromIdentifier(int identifier) { if (identifier > 0) { if (mDrawer.mDrawerItems != null) { int position = 0; for (IDrawerItem i : mDrawer.mDrawerItems) { if (i.getIdentifier() == identifier) { return position; } position = position + 1; } } } else { throw new RuntimeException("the item requires a unique identifier to use this method"); } return -1; } /** * get the current selection * * @return */ public int getCurrentSelection() { return mDrawer.mCurrentSelection; } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param identifier */ public void setSelectionByIdentifier(int identifier) { setSelection(getPositionFromIdentifier(identifier), true); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param identifier * @param fireOnClick */ public void setSelectionByIdentifier(int identifier, boolean fireOnClick) { setSelection(getPositionFromIdentifier(identifier), fireOnClick); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param drawerItem */ public void setSelection(IDrawerItem drawerItem) { setSelection(getPositionFromIdentifier(drawerItem), true); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param drawerItem * @param fireOnClick */ public void setSelection(IDrawerItem drawerItem, boolean fireOnClick) { setSelection(getPositionFromIdentifier(drawerItem), fireOnClick); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view! * * @param position the position to select */ public void setSelection(int position) { setSelection(position, true); } /** * set the current selection in the drawer * NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; * * @param position * @param fireOnClick */ public void setSelection(int position, boolean fireOnClick) { if (mDrawer.mListView != null) { mDrawer.mListView.setSelection(position + mDrawer.mHeaderOffset); mDrawer.mListView.setItemChecked(position + mDrawer.mHeaderOffset, true); if (fireOnClick && mDrawer.mOnDrawerItemClickListener != null) { mDrawer.mOnDrawerItemClickListener.onItemClick(null, null, position, position, mDrawer.getDrawerItem(position, false)); } mDrawer.mCurrentSelection = position; } } /** * update a specific drawer item :D * automatically identified by its id * * @param drawerItem */ public void updateItem(IDrawerItem drawerItem) { updateItem(drawerItem, getPositionFromIdentifier(drawerItem)); } /** * Update a drawerItem at a specific position * * @param drawerItem * @param position */ public void updateItem(IDrawerItem drawerItem, int position) { if (mDrawer.checkDrawerItem(position, false)) { mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.dataUpdated(); } } /** * Add a drawerItem at the end * * @param drawerItem */ public void addItem(IDrawerItem drawerItem) { if (mDrawer.mDrawerItems != null) { mDrawer.mDrawerItems.add(drawerItem); mDrawer.mAdapter.dataUpdated(); } } /** * Add a drawerItem at a specific position * * @param drawerItem * @param position */ public void addItem(IDrawerItem drawerItem, int position) { if (mDrawer.mDrawerItems != null) { mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.dataUpdated(); } } /** * Remove a drawerItem at a specific position * * @param position */ public void removeItem(int position) { if (mDrawer.checkDrawerItem(position, false)) { mDrawer.mDrawerItems.remove(position); mDrawer.mAdapter.dataUpdated(); } } /** * Removes all items from drawer */ public void removeAllItems() { mDrawer.mDrawerItems.clear(); mDrawer.mAdapter.dataUpdated(); } /** * add new Items to the current DrawerItem List * * @param drawerItems */ public void addItems(IDrawerItem... drawerItems) { if (mDrawer.mDrawerItems != null) { Collections.addAll(mDrawer.mDrawerItems, drawerItems); mDrawer.mAdapter.dataUpdated(); } } /** * Replace the current DrawerItems with a new ArrayList of items * * @param drawerItems */ public void setItems(ArrayList<IDrawerItem> drawerItems) { mDrawer.mDrawerItems = drawerItems; mDrawer.mAdapter.setDrawerItems(mDrawer.mDrawerItems); mDrawer.mAdapter.dataUpdated(); } /** * Update the name of a drawer item if its an instance of nameable * * @param nameRes * @param position */ public void updateName(int nameRes, int position) { if (mDrawer.checkDrawerItem(position, false)) { IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position); if (drawerItem instanceof Nameable) { ((Nameable) drawerItem).setNameRes(nameRes); } mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.notifyDataSetChanged(); } } /** * Update the name of a drawer item if its an instance of nameable * * @param name * @param position */ public void updateName(String name, int position) { if (mDrawer.checkDrawerItem(position, false)) { IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position); if (drawerItem instanceof Nameable) { ((Nameable) drawerItem).setName(name); } mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.notifyDataSetChanged(); } } /** * Update the badge of a drawer item if its an instance of badgeable * * @param badge * @param position */ public void updateBadge(String badge, int position) { if (mDrawer.checkDrawerItem(position, false)) { IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position); if (drawerItem instanceof Badgeable) { ((Badgeable) drawerItem).setBadge(badge); } mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.notifyDataSetChanged(); } } /** * Update the icon of a drawer item if its an instance of iconable * * @param icon * @param position */ public void updateIcon(Drawable icon, int position) { if (mDrawer.checkDrawerItem(position, false)) { IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position); if (drawerItem instanceof Iconable) { ((Iconable) drawerItem).setIcon(icon); } mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.notifyDataSetChanged(); } } /** * Update the icon of a drawer item if its an instance of iconable * * @param icon * @param position */ public void updateIcon(IIcon icon, int position) { if (mDrawer.checkDrawerItem(position, false)) { IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position); if (drawerItem instanceof Iconable) { ((Iconable) drawerItem).setIIcon(icon); } mDrawer.mDrawerItems.set(position, drawerItem); mDrawer.mAdapter.notifyDataSetChanged(); } } /** * setter for the OnDrawerItemClickListener * * @param onDrawerItemClickListener */ public void setOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) { mDrawer.mOnDrawerItemClickListener = onDrawerItemClickListener; } /** * method to get the OnDrawerItemClickListener * * @return */ public OnDrawerItemClickListener getOnDrawerItemClickListener() { return mDrawer.mOnDrawerItemClickListener; } /** * setter for the OnDrawerItemLongClickListener * * @param onDrawerItemLongClickListener */ public void setOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) { mDrawer.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener; } /** * method to get the OnDrawerItemLongClickListener * * @return */ public OnDrawerItemLongClickListener getOnDrawerItemLongClickListener() { return mDrawer.mOnDrawerItemLongClickListener; } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState * @return */ public Bundle saveInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { if (getListView() != null) { savedInstanceState.putInt(BUNDLE_SELECTION, mDrawer.mCurrentSelection); } } return savedInstanceState; } } public interface OnDrawerItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem); } public interface OnDrawerItemLongClickListener { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem); } public interface OnDrawerListener { public void onDrawerOpened(View drawerView); public void onDrawerClosed(View drawerView); } public interface OnDrawerItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem); public void onNothingSelected(AdapterView<?> parent); } }
package com.witchworks.common.item.tool; import com.witchworks.api.helper.IModelRegister; import com.witchworks.client.handler.ModelHandler; import com.witchworks.common.core.WitchWorksCreativeTabs; import com.witchworks.common.core.helper.ItemNBTHelper; import com.witchworks.common.item.ModItems; import com.witchworks.common.item.ModMaterials; import com.witchworks.common.lib.LibItemName; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.*; import net.minecraft.entity.passive.EntityBat; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.util.DamageSource; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Random; // Uses code from Botania public class ItemAthame extends ItemSword implements IModelRegister { public ItemAthame() { super(ModMaterials.TOOL_RITUAL); setRegistryName(LibItemName.ATHAME); setUnlocalizedName(LibItemName.ATHAME); setCreativeTab(WitchWorksCreativeTabs.ITEMS_CREATIVE_TAB); MinecraftForge.EVENT_BUS.register(this); } @Override public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { if (!target.world.isRemote) if (target instanceof EntityEnderman && attacker instanceof EntityPlayer) { target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) attacker), 20); stack.damageItem(50, attacker); } else { stack.damageItem(1, attacker); } return true; } @SubscribeEvent public void onEntityDrops(LivingDropsEvent event) { if (event.isRecentlyHit() && event.getSource().getTrueSource() != null && event.getSource().getTrueSource() instanceof EntityPlayer) { ItemStack weapon = ((EntityPlayer) event.getSource().getTrueSource()).getHeldItemMainhand(); if (!weapon.isEmpty() && weapon.getItem() == this) { Random rand = event.getEntityLiving().world.rand; int looting = EnchantmentHelper.getEnchantmentLevel(Enchantments.LOOTING, weapon); if (event.getEntityLiving() instanceof AbstractSkeleton && rand.nextInt(26) <= 3 + looting) addDrop(event, new ItemStack(Items.SKULL, 1, event.getEntityLiving() instanceof EntityWitherSkeleton ? 1 : 0)); else if (event.getEntityLiving() instanceof EntityZombie && !(event.getEntityLiving() instanceof EntityPigZombie) && rand.nextInt(26) <= 2 + 2 * looting) addDrop(event, new ItemStack(Items.SKULL, 1, 2)); else if (event.getEntityLiving() instanceof EntityCreeper && rand.nextInt(26) <= 2 + 2 * looting) addDrop(event, new ItemStack(Items.SKULL, 1, 4)); else if (event.getEntityLiving() instanceof EntityBat) addDrop(event, new ItemStack(ModItems.wool_of_bat, 3)); else if (event.getEntityLiving() instanceof EntityWolf) addDrop(event, new ItemStack(ModItems.tongue_of_dog, 1)); else if (event.getEntityLiving() instanceof EntityPlayer && rand.nextInt(11) <= 1 + looting) { ItemStack stack = new ItemStack(Items.SKULL, 1, 3); ItemNBTHelper.setString(stack, "SkullOwner", event.getEntityLiving().getName()); addDrop(event, stack); } } } } private void addDrop(LivingDropsEvent event, ItemStack drop) { EntityItem entityitem = new EntityItem(event.getEntityLiving().world, event.getEntityLiving().posX, event.getEntityLiving().posY, event.getEntityLiving().posZ, drop); entityitem.setPickupDelay(10); event.getDrops().add(entityitem); } @SideOnly(Side.CLIENT) @Override public void registerModel() { ModelHandler.registerModel(this, 0); } }
package com.qiniu.android.common; import android.util.Log; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public final class FixedZone extends Zone { public static final Zone zone0 = new FixedZone(new String[]{ "upload.qiniup.com", "upload-jjh.qiniup.com", "upload-xs.qiniup.com", "up.qiniup.com", "up-jjh.qiniup.com", "up-xs.qiniup.com", "upload.qbox.me", "up.qbox.me" }); public static final Zone zone1 = new FixedZone(new String[]{ "upload-z1.qiniup.com", "up-z1.qiniup.com", "upload-z1.qbox.me", "up-z1.qbox.me" }); public static final Zone zone2 = new FixedZone(new String[]{ "upload-z2.qiniup.com", "upload-dg.qiniup.com", "upload-fs.qiniup.com", "up-z2.qiniup.com", "up-dg.qiniup.com", "up-fs.qiniup.com", "upload-z2.qbox.me", "up-z2.qbox.me" }); public static final Zone zoneNa0 = new FixedZone(new String[]{ "upload-na0.qiniup.com", "up-na0.qiniup.com", "upload-na0.qbox.me", "up-na0.qbox.me" }); public static final Zone zoneAs0 = new FixedZone(new String[]{ "upload-as0.qiniup.com","up-as0.qiniup.com", "upload-as0.qbox.me","up-as0.qbox.me" }); private ZoneInfo zoneInfo; public FixedZone(ZoneInfo zoneInfo) { this.zoneInfo = zoneInfo; } public FixedZone(String[] upDomains) { this.zoneInfo = createZoneInfo(upDomains); } public static ZoneInfo createZoneInfo(String[] upDomains) { List<String> upDomainsList = new ArrayList<String>(); Map<String, Long> upDomainsMap = new ConcurrentHashMap<String, Long>(); for (String domain : upDomains) { upDomainsList.add(domain); upDomainsMap.put(domain, 0L); } return new ZoneInfo(0, upDomainsList, upDomainsMap); } @Override public synchronized String upHost(String upToken, boolean useHttps, String frozenDomain) { String upHost = this.upHost(this.zoneInfo, useHttps, frozenDomain); for (Map.Entry<String, Long> entry : this.zoneInfo.upDomainsMap.entrySet()) { Log.d("Qiniu.FixedZone", entry.getKey() + ", " + entry.getValue()); } return upHost; } @Override public void preQuery(String token, QueryHandler complete) { complete.onSuccess(); } @Override public boolean preQuery(String token) { return true; } @Override public synchronized void frozenDomain(String upHostUrl) { if (upHostUrl != null) { URI uri = URI.create(upHostUrl); //frozen domain String frozenDomain = uri.getHost(); zoneInfo.frozenDomain(frozenDomain); } } }
package cz.tomasdvorak.eet.client.dto; import cz.etrzby.xml.OdpovedType; import cz.etrzby.xml.TrzbaType; import cz.tomasdvorak.eet.client.utils.StringUtils; import javax.xml.bind.DatatypeConverter; /** * Communication result holding all response data and additionally also all request data. * There are defined some additional helper methods for easier access to usual fields (FIK, PKP, BKP) */ public class SubmitResult extends OdpovedType { private final TrzbaType request; public SubmitResult(final TrzbaType request, final OdpovedType response) { super(); setChyba(response.getChyba()); setHlavicka(response.getHlavicka()); setPotvrzeni(response.getPotvrzeni()); withVarovani(response.getVarovani()); this.request = request; } /** * Get the original request to this response */ public TrzbaType getRequest() { return request; } /** * Utility method for easier access to BKP (Taxpayer's Security Code) security code * @return BKP code from the request */ public String getBKP() { return getHlavicka().getBkp(); } /** * Utility method for easier access to PKP (Taxpayer's Signature Code) security code * @return PKP code, encoded as Base64, suitable for printing on the receipt in case of communication failure. */ public String getPKP() { return StringUtils.toBase64(request.getKontrolniKody().getPkp().getValue()); } /** * Utility method for easier access to FIK (Fiscal Identification Code) * @return FIK code from the response. May be {@code null}, if the response contains errors */ public String getFik() { return getPotvrzeni() == null ? null : getPotvrzeni().getFik(); } }
package de.mxro.metrics.internal; import de.mxro.async.Async; import de.mxro.async.Deferred; import de.mxro.async.Promise; import de.mxro.async.callbacks.ValueCallback; import de.mxro.metrics.MetricsNode; import de.mxro.metrics.helpers.MetricsData; import de.mxro.metrics.helpers.RecordOperation; public class UnsafeMetricsNode implements MetricsNode { private final MetricsData data; @Override public void record(final RecordOperation op) { op.perform(data); } public UnsafeMetricsNode() { super(); this.data = new MetricsDataImpl(); } @Override public Promise<Object> retrieve(final String id) { return retrieve(id, Object.class); } @Override public void retrieve(final String id, final ValueCallback<Object> cb) { retrieve(id, Object.class); } @Override public <T> Promise<T> retrieve(final String id, final Class<T> type) { return Async.promise(new Deferred<T>() { @Override public void get(final ValueCallback<T> callback) { retrieve(id, type, callback); } }); } @SuppressWarnings("unchecked") @Override public <T> void retrieve(final String id, final Class<T> type, final ValueCallback<T> cb) { if (type.equals(Object.class)) { cb.onSuccess((T) data.get(id)); return; } cb.onSuccess(data.get(id, type)); } }
package de.tblsoft.solr.pipeline.filter; import de.tblsoft.solr.pipeline.AbstractFilter; import de.tblsoft.solr.pipeline.bean.Document; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GrepFilter extends AbstractFilter { private String fieldName; private Pattern pattern; private boolean shouldMatch = true; @Override public void init() { fieldName = getProperty("fieldName", null); verify(fieldName, "For the GrepFilter a fieldName must be defined."); String patternString = getProperty("pattern", null); verify(patternString, "For the GrepFilter a pattern must be defined."); pattern = Pattern.compile(patternString); shouldMatch = getPropertyAsBoolean("shouldMatch", true); super.init(); } @Override public void document(Document document) { List<String> values = document.getFieldValues(fieldName, new ArrayList<String>()); for(String value: values) { value = value.replaceAll("\\r\\n|\\r|\\n", " "); Matcher m = pattern.matcher(value); if(shouldMatch && !m.matches()) { //document.deleteField(fieldName); } else if (!shouldMatch && m.matches()) { //document.deleteField(fieldName); } else { super.document(document); } } } }
package graphql.schema; import graphql.PublicApi; /** * Named schema elements that contain input type information. * * * @see graphql.schema.GraphQLInputType * @see graphql.schema.GraphQLInputObjectField * @see graphql.schema.GraphQLArgument */ @PublicApi public interface GraphQLInputValueDefinition extends GraphQLDirectiveContainer { <T extends GraphQLInputType> T getType(); }
package io.github.olyutorskii.doubdabc; import java.io.IOException; import java.io.Writer; import java.nio.BufferOverflowException; import java.nio.CharBuffer; import java.nio.ReadOnlyBufferException; /** * BCD Character sequence holder. * * <p>It has {@link java.lang.CharSequence} API. * * <p>There is some API for character-output classes. */ public class BcdSequence implements CharSequence{ private static final int ARABIC_UC_MASK = 0b0011_0000; private final BcdRegister decimal; private final int[] intBuf; private final char[] charBuf; /** * Constructor. * * @param decimal BCD register * @throws NullPointerException argument is null */ public BcdSequence(BcdRegister decimal) throws NullPointerException{ super(); this.decimal = decimal; int digits = this.decimal.getMaxDigits(); this.intBuf = new int[digits]; this.charBuf = new char[digits]; return; } /** * Write digits to Appendable. * * @param app output * @return digits length * @throws IOException If an I/O error occurs */ public int flushDigitTo(Appendable app) throws IOException{ int length = buildChar(); for(int idx = 0; idx < length; idx++){ char decimalCh = this.charBuf[idx]; app.append(decimalCh); } return length; } /** * Write digits to CharBuffer. * * @param cBuf output * @return digits length * @throws BufferOverflowException * If buffer's current position is not smaller than its limit * @throws ReadOnlyBufferException * If buffer is read-only */ public int flushDigitTo(CharBuffer cBuf) throws BufferOverflowException, ReadOnlyBufferException{ int length = buildChar(); cBuf.put(this.charBuf, 0, length); return length; } /** * Write digits to Writer. * * @param writer output * @return digits length * @throws IOException If an I/O error occurs */ public int flushDigitTo(Writer writer) throws IOException{ int length = buildChar(); writer.write(this.charBuf, 0, length); return length; } /** * Write digits to StringBuffer. * * @param buf output * @return digits length */ public int flushDigitTo(StringBuffer buf){ int length = buildChar(); buf.append(this.charBuf, 0, length); return length; } /** * Write digits to StringBuilder. * * @param buf output * @return digits length */ public int flushDigitTo(StringBuilder buf){ int length = buildChar(); buf.append(this.charBuf, 0, length); return length; } /** * Return digits columns. * * <p>There is no sign character. * * @return digits columns */ @Override public int length(){ int result = this.decimal.getPrecision(); return result; } /** * Return each digit character. * * @param index digit position starting 0 * @return digit character ('0' to '9') * @throws IndexOutOfBoundsException * Argument is negative, or, not less than <code>length()</code> */ @Override public char charAt(int index) throws IndexOutOfBoundsException{ int precision = this.decimal.getPrecision(); if(index < 0 || precision <= index) throw new IndexOutOfBoundsException(); int digitPos = precision - index - 1; int digit = this.decimal.getDigit(digitPos); // map [0 - 9](int) to ['0' - '9'](char) char result = (char)( digit | ARABIC_UC_MASK ); return result; } /** * Return fixed-ranged subsequence. * * @param start start index * @param end end index * @return ranged sub-sequence * @throws IndexOutOfBoundsException * <code>start</code> is negative, * <code>end</code> is less than <code>start</code>, * or <code>end</code> is greater than length() */ @Override public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException{ if(start < 0 || end < start) throw new IndexOutOfBoundsException(); int precision = this.decimal.getPrecision(); if(end > precision) throw new IndexOutOfBoundsException(); copyChar(start, end); String result = new String(this.charBuf, start, end - start); return result; } /** * Return fixed string text. * * @return fixed string */ @Override public String toString(){ int precision = this.decimal.getPrecision(); buildChar(); String result = new String(this.charBuf, 0, precision); return result; } /** * Build char array data. * @return digits length */ private int buildChar(){ int precision = this.decimal.getPrecision(); int result = copyChar(0, precision); return result; } /** * Build ranged char array data. * @param start start * @param end end * @return digits length */ private int copyChar(int start, int end){ int length = end - start; this.decimal.toIntArray(this.intBuf, 0); for(int idx = start; idx < end; idx++){ int digit = this.intBuf[idx]; // map [0 - 9](int) to ['0' - '9'](char) char decimalCh = (char)( digit | ARABIC_UC_MASK ); this.charBuf[idx] = decimalCh; } return length; } }
package org.noear.weed.dialect; import org.noear.weed.DbContext; import org.noear.weed.GetHandler; import org.noear.weed.IDataItem; import org.noear.weed.SQLBuilder; import org.noear.weed.ext.Fun1; import org.noear.weed.utils.StringUtils; import java.sql.Clob; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * OracleBETWEEN AND :: >= + <= * * @author noear * @since 3.2 * */ public class DbOracleDialect implements DbDialect { @Override public Object preChange(Object val) throws SQLException { if(val instanceof Clob){ Clob clob = ((Clob) val); return clob.getSubString(1,(int)clob.length()); } else{ return val; } } @Override public boolean excludeFormat(String str) { return str.startsWith("\""); } @Override public String schemaFormat(String sc) { return "\"" + sc + "\""; } @Override public String tableFormat(String tb) { String[] ss = tb.split("\\."); if(ss.length > 1){ return "\"" + ss[0] + "\".\"" + ss[1].toUpperCase() + "\""; }else{ return "\"" + ss[0].toUpperCase() + "\""; } } @Override public String columnFormat(String col) { String[] ss = col.split("\\."); if(ss.length > 1){ if("*".equals(ss[1])){ return "\"" + ss[0].toUpperCase() + "\".*"; }else { return "\"" + ss[0] + "\".\"" + ss[1].toUpperCase() + "\""; } }else{ return "\"" + ss[0].toUpperCase() + "\""; } } @Override public boolean supportsVariablePaging() { return true; } @Override public void selectPage(DbContext ctx, String table1, SQLBuilder sqlB, StringBuilder orderBy, int start, int size) { sqlB.insert(0, "SELECT t.* FROM (SELECT ROWNUM WD3_ROW_NUM,x.* FROM (SELECT "); if (orderBy != null) { sqlB.append(orderBy); } if (supportsVariablePaging()) { sqlB.append(") x WHERE ROWNUM<=?"); sqlB.append(") t WHERE t.WD3_ROW_NUM >?"); sqlB.paramS.add(start + size); sqlB.paramS.add(start); } else { sqlB.append(") x WHERE ROWNUM<=").append(start + size); sqlB.append(") t WHERE t.WD3_ROW_NUM >").append(start); } } @Override public void selectTop(DbContext ctx, String table1, SQLBuilder sqlB, StringBuilder orderBy, int size) { sqlB.insert(0,"SELECT "); if(sqlB.indexOf(" WHERE ") > 0){ sqlB.append(" AND"); }else{ sqlB.append(" WHERE"); } if(supportsVariablePaging()) { sqlB.append(" ROWNUM <= ?"); sqlB.paramS.add(size); }else{ sqlB.append(" ROWNUM <= ").append(size); } if(orderBy!=null){ sqlB.append(orderBy); } } @Override public <T extends GetHandler> boolean insertList(DbContext ctx, String table1, SQLBuilder sqlB, Fun1<Boolean, String> isSqlExpr, IDataItem cols, Collection<T> valuesList) { List<Object> args = new ArrayList<Object>(); StringBuilder sb = StringUtils.borrowBuilder(); sb.append(" INSERT ALL "); for(GetHandler gh: valuesList) { insertOne(ctx, sb, table1, isSqlExpr, cols, gh, args); } sb.append(" SELECT 1 from dual"); if(sb.length() < 20){ return false; } sqlB.append(StringUtils.releaseBuilder(sb), args.toArray()); return true; } private void insertOne(DbContext ctx, StringBuilder sb, String _table, Fun1<Boolean, String> isSqlExpr, IDataItem cols, GetHandler gh, List<Object> args){ sb.append(" INTO ").append(_table).append(" ("); for(String key : cols.keys()){ sb.append(ctx.formater().formatColumn(key)).append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(") "); sb.append("VALUES"); sb.append("("); for(String key : cols.keys()) { Object value = gh.get(key); if (value instanceof String) { String val2 = (String) value; if (isSqlExpr.run(val2)) { //SQL sb.append(val2.substring(1)).append(","); } else { sb.append("?,"); args.add(value); } } else { sb.append("?,"); args.add(value); } } sb.deleteCharAt(sb.length() - 1); sb.append(") \n"); } }
package io.luna.game.model.mobile; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.luna.game.GameService; import io.luna.game.model.Position; import io.luna.game.model.item.IndexedItem; import io.luna.game.model.mobile.attr.AttributeKey; import io.luna.game.model.mobile.attr.AttributeValue; import io.luna.net.codec.login.LoginResponse; import io.luna.util.GsonUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; public final class PlayerSerializer { /** * The asynchronous logger. */ private static final Logger LOGGER = LogManager.getLogger(); /** * The {@link Path} to all of the serialized {@link Player} data. */ private static final Path FILE_DIR = Paths.get("./data/saved_players"); /** * The {@link Player} being serialized or deserialized. */ private final Player player; /** * The {@link Path} to the character file. */ private final Path path; /** * Creates a new {@link PlayerSerializer}. * * @param player The {@link Player} being serialized or deserialized. */ public PlayerSerializer(Player player) { this.player = player; path = FILE_DIR.resolve(player.getUsername() + ".toml"); } static { if (Files.notExists(FILE_DIR)) { try { Files.createDirectory(FILE_DIR); } catch (Exception e) { LOGGER.catching(e); } } } /** * Attempts to serialize all persistent data for the {@link Player}. */ public void save() { Map<String, Object> mainTable = new LinkedHashMap<>(); mainTable.put("password", player.getPassword()); mainTable.put("position", player.getPosition()); mainTable.put("rights", player.getRights().name()); mainTable.put("running", player.getWalkingQueue().isRunning()); mainTable.put("appearance", player.getAppearance().toArray()); mainTable.put("inventory", player.getInventory().toIndexedArray()); mainTable.put("bank", player.getBank().toIndexedArray()); mainTable.put("equipment", player.getEquipment().toIndexedArray()); mainTable.put("skills", player.getSkills().toArray()); Map<String, Object> attrTable = new HashMap<>(); for (Entry<String, AttributeValue<?>> it : player.attributes) { AttributeKey<?> key = AttributeKey.ALIASES.get(it.getKey()); AttributeValue<?> value = it.getValue(); if (key.isPersistent()) { Map<String, Object> attrSubTable = new LinkedHashMap<>(); attrSubTable.put("type", key.getTypeName()); attrSubTable.put("value", value.get()); attrTable.put(key.getName(), attrSubTable); } } mainTable.put("attributes", attrTable); try (Writer writer = new FileWriter(path.toFile())) { writer.write(GsonUtils.GSON.toJson(mainTable)); } catch (IOException e) { LOGGER.catching(e); } } /** * Attempts to asynchronously serialize all persistent data for the {@link Player}. Returns a {@link ListenableFuture} * detailing the progress and result of the asynchronous task. * * @param service The {@link GameService} to use for asynchronous execution. * @return The {@link ListenableFuture} detailing progress and the result. */ public ListenableFuture<Void> asyncSave(GameService service) { return service.submit((Callable<Void>) () -> { save(); return null; }); } /** * Attempts to deserialize all persistent data for the {@link Player}. * * @param expectedPassword The expected password to be compared against the deserialized password. * @return The {@link LoginResponse} determined by the deserialization. */ public LoginResponse load(String expectedPassword) { if (!Files.exists(path)) { return LoginResponse.NORMAL; } try (Reader reader = new FileReader(path.toFile())) { JsonObject jsonReader = (JsonObject) new JsonParser().parse(reader); String password = jsonReader.get("password").getAsString(); if (!expectedPassword.equals(password)) { return LoginResponse.INVALID_CREDENTIALS; } Position position = GsonUtils.getAsType(jsonReader.get("position"), Position.class); player.setPosition(position); PlayerRights rights = PlayerRights.valueOf(jsonReader.get("rights").getAsString()); player.setRights(rights); boolean running = jsonReader.get("running").getAsBoolean(); player.getWalkingQueue().setRunning(running); int[] appearance = GsonUtils.getAsType(jsonReader.get("appearance"), int[].class); player.getAppearance().setValues(appearance); IndexedItem[] inventory = GsonUtils.getAsType(jsonReader.get("inventory"), IndexedItem[].class); player.getInventory().setIndexedItems(inventory); IndexedItem[] bank = GsonUtils.getAsType(jsonReader.get("bank"), IndexedItem[].class); player.getBank().setIndexedItems(bank); IndexedItem[] equipment = GsonUtils.getAsType(jsonReader.get("equipment"), IndexedItem[].class); player.getEquipment().setIndexedItems(equipment); Skill[] skills = GsonUtils.getAsType(jsonReader.get("skills"), Skill[].class); player.getSkills().setSkills(skills); JsonObject attr = jsonReader.get("attributes").getAsJsonObject(); for (Entry<String, JsonElement> it : attr.entrySet()) { JsonObject attrReader = it.getValue().getAsJsonObject(); Class<?> type = Class.forName(attrReader.get("type").getAsString()); Object data = GsonUtils.getAsType(attrReader.get("value"), type); player.attr().get(it.getKey()).set(data); } } catch (Exception e) { LOGGER.catching(e); return LoginResponse.COULD_NOT_COMPLETE_LOGIN; } return LoginResponse.NORMAL; } /** * Attempts to asynchronously deserialize all persistent data for the {@link Player}. Returns a {@link ListenableFuture} * detailing the progress and result of the asynchronous task. * * @param expectedPassword The expected password to be compared against the deserialized password. * @param service The {@link GameService} to use for asynchronous execution. * @return The {@link ListenableFuture} detailing progress and the result. */ public ListenableFuture<LoginResponse> asyncLoad(String expectedPassword, GameService service) { return service.submit(() -> load(expectedPassword)); } }
package com.airbnb.lottie; import android.content.Context; import android.content.res.Resources; import android.graphics.Rect; import androidx.annotation.Nullable; import androidx.annotation.RawRes; import androidx.annotation.RestrictTo; import androidx.annotation.WorkerThread; import androidx.collection.LongSparseArray; import androidx.collection.SparseArrayCompat; import android.util.Log; import com.airbnb.lottie.model.Font; import com.airbnb.lottie.model.FontCharacter; import com.airbnb.lottie.model.Marker; import com.airbnb.lottie.model.layer.Layer; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Logger; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; /** * After Effects/Bodymovin composition model. This is the serialized model from which the * animation will be created. * * To create one, use {@link LottieCompositionFactory}. * * It can be used with a {@link com.airbnb.lottie.LottieAnimationView} or * {@link com.airbnb.lottie.LottieDrawable}. */ public class LottieComposition { private final PerformanceTracker performanceTracker = new PerformanceTracker(); private final HashSet<String> warnings = new HashSet<>(); private Map<String, List<Layer>> precomps; private Map<String, LottieImageAsset> images; /** Map of font names to fonts */ private Map<String, Font> fonts; private List<Marker> markers; private SparseArrayCompat<FontCharacter> characters; private LongSparseArray<Layer> layerMap; private List<Layer> layers; // This is stored as a set to avoid duplicates. private Rect bounds; private float startFrame; private float endFrame; private float frameRate; /** * Used to determine if an animation can be drawn with hardware acceleration. */ private boolean hasDashPattern; /** * Counts the number of mattes and masks. Before Android switched to SKIA * for drawing in Oreo (API 28), using hardware acceleration with mattes and masks * was only faster until you had ~4 masks after which it would actually become slower. */ private int maskAndMatteCount = 0; @RestrictTo(RestrictTo.Scope.LIBRARY) public void init(Rect bounds, float startFrame, float endFrame, float frameRate, List<Layer> layers, LongSparseArray<Layer> layerMap, Map<String, List<Layer>> precomps, Map<String, LottieImageAsset> images, SparseArrayCompat<FontCharacter> characters, Map<String, Font> fonts, List<Marker> markers) { this.bounds = bounds; this.startFrame = startFrame; this.endFrame = endFrame; this.frameRate = frameRate; this.layers = layers; this.layerMap = layerMap; this.precomps = precomps; this.images = images; this.characters = characters; this.fonts = fonts; this.markers = markers; } @RestrictTo(RestrictTo.Scope.LIBRARY) public void addWarning(String warning) { Logger.warning(warning); warnings.add(warning); } @RestrictTo(RestrictTo.Scope.LIBRARY) public void setHasDashPattern(boolean hasDashPattern) { this.hasDashPattern = hasDashPattern; } @RestrictTo(RestrictTo.Scope.LIBRARY) public void incrementMatteOrMaskCount(int amount) { maskAndMatteCount += amount; } /** * Used to determine if an animation can be drawn with hardware acceleration. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public boolean hasDashPattern() { return hasDashPattern; } /** * Used to determine if an animation can be drawn with hardware acceleration. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public int getMaskAndMatteCount() { return maskAndMatteCount; } public ArrayList<String> getWarnings() { return new ArrayList<>(Arrays.asList(warnings.toArray(new String[warnings.size()]))); } @SuppressWarnings("WeakerAccess") public void setPerformanceTrackingEnabled(boolean enabled) { performanceTracker.setEnabled(enabled); } public PerformanceTracker getPerformanceTracker() { return performanceTracker; } @RestrictTo(RestrictTo.Scope.LIBRARY) public Layer layerModelForId(long id) { return layerMap.get(id); } @SuppressWarnings("WeakerAccess") public Rect getBounds() { return bounds; } @SuppressWarnings("WeakerAccess") public float getDuration() { return (long) (getDurationFrames() / frameRate * 1000); } public float getStartFrame() { return startFrame; } public float getEndFrame() { return endFrame; } public float getFrameRate() { return frameRate; } public List<Layer> getLayers() { return layers; } @RestrictTo(RestrictTo.Scope.LIBRARY) @Nullable public List<Layer> getPrecomps(String id) { return precomps.get(id); } public SparseArrayCompat<FontCharacter> getCharacters() { return characters; } public Map<String, Font> getFonts() { return fonts; } public List<Marker> getMarkers() { return markers; } @Nullable public Marker getMarker(String markerName) { int size = markers.size(); for (int i = 0; i < markers.size(); i++) { Marker marker = markers.get(i); if (marker.matchesName(markerName)) { return marker; } } return null; } public boolean hasImages() { return !images.isEmpty(); } @SuppressWarnings("WeakerAccess") public Map<String, LottieImageAsset> getImages() { return images; } public float getDurationFrames() { return endFrame - startFrame; } @Override public String toString() { final StringBuilder sb = new StringBuilder("LottieComposition:\n"); for (Layer layer : layers) { sb.append(layer.toString("\t")); } return sb.toString(); } /** * This will be removed in the next version of Lottie. {@link LottieCompositionFactory} has improved * API names, failure handlers, and will return in-progress tasks so you will never parse the same * animation twice in parallel. * * @see LottieCompositionFactory */ @Deprecated public static class Factory { private Factory() { } /** * @see LottieCompositionFactory#fromAsset(Context, String) */ @Deprecated public static Cancellable fromAssetFileName(Context context, String fileName, OnCompositionLoadedListener l) { ListenerAdapter listener = new ListenerAdapter(l); LottieCompositionFactory.fromAsset(context, fileName).addListener(listener); return listener; } /** * @see LottieCompositionFactory#fromRawRes(Context, int) */ @Deprecated public static Cancellable fromRawFile(Context context, @RawRes int resId, OnCompositionLoadedListener l) { ListenerAdapter listener = new ListenerAdapter(l); LottieCompositionFactory.fromRawRes(context, resId).addListener(listener); return listener; } /** * @see LottieCompositionFactory#fromJsonInputStream(InputStream) */ @Deprecated public static Cancellable fromInputStream(InputStream stream, OnCompositionLoadedListener l) { ListenerAdapter listener = new ListenerAdapter(l); LottieCompositionFactory.fromJsonInputStream(stream, null).addListener(listener); return listener; } /** * @see LottieCompositionFactory#fromJsonString(String) */ @Deprecated public static Cancellable fromJsonString(String jsonString, OnCompositionLoadedListener l) { ListenerAdapter listener = new ListenerAdapter(l); LottieCompositionFactory.fromJsonString(jsonString, null).addListener(listener); return listener; } /** * @see LottieCompositionFactory#fromJsonReader(JsonReader) */ @Deprecated public static Cancellable fromJsonReader(JsonReader reader, OnCompositionLoadedListener l) { ListenerAdapter listener = new ListenerAdapter(l); LottieCompositionFactory.fromJsonReader(reader, null).addListener(listener); return listener; } /** * @see LottieCompositionFactory#fromAssetSync(Context, String) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromFileSync(Context context, String fileName) { return LottieCompositionFactory.fromAssetSync(context, fileName).getValue(); } /** * @see LottieCompositionFactory#fromJsonInputStreamSync(InputStream) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromInputStreamSync(InputStream stream) { return LottieCompositionFactory.fromJsonInputStreamSync(stream, null).getValue(); } /** * This will now auto-close the input stream! * * @see LottieCompositionFactory#fromJsonInputStreamSync(InputStream, boolean) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromInputStreamSync(InputStream stream, boolean close) { if (close) { Logger.warning("Lottie now auto-closes input stream!"); } return LottieCompositionFactory.fromJsonInputStreamSync(stream, null).getValue(); } /** * @see LottieCompositionFactory#fromJsonSync(JSONObject) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromJsonSync(@SuppressWarnings("unused") Resources res, JSONObject json) { return LottieCompositionFactory.fromJsonSync(json, null).getValue(); } /** * @see LottieCompositionFactory#fromJsonStringSync(String) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromJsonSync(String json) { return LottieCompositionFactory.fromJsonStringSync(json, null).getValue(); } /** * @see LottieCompositionFactory#fromJsonReaderSync(JsonReader) */ @Nullable @WorkerThread @Deprecated public static LottieComposition fromJsonSync(JsonReader reader) throws IOException { return LottieCompositionFactory.fromJsonReaderSync(reader, null).getValue(); } private static final class ListenerAdapter implements LottieListener<LottieComposition>, Cancellable { private final OnCompositionLoadedListener listener; private boolean cancelled = false; private ListenerAdapter(OnCompositionLoadedListener listener) { this.listener = listener; } @Override public void onResult(LottieComposition composition) { if (cancelled) { return; } listener.onCompositionLoaded(composition); } @Override public void cancel() { cancelled = true; } } } }
package legends.model.events; import legends.model.Entity; import legends.model.Site; import legends.model.Structure; import legends.model.World; import legends.model.events.basic.EntityRelatedEvent; import legends.model.events.basic.Event; import legends.model.events.basic.HfRelatedEvent; import legends.model.events.basic.SiteRelatedEvent; import legends.model.events.basic.StructureRelatedEvent; import legends.xml.annotation.Xml; import legends.xml.annotation.XmlSubtype; @XmlSubtype("created structure") public class CreatedStructureEvent extends Event implements SiteRelatedEvent, EntityRelatedEvent, HfRelatedEvent, StructureRelatedEvent { @Xml("civ_id,civ") int civId = -1; @Xml("site_id,site") int siteId = -1; @Xml("site_civ_id,site_civ") int siteCivId = -1; @Xml("structure_id,structure") int structureId = -1; @Xml("builder_hfid,builder_hf") int builderHfId = -1; public int getCivId() { return civId; } public void setCivId(int civId) { this.civId = civId; } public int getSiteId() { return siteId; } public void setSiteId(int siteId) { this.siteId = siteId; } public int getSiteCivId() { return siteCivId; } public void setSiteCivId(int siteCivId) { this.siteCivId = siteCivId; } public int getStructureId() { return structureId; } public void setStructureId(int structureId) { this.structureId = structureId; } public int getBuilderHfId() { return builderHfId; } public void setBuilderHfId(int builderHfId) { this.builderHfId = builderHfId; } @Override public boolean isRelatedToEntity(int entityId) { return civId == entityId || siteCivId == entityId; } @Override public boolean isRelatedToSite(int siteId) { return this.siteId == siteId; } @Override public boolean isRelatedToHf(int hfId) { return builderHfId == hfId; } @Override public boolean isRelatedToStructure(int structureId, int siteId) { return this.structureId == structureId && this.siteId == siteId; } @Override public void process() { Structure structure = World.getStructure(structureId, siteId); structure.setConstructionYear(year); Site site = World.getSite(siteId); Entity civ = World.getEntity(civId); civ.getSites().add(site); site.setOwner(civ); Entity siteCiv = World.getEntity(siteCivId); siteCiv.getSites().add(site); siteCiv.setParent(civ); if (siteCiv.getType().equals("unknown")) siteCiv.setType("sitegovernment"); if (siteCiv.getRace().equals("unknown")) siteCiv.setRace(civ.getRace()); } @Override public String getShortDescription() { String site = World.getSite(siteId).getLink(); if (builderHfId != -1) return World.getHistoricalFigure(builderHfId).getLink() + " thrust a spire of slade up from the underworld, naming it " + World.getStructure(structureId, siteId).getLink() + ", and established a gateway between worlds in " + site; if (siteCivId != -1) if (civId != -1) return World.getEntity(siteCivId).getLink() + " of " + World.getEntity(civId).getLink() + " constructed " + World.getStructure(structureId, siteId).getLink() + " in " + site; else return World.getEntity(siteCivId).getLink() + " constructed " + World.getStructure(structureId, siteId).getLink() + " in " + site; else return World.getEntity(civId).getLink() + " constructed " + World.getStructure(structureId, siteId).getLink() + " in " + site; } }
package mclaudio76.odataspring.demo; import java.util.ArrayList; import java.util.List; import mclaudio76.odataspring.core.IODataService; import mclaudio76.odataspring.core.ODataEntityHelper; import mclaudio76.odataspring.core.ODataParamValue; public class ProductService implements IODataService<Product> { private ArrayList<Product> products = new ArrayList<>(); private ODataEntityHelper helper = new ODataEntityHelper(); public ProductService() { products.add(new Product(1, "Alfa A1", "Racing car")); products.add(new Product(2, "Beta B1", "Luxury car")); products.add(new Product(3, "Gamma G3", "Speedy car")); products.add(new Product(4, "Delta D4", "City car")); } @Override public List<Product> listAll() { return products; } @Override public Product findByKey(ODataParamValue ... keys) { for(Product p : products) { if(helper.entityMatchesKeys(p, keys)) { return p; } } return null; } @Override public Product create(ODataParamValue... values) { Product product = new Product(); helper.setFieldsValue(product, values); products.add(product); return product; } @Override public void delete(ODataParamValue... keys) { Product p = findByKey(keys); if(p != null) { products.remove(p); } } @Override public Product update(Product target, ODataParamValue... values) { if(target != null) { helper.setFieldsValue(target, values); } return target; } @Override public Class<Product> getEntityClass() { return Product.class; } }
package me.alb_i986.selenium.tinafw.domain; import me.alb_i986.selenium.tinafw.pages.*; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; /** * A Browser has a WebDriver. * * A Browser may be opened and closed. * By opening a Browser, a WebDriver is instantiated. * */ public class Browser { private WebDriverFactory driverFactory; private WebDriver driver; /** * By default inject a {@link WebDriverFactoryLocal} decorated by * {@link WebDriverFactoryDecoratorImplicitWait}. */ public Browser() { this.driverFactory = new WebDriverFactoryDecoratorImplicitWait( new WebDriverFactoryLocal()); } public Browser(WebDriverFactory driverFactory) { if(driverFactory == null) throw new IllegalArgumentException("The arg cannot be null"); this.driverFactory = driverFactory; } public void open() { if(isOpen()) { throw new IllegalStateException("Browser already open: close it first"); } driver = driverFactory.getWebDriver(); } /** * @see WebDriver#quit() */ public void close() { if(isOpen()) { driver.quit(); driver = null; } } /** * Append the given relative URL to {@link Page#BASE_URL} * and navigate there. * * @param relativeUrl e.g. "/article/999" * (a '/' will be prefixed if not present) */ public void browseTo(String relativeUrl) { assertIsOpen(); driver.get( Page.BASE_URL + // add a '/' if it's not present neither in Page.BASE_URL. nor in relativeUrl (!relativeUrl.startsWith("/") && !Page.BASE_URL.endsWith("/") ? "/" : "") + relativeUrl.trim() ); } /** * @see TakesScreenshot#getScreenshotAs(OutputType) */ public <T> T getScreenshotAs(OutputType<T> outputType) { assertIsOpen(); return ((TakesScreenshot)driver).getScreenshotAs(outputType); } /** * @return true if driver is not null. */ public boolean isOpen() { return driver != null; } public WebDriver getWebDriver() { return driver; } private void assertIsOpen() { if(!isOpen()) throw new IllegalStateException("The browser is not open"); } }
package wepresent.wepresent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.android.volley.toolbox.Volley; import wepresent.wepresent.mappers.AsyncTaskReport; import wepresent.wepresent.mappers.Mapper; import wepresent.wepresent.mappers.SingleSlideMapper; public class SlideViewActivity extends ActionBarActivity implements AsyncTaskReport { private LinearLayout linLayout; private ImageView imageView; private TextView textView; private SingleSlideMapper slideMapper; private int value = 0; private int sessionId, slideId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slide_view); // Set title setTitle("Slide notes"); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Get the extras Bundle intentInfo = getIntent().getExtras(); sessionId = intentInfo.getInt("SessionID"); slideId = intentInfo.getInt("SlideID"); // Start the mapper slideMapper = new SingleSlideMapper(this); slideMapper.start(sessionId, slideId); } public void done(Mapper.MapperSort mapper) { if(slideMapper.isSlideSuccesful()){ // Get the slide info String slideUrl = slideMapper.getSlideUrl(); String slideNotes = slideMapper.getSlideNotes(); // Create the image loader ImageLoader.ImageCache imageCache = new BitmapLruCache(); ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(this), imageCache); NetworkImageView image = (NetworkImageView) findViewById(R.id.slideViewImage); image.setImageUrl(slideUrl, imageLoader); image.setFitsSystemWindows(true); TextView text = (TextView) findViewById(R.id.slideViewNotes); text.setText(slideNotes); } else { System.out.println("shitsbrokenlol"); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
package me.prettyprint.cassandra.model; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.cassandra.thrift.Column; /** * Return type from get_range_slices for simple columns * @author Ran Tavory * @author zznate * * @param <N> * @param <V> */ public final class OrderedRows<K,N,V> extends Rows<K,N,V> { private final ArrayDeque<Row<K,N,V>> rowsList; public OrderedRows(LinkedHashMap<K, List<Column>> thriftRet, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { super(thriftRet, nameSerializer, valueSerializer); rowsList = new ArrayDeque<Row<K,N,V>>(thriftRet.size()); for (Map.Entry<K, List<Column>> entry: thriftRet.entrySet()) { rowsList.add(new Row<K,N,V>(entry.getKey(), entry.getValue(), nameSerializer, valueSerializer)); } } /** * Preserves rows order * @return an unmodifiable list of Rows */ public List<Row<K,N,V>> getList() { return Collections.unmodifiableList(new ArrayList<Row<K, N, V>>(rowsList)); } /** * Returns the last element in this row result. Helpful for passing along for paging situations. * @return */ public Row<K, N, V> peekLast() { return rowsList != null && rowsList.size() > 0 ? rowsList.peekLast() : null; } }
package proyectoanalisis2017.pkg1; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.HashMap; import java.util.LinkedList; import javax.swing.ImageIcon; /** * * @author Gianka */ public class pnlVentana extends javax.swing.JPanel implements KeyListener{ /** * Creates new form pnlCiudad */ private int x1Ciudad; private int x2Ciudad; private int x1Componente; private int x2Componete; private int altura; Ciudad ciudad; private Boolean estaSelecionadoComponente; LinkedList<Item> lstItems; private Item itemSeleccionado; private int xImgSelecionada; private int yImgSelecionada; public pnlVentana() { initComponents(); this.lstItems = new LinkedList<>(); this.xImgSelecionada = 0; this.yImgSelecionada = 0; this.itemSeleccionado = new Item(); this.estaSelecionadoComponente = false; //crearComponentes(); // crearComponentes(); //this.setBackground(Color.BLACK); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setBackground(new java.awt.Color(255, 255, 255)); addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { formMouseDragged(evt); } }); addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { formMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { formMouseReleased(evt); } public void mouseClicked(java.awt.event.MouseEvent evt) { formMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { formMouseEntered(evt); } }); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked }//GEN-LAST:event_formMouseClicked private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed if (evt.getX() > this.x1Componente && evt.getX() < this.x2Componete) { for (int i = 0; i < this.lstItems.size(); i++) { if (this.lstItems.get(i).area.contains(new Point(evt.getX(), evt.getY()))) { this.estaSelecionadoComponente = true; this.lstItems.get(i).contador=0; this.itemSeleccionado = this.lstItems.get(i); } } } }//GEN-LAST:event_formMousePressed private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged if (this.estaSelecionadoComponente) { this.xImgSelecionada = evt.getX(); this.yImgSelecionada = evt.getY(); repaint(); } }//GEN-LAST:event_formMouseDragged private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased if (this.estaSelecionadoComponente) { try { this.estaSelecionadoComponente = false; this.xImgSelecionada = 0; this.yImgSelecionada = 0; int auxN = evt.getY() / this.ciudad.altoCampo; int auxM = evt.getX() / this.ciudad.anchoCampo; this.ciudad.matrizCiudad[auxN][auxM] = this.itemSeleccionado.lstComponentes.get(this.itemSeleccionado.contador).tipo; } catch (Exception e) { } repaint(); } }//GEN-LAST:event_formMouseReleased private void formMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseEntered // TODO add your handling code here: }//GEN-LAST:event_formMouseEntered private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed // TODO add your handling code here: }//GEN-LAST:event_formKeyPressed @Override protected void paintComponent(Graphics g) { super.paintComponent(g); //To change body of generated methods, choose Tools | Templates. System.out.println((x2Ciudad)); g.drawImage(new ImageIcon(getClass().getResource("../ImgComponentes/Fondo.jpg")).getImage(), 0, 0, this.x2Ciudad, this.altura, this); g.setColor(Color.decode("#FC4600")); g.fillRect(this.x1Componente, 0, (this.x2Componete - this.x2Ciudad) * 2, this.altura); g.setColor(Color.BLACK); pintarComponentes(g); if (ciudad != null) { // lineas de referencia de las areas de la aplicacion g.drawRect(0, 0, this.x2Ciudad, this.altura); //g.setColor(Color.red); // g.drawRect(this.x1Componente, 0, this.x2Componete - this.x1Componente, this.altura); pintarCiudad(g); //pinta la anamiacion de colocar imagen en el tablero if (this.estaSelecionadoComponente && this.xImgSelecionada > this.x1Ciudad && this.xImgSelecionada < this.x2Ciudad && this.yImgSelecionada > 0 && this.yImgSelecionada < this.altura) { g.drawImage(new ImageIcon(getClass().getResource(this.itemSeleccionado.lstComponentes.get(this.itemSeleccionado.contador).ruta)).getImage(), this.xImgSelecionada, this.yImgSelecionada, 100, 100, this); int auxN = this.yImgSelecionada / this.ciudad.altoCampo; int auxM = this.xImgSelecionada / this.ciudad.anchoCampo; System.out.println(auxN + "--" + auxM); g.drawRect(auxM * this.ciudad.anchoCampo, auxN * this.ciudad.altoCampo, this.ciudad.anchoCampo, this.ciudad.altoCampo); } } } public void crearComponentes() { int auxAltura = 100; //this.lstComponente.add(new Item(this.idContador++, "4.1", "../ImgComponentes/4.1.png", )); LinkedList<Componente> auxLista= new LinkedList<>(); auxLista.add(new Componente("4.1")); auxLista.add(new Componente("4.2")); auxLista.add(new Componente("4.3")); auxLista.add(new Componente("4.4")); this.lstItems.add(new Item(0, auxLista, this.x1Componente + 20, 0 * auxAltura, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("1.1")); auxLista.add(new Componente("1.2")); this.lstItems.add(new Item(1, auxLista, this.x1Componente + 20, 1 * auxAltura+10, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("2.1")); auxLista.add(new Componente("2.2")); auxLista.add(new Componente("2.3")); auxLista.add(new Componente("2.4")); this.lstItems.add(new Item(2, auxLista, this.x1Componente + 20, 2 * auxAltura+20, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("3.1")); auxLista.add(new Componente("3.2")); this.lstItems.add(new Item(3, auxLista, this.x1Componente + 20, 3 * auxAltura+30, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("5.1")); auxLista.add(new Componente("5.2")); auxLista.add(new Componente("5.3")); auxLista.add(new Componente("5.4")); this.lstItems.add(new Item(4, auxLista, this.x1Componente + 20, 4 * auxAltura+40, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("6.1")); auxLista.add(new Componente("6.2")); auxLista.add(new Componente("6.3")); auxLista.add(new Componente("6.4")); this.lstItems.add(new Item(4, auxLista, this.x1Componente + 20, 5 * auxAltura+50, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("7.1")); auxLista.add(new Componente("7.2")); auxLista.add(new Componente("7.3")); auxLista.add(new Componente("7.4")); this.lstItems.add(new Item(6, auxLista, this.x1Componente + 20+80, 0 * auxAltura, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("8.1")); auxLista.add(new Componente("8.2")); auxLista.add(new Componente("8.3")); auxLista.add(new Componente("8.4")); this.lstItems.add(new Item(7, auxLista, this.x1Componente + 30+80, 1 * auxAltura, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("9.1")); auxLista.add(new Componente("9.2")); auxLista.add(new Componente("9.3")); auxLista.add(new Componente("9.4")); this.lstItems.add(new Item(8, auxLista, this.x1Componente + 30+80, 2 * auxAltura, 70, 100)); auxLista= new LinkedList<>(); auxLista.add(new Componente("11.1")); auxLista.add(new Componente("11.2")); auxLista.add(new Componente("11.3")); auxLista.add(new Componente("11.4")); this.lstItems.add(new Item(9, auxLista, this.x1Componente + 30+80, 3 * auxAltura, 70, 100)); // this.lstComponente.add(new Item(this.idContador++, 2, "../ImgComponentes/2.png", this.x1Componente + 20, this.idContador * auxAltura, 100, auxAltura)); //this.lstComponente.add(new Item(this.idContador++, 3, "../ImgComponentes/3.png", this.x1Componente + 20, this.idContador * auxAltura, 100, auxAltura)); //this.lstComponentipote.add(new Item(this.idContador++, 4, "../ImgComponentes/4.png", this.x1Componente + 20, this.idContador * auxAltura, 100, auxAltura)); //this.lstComponente.add(new Item(this.idContador++, 0, "../ImgComponentes/0.png", this.x1Componente + 20, this.idContador * auxAltura, 100, auxAltura)); } public void setX1Ciudad(int x1Ciudad) { this.x1Ciudad = x1Ciudad; } public void setX2Ciudad(int x2Ciudad) { this.x2Ciudad = x2Ciudad; } public void setX1Componente(int x1Componente) { this.x1Componente = x1Componente; } public void setX2Componete(int x2Componete) { this.x2Componete = x2Componete; } public void setAltura(int altura) { this.altura = altura; } private void pintarComponentes(Graphics g) { for (int i = 0; i < this.lstItems.size(); i++) { Item auxComponente = new Item(); auxComponente = this.lstItems.get(i); g.drawImage(new ImageIcon(getClass().getResource(auxComponente.lstComponentes.getFirst().ruta)).getImage(), auxComponente.area.x, auxComponente.area.y, auxComponente.area.width, auxComponente.area.height, this); } } public void setCiudad(Ciudad ciudad) { this.ciudad = ciudad; this.x2Ciudad = this.ciudad.anchoCampo * this.ciudad.m; this.x1Componente = this.ciudad.anchoCampo * this.ciudad.m; repaint(); } private void pintarCiudad(Graphics g) { for (int i = 0; i < this.ciudad.n; i++) { for (int j = 0; j < this.ciudad.m; j++) { if (!this.ciudad.matrizCiudad[i][j].equals("")) { g.drawImage(new ImageIcon(getClass().getResource("../ImgComponentes/" + this.ciudad.matrizCiudad[i][j] + ".png")).getImage(), this.ciudad.anchoCampo * j, this.ciudad.altoCampo * i, this.ciudad.anchoCampo, this.ciudad.altoCampo, this); } } } } @Override public void keyTyped(KeyEvent ke) { } @Override public void keyPressed(KeyEvent ke) { if(this.itemSeleccionado.contador==this.itemSeleccionado.lstComponentes.size()-1) { this.itemSeleccionado.contador=0; }else { this.itemSeleccionado.contador++; } repaint(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void keyReleased(KeyEvent ke) { } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
package org.ranksys.examples; import es.uam.eps.ir.ranksys.core.util.parsing.DoubleParser; import static es.uam.eps.ir.ranksys.core.util.parsing.Parsers.lp; import es.uam.eps.ir.ranksys.fast.index.FastItemIndex; import es.uam.eps.ir.ranksys.fast.index.FastUserIndex; import es.uam.eps.ir.ranksys.fast.index.SimpleFastItemIndex; import es.uam.eps.ir.ranksys.fast.index.SimpleFastUserIndex; import es.uam.eps.ir.ranksys.fast.preference.FastPreferenceData; import es.uam.eps.ir.ranksys.fast.preference.SimpleFastPreferenceData; import java.io.IOException; import org.ranksys.compression.codecs.CODEC; import org.ranksys.compression.codecs.dsi.FixedLengthBitStreamCODEC; import org.ranksys.compression.codecs.lemire.IntegratedFORVBCODEC; import org.ranksys.compression.preferences.RatingCODECPreferenceData; public class Compression { public static void main(String[] args) throws IOException, ClassNotFoundException { String userPath = args[0]; String itemPath = args[1]; String dataPath = args[2]; // READING USER, ITEM AND RATINGS FILES FastUserIndex<Long> users = SimpleFastUserIndex.load(userPath, lp); FastItemIndex<Long> items = SimpleFastItemIndex.load(itemPath, lp); FastPreferenceData<Long, Long> simpleData = SimpleFastPreferenceData.load(dataPath, lp, lp, DoubleParser.ddp, users, items); // CREATING A COMPRESSED PREFERENCE DATA CODEC<int[]> uCodec = new IntegratedFORVBCODEC(); CODEC<int[]> iCodec = new IntegratedFORVBCODEC(); // We assume here that the ratings are 1-5 stars CODEC<byte[]> vCodec = new FixedLengthBitStreamCODEC(3); FastPreferenceData<Long, Long> codecData = new RatingCODECPreferenceData<>(simpleData, users, items, uCodec, iCodec, vCodec); // PRINTING COMPRESSION STATISTICS System.out.println(uCodec.stats()[0] + "\t" + uCodec.stats()[1]); System.out.println(iCodec.stats()[0] + "\t" + iCodec.stats()[1]); System.out.println(vCodec.stats()[0] + "\t" + vCodec.stats()[1]); System.out.println(codecData.numPreferences()); } }
package net.darkhax.orestages; import java.util.ListIterator; import net.darkhax.bookshelf.util.BlockUtils; import net.darkhax.bookshelf.util.RenderUtils; import net.darkhax.gamestages.event.GameStageEvent; import net.darkhax.orestages.api.OreTiersAPI; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class OreTiersEventHandler { @SubscribeEvent(priority = EventPriority.LOWEST) public void onBlockBreak (BreakEvent event) { final Tuple<String, IBlockState> stageInfo = OreTiersAPI.getStageInfo(event.getState()); // Checks if the block has a stage and the player is not valid to break it. if (stageInfo != null && (event.getPlayer() == null || !OreTiersAPI.hasStage(event.getPlayer(), stageInfo.getFirst()))) { // Sets the EXP to drop to 0 event.setExpToDrop(0); // Checks if the player can't harvest the original block, but they can harvest the // replacement block if (!ForgeHooks.canHarvestBlock(event.getState().getBlock(), event.getPlayer(), event.getWorld(), event.getPos()) && BlockUtils.canHarvestSafely(stageInfo.getSecond(), event.getPlayer())) { // Drops the replacement block instead this.dropBlock(event.getWorld(), event.getPlayer(), event.getPos(), stageInfo.getSecond()); } } } // TODO put this in bookshelf BlockUtils public void dropBlock (World world, EntityPlayer player, BlockPos pos, IBlockState state) { try { state.getBlock().harvestBlock(world, player, pos, state, world.getTileEntity(pos), player.getHeldItemMainhand()); } catch (final Exception e) { OreStages.LOG.trace("Error correcting block drops", e); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onBreakSpeed (BreakSpeed event) { try { final Tuple<String, IBlockState> stageInfo = OreTiersAPI.getStageInfo(event.getState()); // Checks if the block has a stage and the player is not valid to break it. if (stageInfo != null && (event.getEntityPlayer() == null || !OreTiersAPI.hasStage(event.getEntityPlayer(), stageInfo.getFirst()))) { // Sets the new break speed to match the replacement block event.setNewSpeed(BlockUtils.getBreakSpeedToMatch(event.getState(), stageInfo.getSecond(), event.getEntityPlayer().world, event.getEntityPlayer(), event.getPos())); } } catch (final Exception e) { OreStages.LOG.trace("Error calculating mining speed!", e); } } @SubscribeEvent(priority = EventPriority.LOWEST) public void onBlockDrops (HarvestDropsEvent event) { final Tuple<String, IBlockState> stageInfo = OreTiersAPI.getStageInfo(event.getState()); // Checks if the block has a stage and the player is not valid to break it. if (stageInfo != null && (event.getHarvester() == null || !OreTiersAPI.hasStage(event.getHarvester(), stageInfo.getFirst()))) { // Clear the drop list and add the correct drops event.getDrops().clear(); event.getDrops().addAll(stageInfo.getSecond().getBlock().getDrops(event.getWorld(), event.getPos(), stageInfo.getSecond(), event.getFortuneLevel())); // Reset the drop chance event.setDropChance(ForgeEventFactory.fireBlockHarvesting(event.getDrops(), event.getWorld(), event.getPos(), stageInfo.getSecond(), event.getFortuneLevel(), event.getDropChance(), event.isSilkTouching(), event.getHarvester())); } } @SubscribeEvent() @SideOnly(Side.CLIENT) public void onStageSync (GameStageEvent.ClientSync event) { // Reload chunk renderers for the player RenderUtils.markRenderersForReload(true); } @SubscribeEvent @SideOnly(Side.CLIENT) public void onOverlayRendered (RenderGameOverlayEvent.Text event) { final Minecraft mc = Minecraft.getMinecraft(); // Checks if the F3 menu is open if (mc.gameSettings.showDebugInfo && event.getRight() != null) { // Iterates through the debug menu for (final ListIterator<String> iterator = event.getRight().listIterator(); iterator.hasNext();) { final String line = iterator.next(); for (final String string : OreTiersAPI.REPLACEMENT_IDS.keySet()) { // Checks if the ID is a hidden ID if (line.equalsIgnoreCase(string)) { // Replaces the block id with the hidden ID iterator.set(OreTiersAPI.REPLACEMENT_IDS.get(line)); break; } } } } } }
package net.fortuna.ical4j.vcard.property; import java.util.Locale; import net.fortuna.ical4j.vcard.Property; /** * @author Ben * */ public final class Language extends Property { private static final long serialVersionUID = 1863658302945551760L; private Locale[] locales; /** * @param locales */ public Language(Locale...locales) { super(Name.LANG); this.locales = locales; } /** * @return the locales */ public Locale[] getLocales() { return locales; } /* (non-Javadoc) * @see net.fortuna.ical4j.vcard.Property#getValue() */ @Override public String getValue() { StringBuilder b = new StringBuilder(); for (int i = 0; i < locales.length; i++) { if (i > 0) { b.append(','); } b.append(locales[i].getLanguage()); } return b.toString(); } }
package com.privacy.sandboxedapp; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class SandboxedMainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sandboxed_main); Intent i = new Intent(); i.putExtra("data", "a value"); i.setAction("com.privacy.sandbox.REQUEST_LOCATION"); sendBroadcast(i, "com.privacy.sandbox.SANDBOX_LOCATION"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sandboxed_main, menu); return true; } // Let us see if this changes }
package net.sf.jabb.spring.rest; import java.io.IOException; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.net.ssl.SSLException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.support.HttpRequestWrapper; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.MultiValueMap; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import net.sf.jabb.spring.rest.CustomHttpRequestRetryHandler.IdempotentPredicate; import net.sf.jabb.util.parallel.BackoffStrategy; import net.sf.jabb.util.parallel.WaitStrategy; /** * Template class for REST API client using Spring's <code>RestTemplate</code>. * This class is intended to be inherited. Subclass should override the following methods if needed: * <ul> * <li>{@link #configureConnectionManager(PoolingHttpClientConnectionManager)}</li> * <li>{@link #configureHttpClient(HttpClientBuilder)}</li> * <li>{@link #configureRequestFactory(HttpComponentsClientHttpRequestFactory)}</li> * <li>{@link #configureRequestFactory(ClientHttpRequestFactory)}</li> * <li>{@link #buildRequestRetryHandler()}</li> * <li>{@link #configureRestTemplate(RestTemplate)}</li> * </ul> * * Subclass should also set {@link #baseUrl}, and call {@link #initializeRestTemplate()} before {@link #restTemplate} can be used. * @author James Hu (Zhengmao Hu) * */ public abstract class AbstractRestClient { //private static final Logger logger = LoggerFactory.getLogger(AbstractRestClient.class); protected static final String HEADER_AUTHORIZATION = "Authorization"; protected static final HttpHeaders ACCEPT_JSON; protected static final HttpHeaders ACCEPT_AND_OFFER_JSON; static{ HttpHeaders tmpHeaders = new HttpHeaders(); tmpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); ACCEPT_JSON = HttpHeaders.readOnlyHttpHeaders(tmpHeaders); tmpHeaders.setContentType(MediaType.APPLICATION_JSON); ACCEPT_AND_OFFER_JSON = HttpHeaders.readOnlyHttpHeaders(tmpHeaders); } /** * The RestTemplate that will be available after {@link #initializeRestTemplate()} is called. */ protected RestTemplate restTemplate; protected String baseUrl; /** * The HttpClientConnectionManager behind the {@link #restTemplate}. * It may be null when the instance is created through {@link #AbstractRestClient(HttpClientConnectionManager)} with null argument * - in that case the instance relies on standard JDK facilities to establish HTTP connections. */ protected HttpClientConnectionManager connectionManager; /** * Constructor. * A <code>PoolingHttpClientConnectionManager</code> will be created and used for HTTP connections initiated by the constructed instance. */ protected AbstractRestClient(){ this(new PoolingHttpClientConnectionManager()); } /** * Constructor. * @param connectionManager The <code>HttpClientConnectionManager</code> to be used for HTTP connections initiated by the constructed instance. * If it is null, then the instance created will rely on standard JDK facilities to establish HTTP connections. */ protected AbstractRestClient(HttpClientConnectionManager connectionManager){ this.connectionManager = connectionManager; } /** * Subclass may override this method to configure PoolingHttpClientConnectionManager. * @param connectionManager the PoolingHttpClientConnectionManager to be configured */ protected void configureConnectionManager(PoolingHttpClientConnectionManager connectionManager){ // do nothing } /** * Subclass may override this method to configure HttpClientBuilder. * @param httpClientBuilder the HttpClientBuilder to be configured */ protected void configureHttpClient(HttpClientBuilder httpClientBuilder){ // do nothing } /** * Subclass may override this method to configure HttpComponentsClientHttpRequestFactory * Please note that after this method is called, {@link #configureRequestFactory(ClientHttpRequestFactory)} will also be called. * @param requestFactory the HttpComponentsClientHttpRequestFactory to be configured */ protected void configureRequestFactory(HttpComponentsClientHttpRequestFactory requestFactory){ // do nothing } /** * Subclass may override this method to configure ClientHttpRequestFactory. * Please note that if the request factory is an instance of PoolingHttpClientConnectionManager, both * {@link #configureRequestFactory(HttpComponentsClientHttpRequestFactory)} and this method will be called. * @param requestFactory the HttpComponentsClientHttpRequestFactory to be configured */ protected void configureRequestFactory(ClientHttpRequestFactory requestFactory){ // do nothing } /** * Subclass may override this method to provide a HttpRequestRetryHandler. * Please note that HttpRequestRetryHandler applies to Apache HttpClient only. * {@link #buildRequestRetryHandler(int, BackoffStrategy, WaitStrategy, boolean, boolean, boolean, IdempotentPredicate, Class...)} method * can be used to create a quite practical HttpRequestRetryHandler * @return the HttpRequestRetryHandler or null if no retry is desired */ protected HttpRequestRetryHandler buildRequestRetryHandler(){ return null; } /** * Subclass may override this method to configure message converters used by the RestTemplate. * @param converters message converters used by the RestTemplate */ protected void configureMessageConverters(List<HttpMessageConverter<?>> converters){ // do nothing } /** * Subclass may override this method to configure RestTemplate. * You may find these methods helpful: * <ul> * <li>{@link #buildAddBasicAuthHeaderRequestInterceptor(String, String)}</li> * <li>{@link #buildAddHeaderRequestInterceptor(String, String)}</li> * <li>{@link #buildAddHeadersRequestInterceptor(String, String, String, String)}</li> * <li>{@link #buildAddHeadersRequestInterceptor(String, String, String, String, String, String)}</li> * <li>{@link #buildAddHeadersRequestInterceptor(String, String, String, String, String, String, String, String)}</li> * <li>{@link #buildAddQueryParameterRequestInterceptor(String, String)}</li> * <li>{@link #buildNoErrorResponseErrorHandler()}</li> * <li>{@link #buildServerErrorOnlyResponseErrorHandler()}</li> * </ul> * @param restTemplate the RestTemplate to be configured */ protected void configureRestTemplate(RestTemplate restTemplate){ // do nothing } /** * Initialize the RestTemplate internally. * When running inside a Spring context, subclass should typically call this method * from within {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()} method. */ protected void initializeRestTemplate(){ if (connectionManager == null){ restTemplate = new RestTemplate(); }else{ if (connectionManager instanceof PoolingHttpClientConnectionManager){ configureConnectionManager((PoolingHttpClientConnectionManager)connectionManager); } HttpRequestRetryHandler retryHandler = buildRequestRetryHandler(); HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager); configureHttpClient(clientBuilder); clientBuilder.setRetryHandler(retryHandler); CloseableHttpClient httpClient = clientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); configureRequestFactory(requestFactory); restTemplate = new RestTemplate(requestFactory); } configureRequestFactory(restTemplate.getRequestFactory()); configureMessageConverters(restTemplate.getMessageConverters()); configureRestTemplate(restTemplate); } /** * Build a <code>HttpRequestRetryHandler</code>. * The returned <code>HttpRequestRetryHandler</code> will not retry on <code>InterruptedIOException</code> and <code>SSLException</code>. * @param retryCount how many times to retry; 0 means no retries * @param backoffStrategy how should retries to backoff from previous ones * @param waitStrategy how should the delay between retries to be implemented * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent * @param retryUnknownHostException true if retry should happen after UnknownHostException * @param retryConnectException true if retry should happen after ConnectException * @param idempotentPredicate Predicate to decide which requests are considered to be retry-able, * if it is null, only <code>GET</code> requests are considered to be retry-able. * @param excludeExceptions the IOException types that should not be retried * @return the <code>HttpRequestRetryHandler</code> */ protected HttpRequestRetryHandler buildRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled, boolean retryUnknownHostException, boolean retryConnectException, BackoffStrategy backoffStrategy, WaitStrategy waitStrategy, IdempotentPredicate idempotentPredicate, Class<? extends IOException>... excludeExceptions){ List<Class<? extends IOException>> excluded = new ArrayList<Class<? extends IOException>>(); excluded.add(InterruptedIOException.class); excluded.add(SSLException.class); if (!retryUnknownHostException){ excluded.add(UnknownHostException.class); } if (!retryConnectException){ excluded.add(ConnectException.class); } if (excludeExceptions != null){ for (Class<? extends IOException> claz: excludeExceptions){ excluded.add(claz); } } return new CustomHttpRequestRetryHandler(retryCount, requestSentRetryEnabled, excluded, backoffStrategy, waitStrategy, idempotentPredicate); } /** * Build a <code>HttpRequestRetryHandler</code>. * The returned <code>HttpRequestRetryHandler</code> will not retry on <code>InterruptedIOException</code> and <code>SSLException</code>. * @param retryCount how many times to retry; 0 means no retries * @param backoffStrategy how should retries to backoff from previous ones * @param waitStrategy how should the delay between retries to be implemented * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent * @param retryUnknownHostException true if retry should happen after UnknownHostException * @param retryConnectException true if retry should happen after ConnectException * @param idempotentPredicate Predicate to decide which requests are considered to be retry-able, * if it is null, only <code>GET</code> requests are considered to be retry-able. * @return the <code>HttpRequestRetryHandler</code> */ protected HttpRequestRetryHandler buildRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled, boolean retryUnknownHostException, boolean retryConnectException, BackoffStrategy backoffStrategy, WaitStrategy waitStrategy, IdempotentPredicate idempotentPredicate){ return buildRequestRetryHandler(retryCount, requestSentRetryEnabled, retryUnknownHostException, retryConnectException, backoffStrategy, waitStrategy, idempotentPredicate, (Class<? extends IOException>[])null); } /** * Create a customized ResponseErrorHandler that ignores HttpStatus.Series.CLIENT_ERROR. * That means responses with status codes like 400/404/401/403/etc are not treated as error, therefore no exception will be thrown in those cases. * Responses with status codes like 500/503/etc will still cause exceptions to be thrown. * @return the ResponseErrorHandler that cares only HttpStatus.Series.SERVER_ERROR */ protected ResponseErrorHandler buildServerErrorOnlyResponseErrorHandler(){ return new DefaultResponseErrorHandler(){ @Override protected boolean hasError(HttpStatus statusCode) { return statusCode.series() == HttpStatus.Series.SERVER_ERROR; } }; } /** * Create a customized ResponseErrorHandler that ignores all HTTP error codes * That means responses with status codes like 40x/50x/etc are not treated as error, therefore no exception will be thrown in those cases. * @return the ResponseErrorHandler that never throws exception */ protected ResponseErrorHandler buildNoErrorResponseErrorHandler(){ return new DefaultResponseErrorHandler(){ @Override protected boolean hasError(HttpStatus statusCode) { return false; } }; } static protected class AddQueryParameterRequestInterceptor implements ClientHttpRequestInterceptor{ private String name; private String value; public AddQueryParameterRequestInterceptor(String name, String value){ this.name = name; this.value = value; } @Override public ClientHttpResponse intercept(org.springframework.http.HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { try{ String originalUriString = request.getURI().toString(); final URI updatedUri = new URI(originalUriString + (originalUriString.contains("?") ? "&" : "?") + URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8")); HttpRequestWrapper wrapper = new HttpRequestWrapper(request){ @Override public URI getURI() { return updatedUri; } }; return execution.execute(wrapper, body); }catch(URISyntaxException e){ e.printStackTrace(); return execution.execute(request, body); } } } static protected class AddHeaderRequestInterceptor implements ClientHttpRequestInterceptor{ private String header; private String value; public AddHeaderRequestInterceptor(String header, String value){ this.header = header; this.value = value; } @Override public ClientHttpResponse intercept(org.springframework.http.HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestWrapper wrapper = new HttpRequestWrapper(request); wrapper.getHeaders().set(header, value); return execution.execute(wrapper, body); } } static protected class AddHeadersRequestInterceptor implements ClientHttpRequestInterceptor{ private String[] headers; private String[] values; public AddHeadersRequestInterceptor(String[] headers, String[] values){ this.headers = headers; this.values = values; } @Override public ClientHttpResponse intercept(org.springframework.http.HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestWrapper wrapper = new HttpRequestWrapper(request); for (int i = 0; i < headers.length; i ++){ wrapper.getHeaders().set(headers[i], values[i]); } return execution.execute(wrapper, body); } } /** * Build a ClientHttpRequestInterceptor that adds a query parameter. * @param name name of the parameter * @param value value of the parameter * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddQueryParameterRequestInterceptor(String name, String value){ return new AddQueryParameterRequestInterceptor(name, value); } /** * Build a ClientHttpRequestInterceptor that adds a request header. * @param header name of the header * @param value value of the header * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddHeaderRequestInterceptor(String header, String value){ return new AddHeaderRequestInterceptor(header, value); } /** * Build a ClientHttpRequestInterceptor that adds two request headers * @param header1 name of header 1 * @param value1 value of header 1 * @param header2 name of header 2 * @param value2 value of header 2 * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2){ return new AddHeadersRequestInterceptor(new String[]{header1, header2}, new String[]{value1, value2}); } /** * Build a ClientHttpRequestInterceptor that adds three request headers * @param header1 name of header 1 * @param value1 value of header 1 * @param header2 name of header 2 * @param value2 value of header 2 * @param header3 name of header 3 * @param value3 value of header 3 * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2, String header3, String value3){ return new AddHeadersRequestInterceptor(new String[]{header1, header2, header3}, new String[]{value1, value2, value3}); } /** * Build a ClientHttpRequestInterceptor that adds three request headers * @param header1 name of header 1 * @param value1 value of header 1 * @param header2 name of header 2 * @param value2 value of header 2 * @param header3 name of header 3 * @param value3 value of header 3 * @param header4 name of the header 4 * @param value4 value of the header 4 * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2, String header3, String value3, String header4, String value4){ return new AddHeadersRequestInterceptor(new String[]{header1, header2, header3, header4}, new String[]{value1, value2, value3, value4}); } /** * Build a ClientHttpRequestInterceptor that adds BasicAuth header * @param user the user name, may be null or empty * @param password the password, may be null or empty * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddBasicAuthHeaderRequestInterceptor(String user, String password){ return new AddHeaderRequestInterceptor(HEADER_AUTHORIZATION, buildBasicAuthValue(user, password)); } /** * Build a ClientHttpRequestInterceptor that adds BasicAuth header * @param apiKey the api key * @return the ClientHttpRequestInterceptor built */ protected ClientHttpRequestInterceptor buildAddBasicAuthHeaderRequestInterceptor(String apiKey){ return new AddHeaderRequestInterceptor(HEADER_AUTHORIZATION, buildBasicAuthValue(apiKey)); } /** * Build the value to be used in HTTP Basic Authentication header * @param user the user name, may be null or empty * @param password the password, may be null or empty * @return the value to be used for header 'Authorization' */ protected String buildBasicAuthValue(String user, String password){ StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(user)){ sb.append(user); } if (StringUtils.isNotEmpty(password)){ if (sb.length() > 0){ sb.append(':'); } sb.append(password); } return buildBasicAuthValue(sb.toString()); } /** * Build the value to be used in HTTP Basic Authentication header * @param key the API key * @return the value to be used for header 'Authorization' */ protected String buildBasicAuthValue(String key){ String base64Creds; try { base64Creds = key == null ? "" : Base64.encodeBase64String(key.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode", e); } return "Basic " + base64Creds; } protected URIBuilder uriBuilder(String partialUri){ String p1 = StringUtils.trimToEmpty(baseUrl); String p2 = StringUtils.trimToEmpty(partialUri); String url; if (p1.length() > 0 && p1.charAt(p1.length() - 1) == '/' && p2.length() > 0 && p2.charAt(p2.length() - 1) == '/'){ url = p1 + p2.substring(1); }else{ url = p1 + p2; } try { return new URIBuilder(url); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } protected URI buildUri(URIBuilder builder){ try { return builder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } protected URI buildUri(String partialUri){ return buildUri(uriBuilder(partialUri)); } protected URI buildUri(String partialUri, List<NameValuePair> params){ return buildUri(uriBuilder(partialUri).addParameters(params)); } protected URI buildUri(String partialUri, String name, String value){ return buildUri(uriBuilder(partialUri).addParameter(name, value)); } protected URI buildUri(String partialUri, String name1, String value1, String name2, String value2){ return buildUri(uriBuilder(partialUri) .addParameter(name1, value1) .addParameter(name2, value2)); } protected URI buildUri(String partialUri, String name1, String value1, String name2, String value2, String name3, String value3){ return buildUri(uriBuilder(partialUri) .addParameter(name1, value1) .addParameter(name2, value2) .addParameter(name3, value3)); } protected URI buildUri(String partialUri, String name1, String value1, String name2, String value2, String name3, String value3, String name4, String value4){ return buildUri(uriBuilder(partialUri) .addParameter(name1, value1) .addParameter(name2, value2) .addParameter(name3, value3) .addParameter(name4, value4)); } /** * Make a writable copy of an existing HttpHeaders * @param headers existing HttpHeaders to be copied * @return a new HttpHeaders that contains all the entries from the existing HttpHeaders */ protected HttpHeaders copy(HttpHeaders headers){ HttpHeaders newHeaders = new HttpHeaders(); newHeaders.putAll(headers); return newHeaders; } /** * Add HTTP Basic Auth header * @param headers the headers, it must not be a read-only one, if it is, use {@link #copy(HttpHeaders)} to make a writable copy first * @param user the user name, may be null or empty * @param password the password, may be null or empty */ protected void addBasicAuthHeader(HttpHeaders headers, String user, String password){ headers.add(HEADER_AUTHORIZATION, buildBasicAuthValue(user, password)); } /** * Add HTTP Basic Auth header * @param headers the headers, it must not be a read-only one, if it is, use {@link #copy(HttpHeaders)} to make a writable copy first * @param key the API key */ protected void addBasicAuthHeader(HttpHeaders headers, String key){ headers.add(HEADER_AUTHORIZATION, buildBasicAuthValue(key)); } protected <T, D> T postForObject(URI uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T postForObject(String uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T postForObject(URI uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T postForObject(String uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T> T getForObject(URI uri, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), responseType).getBody(); } protected <T> T getForObject(String uri, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), responseType).getBody(); } protected <T> T getForObject(URI uri, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), responseType).getBody(); } protected <T> T getForObject(String uri, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), responseType).getBody(); } protected <T, D> T patchForObject(URI uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T patchForObject(String uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T patchForObject(URI uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T patchForObject(String uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T putForObject(URI uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T putForObject(String uri, D data, MultiValueMap<String, String> headers, Class<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T putForObject(URI uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <T, D> T putForObject(String uri, D data, MultiValueMap<String, String> headers, ParameterizedTypeReference<T> responseType){ return restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), responseType).getBody(); } protected <D> void patch(URI uri, D data, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), Void.class); } protected <D> void patch(String uri, D data, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<D>(data, headers), Void.class); } protected <D> void put(URI uri, D data, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), Void.class); } protected <D> void put(String uri, D data, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<D>(data, headers), Void.class); } protected void delete(URI uri, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.DELETE, new HttpEntity<Void>(headers), Void.class); } protected void delete(String uri, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.DELETE, new HttpEntity<Void>(headers), Void.class); } protected void get(URI uri, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), Void.class); } protected void get(String uri, MultiValueMap<String, String> headers){ restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<Void>(headers), Void.class); } }
package org.gluu.oxauth.service; import org.apache.commons.lang.time.DateUtils; import org.gluu.oxauth.model.common.CIBAGrant; import org.gluu.oxauth.model.common.CIBAGrantUserAuthorization; import org.gluu.oxauth.model.config.StaticConfiguration; import org.gluu.oxauth.model.ldap.CIBARequest; import org.gluu.persist.PersistenceEntryManager; import org.gluu.search.filter.Filter; import org.slf4j.Logger; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; import java.util.Date; import java.util.List; /** * Service used to access to the database for CibaRequest ObjectClass. * * @author Milton BO * @version May 28, 2020 */ @Stateless @Named public class CibaRequestService { @Inject private Logger log; @Inject private PersistenceEntryManager entryManager; @Inject private StaticConfiguration staticConfiguration; private String cibaBaseDn() { return staticConfiguration.getBaseDn().getCiba(); // ou=ciba,o=gluu } /** * Uses request data and expiration sent by the client and save request data in database. * @param grant Object containing information related to the request. * @param expiresIn Expiration time that end user has to answer. */ public void persistRequest(CIBAGrant grant, int expiresIn) { Date expirationDate = DateUtils.addSeconds(new Date(), expiresIn); String authReqId = grant.getCIBAAuthenticationRequestId().getCode(); CIBARequest cibaRequest = new CIBARequest(); cibaRequest.setDn("authReqId=" + authReqId + "," + this.cibaBaseDn()); cibaRequest.setAuthReqId(authReqId); cibaRequest.setClientId(grant.getClientId()); cibaRequest.setExpirationDate(expirationDate); cibaRequest.setRequestDate(new Date()); cibaRequest.setStatus(CIBAGrantUserAuthorization.AUTHORIZATION_PENDING.getValue()); cibaRequest.setUserId(grant.getUserId()); entryManager.persist(cibaRequest); } /** * Load a CIBARequest entry from database. * @param authReqId Identifier of the entry. */ public CIBARequest load(String authReqId) { try { return entryManager.find(CIBARequest.class, authReqId); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * Generates a list of requests that are expired and also filter them using a Status. * @param authorizationStatus Status used to filter entries. */ public List<CIBARequest> loadExpiredByStatus(CIBAGrantUserAuthorization authorizationStatus) { try { Date now = new Date(); Filter filter = Filter.createANDFilter( Filter.createEqualityFilter("status", authorizationStatus.getValue()), Filter.createLessOrEqualFilter("exp", entryManager.encodeTime(this.cibaBaseDn(), now))); return entryManager.findEntries(this.cibaBaseDn(), CIBARequest.class, filter); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * Change the status field in database for a specific request. * @param authReqId Identificator of the request. * @param authorizationStatus New status. */ public void updateStatus(String authReqId, CIBAGrantUserAuthorization authorizationStatus) { try { String requestDn = String.format("authReqId=%s,%s", authReqId, this.cibaBaseDn()); CIBARequest cibaRequest = entryManager.find(CIBARequest.class, requestDn); cibaRequest.setStatus(authorizationStatus.getValue()); entryManager.merge(cibaRequest); } catch (Exception e) { log.error(e.getMessage(), e); } } /** * Change the status field in database for a specific request. * @param cibaRequest Entry containing information of the CIBA request. * @param authorizationStatus New status. */ public void updateStatus(CIBARequest cibaRequest, CIBAGrantUserAuthorization authorizationStatus) { try { cibaRequest.setStatus(authorizationStatus.getValue()); entryManager.merge(cibaRequest); } catch (Exception e) { log.error(e.getMessage(), e); } } }
package mr; import manifold.api.fs.cache.PathCache; import manifold.internal.host.ManifoldHost; import manifold.templates.ManifoldTemplates; import manifold.templates.runtime.ILayout; import manifold.util.StreamUtil; import org.commonmark.node.Node; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import org.lesscss.LessCompiler; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.function.Predicate; public class Hyde { static Parser MD_PARSER = Parser.builder().build(); static HtmlRenderer MD_RENDERER = HtmlRenderer.builder().escapeHtml(false).build(); public static void main(String[] args) throws Exception { log("Generating Site..."); File outputDir = makeOutputDir(); File wwwDir = fileFromResourcePath("/www"); // Set default layout ManifoldTemplates.setDefaultLayout(www.layout.main.asLayout()); // Generate Templates PathCache pathCache = ManifoldHost.getCurrentModule().getPathCache(); log("Generating Templates..."); for (String fqn : pathCache.getExtensionCache("mtf").getFqns()) { // ignore layouts and non-www stuff if (fqn.contains(".layout.")) { continue; } if (fqn.endsWith("_html")) { File f = new File(outputDir, getNameFromFile(fqn)); writeTo(f, renderTemplate(fqn, "_html")); } //TODO better MD processing (detect header/footer?) if (fqn.endsWith("_md")) { File f = new File(outputDir, getNameFromFile(fqn)); writeTo(f, mdToHtml(renderTemplate(fqn, "_md"))); } } // External project docs non-template Resources log("Generating External Docs..."); renderExternalMarkdownTo(wwwDir, "manifold-templates.html", "manifold-deps-parent/manifold-templates/README.md"); renderExternalMarkdownTo(wwwDir, "manifold-js.html", "manifold-deps-parent/manifold-js/README.md"); // Copy non-template Resources log("Copying Resources..."); copyDirInto(wwwDir, outputDir, file -> !file.getName().endsWith(".mtf") && !file.getName().endsWith(".less")); log("Generating CSS from LESS..."); generateCSS(fileFromResourcePath("/www/css/site.less"), new File(outputDir, "css/site.css")); log("Done!"); } private static void renderExternalMarkdownTo(File wwwDir, String targetFileName, String inputFile) throws IOException { File output = new File(wwwDir, targetFileName); ILayout layout = www.layout.main.asLayout(); StringBuffer content = new StringBuffer(); layout.header(content); content.append(mdToHtml(new String(Files.readAllBytes(new File(inputFile).toPath())))); layout.footer(content); Files.write(output.toPath(), content.toString().getBytes()); } private static void generateCSS(File lessFile, File outputFile) throws Exception { new LessCompiler().compile(lessFile, outputFile); } private static void log(String s) { System.out.println("Mr. Hyde says: " + s); } private static File fileFromResourcePath(String name) throws URISyntaxException { return new File(Hyde.class.getResource(name).toURI()); } private static void copyDirInto(File in, File out, Predicate<File> filter) { for (File file : in.listFiles()) { StreamUtil.copy(file, out, filter); } } private static String mdToHtml(String markdown) { Node doc = MD_PARSER.parse(markdown); return MD_RENDERER.render(doc); } private static void writeTo(File f, String html) throws IOException { Files.write(Paths.get(f.getPath()), html.getBytes(StandardCharsets.UTF_8)); } private static String renderTemplate(String fqn, String ext) throws Exception { CharSequence className = fqn.subSequence(0, fqn.length() - ext.length()); Class<?> aClass = Class.forName(className.toString()); return (String) aClass.getMethod("render").invoke(null); } private static String getNameFromFile(String fqn) { int endIndex = fqn.lastIndexOf("_"); String stripPackage = fqn.substring(4, endIndex); String noDots = stripPackage.replace(".", "" + File.separatorChar); return noDots + ".html"; } private static File makeOutputDir() { File site = new File("manifold-docs/www"); site.mkdirs(); return site; } // HTML utils public static class BaseTemplate extends manifold.templates.runtime.BaseTemplate { public String anchor(String content) { return "<a class=\"toc_anchor\" name=\"" + anchorId(content) + "\">&nbsp;</a>" + content; } public String linkTo(String name) { return "<a href=\"#" + anchorId(name) + "\">" + name + "</a>"; } private String anchorId(String content) { String strValue = content.replaceAll("[^A-Za-z0-9 ]", "").trim().toLowerCase(); return strValue.replace(" ", "_"); } } }
package com.kadam.mavenproject1; /** * * @author kadam */ public class Main { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. Human european = new European(30); System.out.println("AGE of the human: " + european.getAge()); } }
package org.biouno.unochoice.model; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.biouno.unochoice.util.Utils; import org.jenkinsci.plugins.scriptler.ScriptlerManagement; import org.jenkinsci.plugins.scriptler.config.Script; import org.jenkinsci.plugins.scriptler.util.ScriptHelper; import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.bind.JavaScriptMethod; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.ManagementLink; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * A scriptler script. * * @author Bruno P. Kinoshita * @since 0.1 */ public class ScriptlerScript extends AbstractScript { /* * Serial UID. */ private static final long serialVersionUID = -6600327523009436354L; private final String scriptlerScriptId; // Map is not serializable, but LinkedHashMap is. Ignore static analysis errors private final Map<String, String> parameters; @DataBoundConstructor public ScriptlerScript(String scriptlerScriptId, List<ScriptlerScriptParameter> parameters) { super(); this.scriptlerScriptId = scriptlerScriptId; this.parameters = new LinkedHashMap<>(); if (parameters != null) { for (ScriptlerScriptParameter parameter : parameters) { this.parameters.put(parameter.getName(), parameter.getValue()); } } } /** * @return the scriptlerScriptId */ public String getScriptlerScriptId() { return scriptlerScriptId; } /** * @return the parameters */ public Map<String, String> getParameters() { return parameters; } @Override public Object eval() { return eval(null); } /* * (non-Javadoc) * @see org.biouno.unochoice.model.Script#eval(java.util.Map) */ @Override public Object eval(Map<String, String> parameters) { final Map<String, String> envVars = Utils.getSystemEnv(); Map<String, String> evaledParameters = new LinkedHashMap<>(envVars); // if we have any parameter that came from UI, let's eval and use them if (parameters != null && !parameters.isEmpty()) { // fill our map with the given parameters evaledParameters.putAll(parameters); // and now try to expand env vars for (String key : this.getParameters().keySet()) { String value = this.getParameters().get(key); value = Util.replaceMacro(value, parameters); evaledParameters.put(key, value); } } else { evaledParameters.putAll(this.getParameters()); } return this.toGroovyScript().eval(evaledParameters); } /** * Converts this scriptler script to a GroovyScript. * * @return a GroovyScript */ public GroovyScript toGroovyScript() { final Script scriptler = ScriptHelper.getScript(getScriptlerScriptId(), true); if (scriptler == null) { throw new RuntimeException("Missing required scriptler!"); } boolean isSandbox = ScriptHelper.isApproved(scriptler.script) ? false : true; return new GroovyScript(new SecureGroovyScript(scriptler.script, isSandbox, null), null); } @Extension(optional = true) public static class DescriptorImpl extends ScriptDescriptor { static { // make sure this class fails to load during extension discovery if scriptler isn't present ScriptlerManagement.getScriptlerHomeDirectory(); } /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Scriptler Script"; } @Override public AbstractScript newInstance(StaplerRequest req, JSONObject jsonObject) throws FormException { ScriptlerScript script = null; String scriptScriptId = jsonObject.getString("scriptlerScriptId"); if (scriptScriptId != null && !scriptScriptId.trim().equals("")) { List<ScriptlerScriptParameter> parameters = new ArrayList<>(); final JSONObject defineParams = jsonObject.getJSONObject("defineParams"); if (defineParams != null && !defineParams.isNullObject()) { JSONObject argsObj = defineParams.optJSONObject("parameters"); if (argsObj == null) { JSONArray argsArrayObj = defineParams.optJSONArray("parameters"); if (argsArrayObj != null) { for (int i = 0; i < argsArrayObj.size(); i++) { JSONObject obj = argsArrayObj.getJSONObject(i); String name = obj.getString("name"); String value = obj.getString("value"); if (name != null && !name.trim().equals("") && value != null) { ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value); parameters.add(param); } } } } else { String name = argsObj.getString("name"); String value = argsObj.getString("value"); if (name != null && !name.trim().equals("") && value != null) { ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value); parameters.add(param); } } } script = new ScriptlerScript(scriptScriptId, parameters); } return script; } @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") private ManagementLink getScriptler() { return Jenkins.get().getExtensionList(ScriptlerManagement.class).get(0); } /** * gets the argument description to be displayed on the screen when selecting a config in the dropdown * * @param scriptlerScriptId * the config id to get the arguments description for * @return the description */ @JavaScriptMethod public JSONArray getParameters(String scriptlerScriptId) { final ManagementLink scriptler = this.getScriptler(); if (scriptler != null) { ScriptlerManagement scriptlerManagement = (ScriptlerManagement) scriptler; final Script script = scriptlerManagement.getConfiguration().getScriptById(scriptlerScriptId); if (script != null && script.getParameters() != null) { return JSONArray.fromObject(script.getParameters()); } } return null; } } }
package org.cyclops.cyclopscore.helper; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import org.cyclops.cyclopscore.datastructure.DimPos; /** * Contains helper methods for various tile entity specific things. * @author rubensworks */ public final class TileHelpers { /** * Safely cast a tile entity. * @param dimPos The dimensional position of the block providing the tile entity. * @param targetClazz The class to cast to. * @param <T> The type of tile to cast at. * @return The tile entity or null. */ public static <T> T getSafeTile(DimPos dimPos, Class<T> targetClazz) { return getSafeTile(dimPos.getWorld(), dimPos.getBlockPos(), targetClazz); } /** * Safely cast a tile entity. * @param world The world. * @param pos The position of the block providing the tile entity. * @param targetClazz The class to cast to. * @param <T> The type of tile to cast at. * @return The tile entity or null. */ public static <T> T getSafeTile(IBlockAccess world, BlockPos pos, Class<T> targetClazz) { TileEntity tile = world.getTileEntity(pos); try { return targetClazz.cast(tile); } catch (ClassCastException e) { return null; } } /** * Safely get a capability from a tile. * @param dimPos The dimensional position of the block providing the tile entity. * @param capability The capability. * @param <C> The capability instance. * @return The capability or null. */ public static <C> C getCapability(DimPos dimPos, Capability<C> capability) { return getCapability(dimPos.getWorld(), dimPos.getBlockPos(), null, capability); } /** * Safely get a capability from a tile. * @param dimPos The dimensional position of the block providing the tile entity. * @param side The side to get the capability from. * @param capability The capability. * @param <C> The capability instance. * @return The capability or null. */ public static <C> C getCapability(DimPos dimPos, EnumFacing side, Capability<C> capability) { return getCapability(dimPos.getWorld(), dimPos.getBlockPos(), side, capability); } /** * Safely get a capability from a tile. * @param world The world. * @param pos The position of the block of the tile entity providing the capability. * @param side The side to get the capability from. * @param capability The capability. * @param <C> The capability instance. * @return The capability or null. */ public static <C> C getCapability(World world, BlockPos pos, EnumFacing side, Capability<C> capability) { return getCapability((IBlockAccess) world, pos, side, capability); } /** * Safely get a capability from a tile. * @param world The world. * @param pos The position of the block of the tile entity providing the capability. * @param capability The capability. * @param <C> The capability instance. * @return The capability or null. */ public static <C> C getCapability(IBlockAccess world, BlockPos pos, Capability<C> capability) { return getCapability(world, pos, null, capability); } /** * Safely get a capability from a tile. * @param world The world. * @param pos The position of the block of the tile entity providing the capability. * @param side The side to get the capability from. * @param capability The capability. * @param <C> The capability instance. * @return The capability or null. */ public static <C> C getCapability(IBlockAccess world, BlockPos pos, EnumFacing side, Capability<C> capability) { TileEntity tile = TileHelpers.getSafeTile(world, pos, TileEntity.class); if(tile != null && tile.hasCapability(capability, side)) { return tile.getCapability(capability, side); } return null; } }
package org.digidoc4j.signers; import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SignatureException; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.List; import javax.crypto.Cipher; import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import org.digidoc4j.DigestAlgorithm; import org.digidoc4j.SignatureToken; import org.digidoc4j.X509Cert; import org.digidoc4j.exceptions.TechnicalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.DSSUtils; import eu.europa.esig.dss.EncryptionAlgorithm; import eu.europa.esig.dss.SignatureAlgorithm; import eu.europa.esig.dss.SignatureValue; import eu.europa.esig.dss.ToBeSigned; import eu.europa.esig.dss.token.AbstractSignatureTokenConnection; import eu.europa.esig.dss.token.DSSPrivateKeyEntry; import eu.europa.esig.dss.token.KSPrivateKeyEntry; import eu.europa.esig.dss.token.PasswordInputCallback; import eu.europa.esig.dss.token.Pkcs11SignatureToken; public class PKCS11SignatureToken implements SignatureToken { private static final Logger logger = LoggerFactory.getLogger(PKCS11SignatureToken.class); private AbstractSignatureTokenConnection signatureTokenConnection; private KSPrivateKeyEntry privateKeyEntry; /** * Initializes the PKCS#11 token. * * @param pkcs11ModulePath PKCS#11 module path, depends on your operating system and installed smart card or hardware token library. * @param password Secret pin code for digital signature. * @param slotIndex Token slot index, depends on the hardware token. */ public PKCS11SignatureToken(String pkcs11ModulePath, char[] password, int slotIndex) { logger.debug("Initializing PKCS#11 signature token from " + pkcs11ModulePath + " and slot " + slotIndex); signatureTokenConnection = new Pkcs11SignatureToken(pkcs11ModulePath, password, slotIndex); privateKeyEntry = findPrivateKey(X509Cert.KeyUsage.NON_REPUDIATION); } /** * Initializes the PKCS#11 token with password callback. * <p/> * This Password Callback is used in order to retrieve the password from the user when accessing the Key Store. * * @param pkcs11ModulePath PKCS#11 module path, depends on your operating system and installed smart card or hardware token library. * @param passwordCallback callback for providing the password for the private key. * @param slotIndex Token slot index, depends on the hardware token. */ public PKCS11SignatureToken(String pkcs11ModulePath, PasswordInputCallback passwordCallback, int slotIndex) { logger.debug("Initializing PKCS#11 signature token with password callback from " + pkcs11ModulePath + " and slot " + slotIndex); signatureTokenConnection = new Pkcs11SignatureToken(pkcs11ModulePath, passwordCallback, slotIndex); privateKeyEntry = findPrivateKey(X509Cert.KeyUsage.NON_REPUDIATION); } /** * Fetches the private key entries from the hardware token for information purposes. * The actual private key remains on the token and won't be accessible. * * @return list of private key entries. */ public List<DSSPrivateKeyEntry> getPrivateKeyEntries() { return signatureTokenConnection.getKeys(); } /** * For selecting a particular private key to be used for signing. * * @param keyEntry Private key entry to set */ public void usePrivateKeyEntry(DSSPrivateKeyEntry keyEntry) { this.privateKeyEntry = (KSPrivateKeyEntry)keyEntry; } @Override public X509Certificate getCertificate() { logger.debug("Fetching certificate"); return getPrivateKeyEntry().getCertificate().getCertificate(); } public byte[] sign2(DigestAlgorithm digestAlgorithm, byte[] dataToSign) throws Exception { MessageDigest sha = MessageDigest.getInstance(digestAlgorithm.name(), "BC"); byte[] digest = sha.digest(dataToSign); DERObjectIdentifier shaoid = new DERObjectIdentifier(digestAlgorithm.getDssDigestAlgorithm().getOid()); AlgorithmIdentifier shaaid = new AlgorithmIdentifier(shaoid, DERNull.INSTANCE); DigestInfo di = new DigestInfo(shaaid, digest); byte[] plainSig = di.getEncoded(ASN1Encoding.DER); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getPrivateKey()); byte[] signature = cipher.doFinal(plainSig); return signature; } public byte[] sign3(DigestAlgorithm digestAlgorithm, byte[] dataToSign) { byte[] result = new byte[512]; try { EncryptionAlgorithm encryptionAlgorithm = privateKeyEntry.getEncryptionAlgorithm(); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.getAlgorithm(encryptionAlgorithm, digestAlgorithm.getDssDigestAlgorithm()); String javaSignatureAlgorithm = signatureAlgorithm.getJCEId(); logger.debug(" ... Signing with PKCS#11 and " + javaSignatureAlgorithm); java.security.Signature signature = java.security.Signature.getInstance(javaSignatureAlgorithm); signature.initSign(privateKeyEntry.getPrivateKey()); signature.update(dataToSign); result = signature.sign(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } return result; } private KSPrivateKeyEntry findPrivateKey(X509Cert.KeyUsage keyUsage) { logger.debug("Searching key by usage: " + keyUsage.name()); List<DSSPrivateKeyEntry> keys = getPrivateKeyEntries(); X509CertSelector selector = new X509CertSelector(); selector.setKeyUsage(getUsageBitArray(keyUsage)); // TODO: Test this! for (DSSPrivateKeyEntry key : keys) { if (selector.match(key.getCertificate().getCertificate())) { privateKeyEntry = (KSPrivateKeyEntry)key; logger.debug("... Found key by keyUsage. Key encryption algorithm:" + privateKeyEntry.getEncryptionAlgorithm().getName()); break; } } return getPrivateKeyEntry(); } private boolean[] getUsageBitArray(X509Cert.KeyUsage keyUsage) { sun.security.x509.KeyUsageExtension usage = new sun.security.x509.KeyUsageExtension(); try { usage.set(keyUsage.name(), Boolean.TRUE); } catch (IOException e) { e.printStackTrace(); } return usage.getBits(); } private KSPrivateKeyEntry getPrivateKeyEntry() { if (privateKeyEntry == null) { privateKeyEntry = (KSPrivateKeyEntry)getPrivateKeyEntries().get(0); logger.debug("... Getting first available key"); } return privateKeyEntry; } @Override public byte[] sign(DigestAlgorithm digestAlgorithm, byte[] dataToSign){ if (privateKeyEntry != null){ String encryptionAlg = privateKeyEntry.getEncryptionAlgorithm().getName(); if ("ECDSA".equals(encryptionAlg)){ logger.debug("Sign ECDSA"); return signECDSA(digestAlgorithm, dataToSign); } else if ("RSA".equals(encryptionAlg)){ logger.debug("Sign RSA"); return signRSA(digestAlgorithm, dataToSign); } throw new TechnicalException("Failed to sign with PKCS#11. Encryption Algorithm should be ECDSA or RSA " + "but actually is : " + encryptionAlg); } throw new TechnicalException("privateKeyEntry is null"); } private byte[] signECDSA(DigestAlgorithm digestAlgorithm, byte[] dataToSign) { try { logger.debug("Signing with PKCS#11 and " + digestAlgorithm.name()); ToBeSigned toBeSigned = new ToBeSigned(dataToSign); eu.europa.esig.dss.DigestAlgorithm dssDigestAlgorithm = eu.europa.esig.dss.DigestAlgorithm.forXML(digestAlgorithm.toString()); SignatureValue signature = signatureTokenConnection.sign(toBeSigned, dssDigestAlgorithm, privateKeyEntry); return signature.getValue(); } catch (Exception e) { logger.error("Failed to sign with PKCS#11: " + e.getMessage()); throw new TechnicalException("Failed to sign with PKCS#11: " + e.getMessage(), e); } } private byte[] signRSA(DigestAlgorithm digestAlgorithm, byte[] dataToSign) { try { logger.debug("Signing with PKCS#11 and " + digestAlgorithm.name()); byte[] digestToSign = DSSUtils.digest(digestAlgorithm.getDssDigestAlgorithm(), dataToSign); byte[] digestWithPadding = addPadding(digestToSign, digestAlgorithm); return signDigest(digestWithPadding); } catch (Exception e) { logger.error("Failed to sign with PKCS#11: " + e.getMessage()); throw new TechnicalException("Failed to sign with PKCS#11: " + e.getMessage(), e); } } private static byte[] addPadding(byte[] digest, DigestAlgorithm digestAlgorithm) { return ArrayUtils.addAll(digestAlgorithm.digestInfoPrefix(), digest); // should find the prefix by checking digest length? } private byte[] signDigest(byte[] digestToSign) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException { logger.debug("Signing digest"); DSSPrivateKeyEntry privateKeyEntry = getPrivateKeyEntry(); PrivateKey privateKey = ((KSPrivateKeyEntry) privateKeyEntry).getPrivateKey(); EncryptionAlgorithm encryptionAlgorithm = privateKeyEntry.getEncryptionAlgorithm(); String signatureAlgorithm = "NONEwith" + encryptionAlgorithm.getName(); return invokeSigning(digestToSign, privateKey, signatureAlgorithm); } private byte[] invokeSigning(byte[] digestToSign, PrivateKey privateKey, String signatureAlgorithm) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { logger.debug("Signing with signature algorithm " + signatureAlgorithm); java.security.Signature signer = java.security.Signature.getInstance(signatureAlgorithm); signer.initSign(privateKey); signer.update(digestToSign); byte[] signatureValue = signer.sign(); return signatureValue; } }
package org.everit.osgi.dev.maven.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Enumeration; import java.util.Random; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.everit.osgi.dev.maven.jaxb.dist.definition.CopyMode; import org.rzo.yajsw.os.OperatingSystem; import org.rzo.yajsw.os.ms.win.w32.WindowsXPProcess; import org.rzo.yajsw.os.ms.win.w32.WindowsXPProcessManager; /** * This class is not thread-safe. It should be used within one thread only. */ public class FileManager implements AutoCloseable { private class ShutdownHook extends Thread { @Override public void run() { shutdownHook = null; if (symbolicLinkServerSocket != null) { try { close(); } catch (IOException e) { log.error("Error during closing FileManager", e); } } } } private static void setUnixPermissionsOnFileIfNecessary(final File file, final ZipArchiveEntry entry) { if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_FAT) { return; } int unixPermissions = entry.getUnixMode(); // Executable boolean doable = (unixPermissions & 0111) > 0; boolean doableByOthers = (unixPermissions & 011) > 0; file.setExecutable(doable, !doableByOthers); // Writeable doable = (unixPermissions & 0222) > 0; doableByOthers = (unixPermissions & 022) > 0; file.setWritable(doable, !doableByOthers); // Readable doable = (unixPermissions & 0444) > 0; doableByOthers = (unixPermissions & 044) > 0; file.setReadable(doable, !doableByOthers); } private final Log log; private ShutdownHook shutdownHook = null; private Socket symbolicLinkServerSocket = null; public FileManager(final Log log) { this.log = log; } /** * In case an elevated service was started, it will be stopped by calling this function. * * @throws IOException */ @Override public void close() throws IOException { if (shutdownHook != null) { Runtime.getRuntime().removeShutdownHook(shutdownHook); shutdownHook = null; } if (symbolicLinkServerSocket != null) { OutputStream outputStream = symbolicLinkServerSocket.getOutputStream(); outputStream.write("stop".getBytes(Charset.defaultCharset())); symbolicLinkServerSocket.close(); symbolicLinkServerSocket = null; } } public void copyDirectory(final File sourceLocation, final File targetLocation, final CopyMode copyMode) throws IOException, MojoExecutionException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { targetLocation.mkdir(); } String[] children = sourceLocation.list(); for (int i = 0; i < children.length; i++) { copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), copyMode); } } else { copyFile(sourceLocation, targetLocation, copyMode); } } public void copyFile(final File source, final File target, final CopyMode copyMode) throws MojoExecutionException { if (CopyMode.FILE.equals(copyMode)) { if (target.exists() && Files.isSymbolicLink(target.toPath())) { target.delete(); } overCopyFile(source, target); } else { try { if (target.exists()) { Path targetPath = target.toPath(); if (Files.isSymbolicLink(targetPath)) { Path symbolicLinkTarget = Files.readSymbolicLink(targetPath); File symbolicLinkTargetFile = symbolicLinkTarget.toFile(); if (!symbolicLinkTargetFile.equals(source)) { target.delete(); createSymbolicLink(target, source); } } else { target.delete(); createSymbolicLink(target, source); } } else { createSymbolicLink(target, source); } } catch (IOException e) { throw new MojoExecutionException("Could not check the target of the symbolic link " + target.getAbsolutePath(), e); } } } public void createSymbolicLink(final File symbolicLinkFile, final File target) throws MojoExecutionException { if (symbolicLinkServerSocket == null) { try { Files.createSymbolicLink(symbolicLinkFile.toPath(), target.toPath()); } catch (FileSystemException e) { if (!isSystemSymbolicLinkCapable()) { throw new MojoExecutionException("Could not create symbolic link and it seems that the system is" + " not capable of handling symbolic links even with elevated mode", e); } startElevatedServer(); if (symbolicLinkServerSocket == null) { throw new MojoExecutionException("Could not create symbolicLink " + symbolicLinkFile.getAbsolutePath() + " with target " + target.getAbsolutePath() + " and starting elevated server failed", e); } } catch (IOException e) { throw new MojoExecutionException("Could not create symbolicLink " + symbolicLinkFile.getAbsolutePath() + " with target " + target.getAbsolutePath()); } } if (symbolicLinkServerSocket != null) { try { OutputStream outputStream = symbolicLinkServerSocket.getOutputStream(); String command = ElevatedSymbolicLinkServer.COMMAND_CREATE_SYMBOLIC_LINK + " " + target.toURI().toString() + " " + symbolicLinkFile.toURI().toString() + "\n"; outputStream.write(command.getBytes(Charset.defaultCharset())); } catch (IOException e) { throw new MojoExecutionException("Could not open stream to elevated symbolic link service", e); } } } private int getFreePort() throws MojoExecutionException { final int protectedPortRange = 1024; int maxPortNum = 65535; final int relativePortRange = maxPortNum - protectedPortRange - 1; Random r = new Random(); int freePort = 0; InetAddress localAddress; try { localAddress = InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new MojoExecutionException("Could not determine localhost address", e); } for (int i = 0, n = 50; i < n && freePort == 0; i++) { int port = r.nextInt(relativePortRange) + protectedPortRange + 1; log.info("Trying port if it is free to start the elevated symboliclink server " + port); try (Socket socket = new Socket(localAddress, port)) { String message = "Port " + port + " is not available."; if (i == n - 1) { message += " Trying another one"; } else { message += " This was the last try."; } log.info(message); } catch (IOException e) { freePort = port; } } if (freePort == 0) { throw new MojoExecutionException("Could not find free port for elevated symbolic link service"); } return freePort; } public boolean isSystemSymbolicLinkCapable() throws MojoExecutionException { String javaSpecVersion = System.getProperty("java.vm.specification.version"); boolean java7Compatible = (javaSpecVersion.compareTo("1.7") >= 0); if (!java7Compatible) { log.warn("Java version must be at least 1.7 to be able to create symbolic links"); return false; } String osname = System.getProperty("os.name").toLowerCase(); String osversion = System.getProperty("os.version"); if ((osname.indexOf("win") >= 0) && (osversion.compareTo("6.0") < 0)) { log.warn("Windows system must have version Vista or greater to be able to support symbolic links."); return false; } return true; } public boolean overCopyFile(final File source, final File target) throws MojoExecutionException { try (FileInputStream fin = new FileInputStream(source)) { return overCopyFile(fin, target); } catch (IOException e) { throw new MojoExecutionException("Cannot copy file " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e); } } /** * Copies an inputstream into a file. In case the file already exists, only those bytes are overwritten in the * target file that are changed. * * @param is * The inputstream of the source. * @param targetFile * The file that will be overridden if it is necessary. * @throws MojoExecutionException * @throws IOException * @throws FileNotFoundException */ public boolean overCopyFile(final InputStream is, final File targetFile) throws IOException { boolean fileChanged = false; boolean symbolicLink = Files.isSymbolicLink(targetFile.toPath()); if (symbolicLink) { targetFile.delete(); } long sum = 0; byte[] buffer = new byte[1024]; try (RandomAccessFile targetRAF = new RandomAccessFile(targetFile, "rw");) { long originalTargetLength = targetFile.length(); int r = is.read(buffer); while (r > -1) { sum += r; byte[] bytesInTarget = tryReadingAmount(targetRAF, r); if (!DistUtil.isBufferSame(buffer, r, bytesInTarget)) { fileChanged = true; targetRAF.seek(targetRAF.getFilePointer() - bytesInTarget.length); targetRAF.write(buffer, 0, r); } r = is.read(buffer); } if (sum < originalTargetLength) { targetRAF.setLength(sum); } } return fileChanged; } public final void replaceFileWithParsed(final File parseableFile, final VelocityContext context, final String encoding) throws IOException, MojoExecutionException { VelocityEngine ve = new VelocityEngine(); File tmpFile = File.createTempFile("eosgi-dist-parse", "tmp"); FileOutputStream fout = null; FileInputStream fin = null; InputStreamReader reader = null; OutputStreamWriter writer = null; try { fin = new FileInputStream(parseableFile); fout = new FileOutputStream(tmpFile); reader = new InputStreamReader(fin); writer = new OutputStreamWriter(fout); ve.evaluate(context, writer, parseableFile.getName(), reader); } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } copyFile(tmpFile, parseableFile, CopyMode.FILE); tmpFile.delete(); } private void startElevatedServer() throws MojoExecutionException { String javaHome = System.getProperty("java.home"); File javaExecutableFile = new File(javaHome, "bin/java.exe"); OperatingSystem operatingSystem = OperatingSystem.instance(); if (operatingSystem.getOperatingSystemName().toLowerCase().indexOf("win") < 0) { throw new MojoExecutionException("Elevated symboliclink service can be started only in windows"); } WindowsXPProcessManager windowsXPProcessManager = new WindowsXPProcessManager(); URL classPathURL = ElevatedSymbolicLinkServer.class.getProtectionDomain().getCodeSource().getLocation(); try { URI classpathURI = classPathURL.toURI(); File classpathFile = new File(classpathURI); WindowsXPProcess process = (WindowsXPProcess) windowsXPProcessManager.createProcess(); process.setTitle("Elevated symboliclink service"); process.setVisible(false); int port = getFreePort(); String command = "\"" + javaExecutableFile.getAbsolutePath() + "\" -cp \"" + classpathFile.getAbsolutePath() + "\" " + ElevatedSymbolicLinkServer.class.getName() + " " + port; log.info("Starting elevated symbolic link service with command: " + command); process.setCommand(command); process.startElevated(); log.info("Symboliclink service started"); InetAddress localHost; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new MojoExecutionException("Could not determine localhost", e); } for (int i = 0, n = 10; i < n && symbolicLinkServerSocket == null && process.isRunning(); i++) { try { symbolicLinkServerSocket = new Socket(localHost, port); shutdownHook = new ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); } catch (IOException e) { if (i < n - 1) { log.info("Waiting for symbolicLinkService to listen on port " + port); try { Thread.sleep(100); } catch (InterruptedException e1) { i = 10; Thread.currentThread().interrupt(); } } else { log.error("Could not open port to symbolic link service on port.", e); } } } if (symbolicLinkServerSocket == null && !process.isRunning()) { log.info("Stopping symbolic link service."); process.stop(100, -1); } } catch (URISyntaxException e) { throw new MojoExecutionException("Error during starting elevated symbolic link service", e); } } public byte[] tryReadingAmount(final RandomAccessFile is, final int amount) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(amount); byte[] buffer = new byte[amount]; int r = is.read(buffer); while (r > -1 && bout.size() < amount) { bout.write(buffer, 0, r); r = is.read(buffer, 0, amount - bout.size()); } return bout.toByteArray(); } public final void unpackZipFile(final File file, final File destinationDirectory) throws IOException { destinationDirectory.mkdirs(); ZipFile zipFile = new ZipFile(file); try { Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); File destFile = new File(destinationDirectory, name); if (entry.isDirectory()) { destFile.mkdirs(); } else { File parentFolder = destFile.getParentFile(); parentFolder.mkdirs(); InputStream inputStream = zipFile.getInputStream(entry); overCopyFile(inputStream, destFile); setUnixPermissionsOnFileIfNecessary(destFile, entry); } } } finally { zipFile.close(); } } }
package org.janelia.alignment; import ij.process.ByteProcessor; import ij.process.ColorProcessor; import ij.process.FloatProcessor; import java.awt.geom.AffineTransform; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import mpicbg.ij.blockmatching.BlockMatching; import mpicbg.models.AbstractAffineModel2D; import mpicbg.models.AbstractModel; import mpicbg.models.CoordinateTransform; import mpicbg.models.CoordinateTransformList; import mpicbg.models.ErrorStatistic; import mpicbg.models.IdentityModel; import mpicbg.models.InvertibleCoordinateTransform; import mpicbg.models.NoninvertibleModelException; import mpicbg.models.Point; import mpicbg.models.PointMatch; import mpicbg.models.RigidModel2D; import mpicbg.models.SpringMesh; import mpicbg.models.Vertex; import mpicbg.trakem2.align.Util; import mpicbg.trakem2.transform.AffineModel2D; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; public class MatchLayersByMaxPMCC { @Parameters static private class Params { @Parameter( names = "--help", description = "Display this note", help = true ) private final boolean help = false; @Parameter( names = "--inputfile1", description = "The first layer tilespec file", required = true ) private String inputfile1; @Parameter( names = "--inputfile2", description = "The second layer tilespec file", required = true ) private String inputfile2; @Parameter( names = "--modelsfile1", description = "The models from the first layer file", required = true ) private String modelsfile1; @Parameter( names = "--targetPath", description = "Path for the output correspondences", required = true ) public String targetPath; @Parameter( names = "--imageWidth", description = "The width of the entire image (all layers), for consistent mesh computation", required = true ) private int imageWidth; @Parameter( names = "--imageHeight", description = "The height of the entire image (all layers), for consistent mesh computation", required = true ) private int imageHeight; @Parameter( names = "--meshesDir1", description = "The directory where the cached mesh per tile of the first image is located", required = false ) private String meshesDir1 = null; @Parameter( names = "--meshesDir2", description = "The directory where the cached mesh per tile of the second image is located", required = false ) private String meshesDir2 = null; @Parameter( names = "--autoAddModel", description = "Automatically add the Identity model in case a model is not found", required = false ) private boolean autoAddModel = false; @Parameter( names = "--fixedLayers", description = "Fixed layer numbers (space separated)", variableArity = true, required = false ) public List<Integer> fixedLayers = new ArrayList<Integer>(); @Parameter( names = "--layerScale", description = "Layer scale", required = false ) public float layerScale = 0.1f; @Parameter( names = "--searchRadius", description = "Search window radius", required = false ) public int searchRadius = 200; @Parameter( names = "--blockRadius", description = "Matching block radius", required = false ) public int blockRadius = -1; // @Parameter( names = "--resolution", description = "Resolution", required = false ) // public int resolution = 16; @Parameter( names = "--minR", description = "minR", required = false ) public float minR = 0.6f; @Parameter( names = "--maxCurvatureR", description = "maxCurvatureR", required = false ) public float maxCurvatureR = 10.0f; @Parameter( names = "--rodR", description = "rodR", required = false ) public float rodR = 0.9f; @Parameter( names = "--useLocalSmoothnessFilter", description = "useLocalSmoothnessFilter", required = false ) public boolean useLocalSmoothnessFilter = false; @Parameter( names = "--localModelIndex", description = "localModelIndex", required = false ) public int localModelIndex = 1; // 0 = "Translation", 1 = "Rigid", 2 = "Similarity", 3 = "Affine" @Parameter( names = "--localRegionSigma", description = "localRegionSigma", required = false ) public float localRegionSigma = 200f; @Parameter( names = "--maxLocalEpsilon", description = "maxLocalEpsilon", required = false ) public float maxLocalEpsilon = 12f; @Parameter( names = "--maxLocalTrust", description = "maxLocalTrust", required = false ) public int maxLocalTrust = 3; //@Parameter( names = "--maxNumNeighbors", description = "maxNumNeighbors", required = false ) //public float maxNumNeighbors = 3f; @Parameter( names = "--resolutionSpringMesh", description = "resolutionSpringMesh", required = false ) private int resolutionSpringMesh = 32; @Parameter( names = "--stiffnessSpringMesh", description = "stiffnessSpringMesh", required = false ) public float stiffnessSpringMesh = 0.1f; @Parameter( names = "--dampSpringMesh", description = "dampSpringMesh", required = false ) public float dampSpringMesh = 0.9f; @Parameter( names = "--maxStretchSpringMesh", description = "maxStretchSpringMesh", required = false ) public float maxStretchSpringMesh = 2000.0f; @Parameter( names = "--springLengthSpringMesh", description = "spring_length", required = false ) public float springLengthSpringMesh = 100.0f; @Parameter( names = "--threads", description = "Number of threads to be used", required = false ) public int numThreads = Runtime.getRuntime().availableProcessors(); } private final static boolean PRINT_TIME_PER_STEP = true; private MatchLayersByMaxPMCC() {} /** * Receives a single layer, applies the transformations, and outputs the ip and mask * of the given level (render the ip and ipMask) * * @param layerTileSpecs * @param ip * @param ipMask * @param mipmapLevel */ private static void tilespecToFloatAndMask( final TileSpecsImage layerTileSpecsImage, final int layer, final FloatProcessor output, final FloatProcessor alpha, final int mipmapLevel, final float layerScale, final String meshesDir ) { final ByteProcessor tp; if ( meshesDir == null ) tp = layerTileSpecsImage.render( layer, mipmapLevel, layerScale ); else tp = layerTileSpecsImage.renderFromMeshes( meshesDir, layer, mipmapLevel, layerScale ); final byte[] inputPixels = ( byte[] )tp.getPixels(); for ( int i = 0; i < inputPixels.length; ++i ) { /* final int argb = inputPixels[ i ]; final int a = ( argb >> 24 ) & 0xff; final int r = ( argb >> 16 ) & 0xff; final int g = ( argb >> 8 ) & 0xff; final int b = argb & 0xff; final float v = ( r + g + b ) / ( float )3; final float w = a / ( float )255; output.setf( i, v ); alpha.setf( i, w ); */ output.setf( i, ( float )( inputPixels[ i ] / 255.0f )); alpha.setf( i, 1.0f ); } } /** * Receives a single layer, applies the transformations, and outputs the ip and mask * of the given level (render the ip and ipMask) * * @param layerTileSpecs * @param ip * @param ipMask * @param mipmapLevel */ private static FloatProcessor tilespecToFloatAndMask( final TileSpecsImage layerTileSpecsImage, final int layer, final int mipmapLevel, final float layerScale, final String meshesDir ) { final ByteProcessor tp; if ( meshesDir == null ) tp = layerTileSpecsImage.render( layer, mipmapLevel, layerScale ); else tp = layerTileSpecsImage.renderFromMeshes( meshesDir, layer, mipmapLevel, layerScale ); return tp.convertToFloatProcessor(); } /* private static Tile< ? >[] createLayersModels( int layersNum, int desiredModelIndex ) { /// create tiles and models for all layers final Tile< ? >[] tiles = new Tile< ? >[ layersNum ]; for ( int i = 0; i < layersNum; ++i ) { switch ( desiredModelIndex ) { case 0: tiles[i] = new Tile< TranslationModel2D >( new TranslationModel2D() ); break; case 1: tiles[i] = new Tile< RigidModel2D >( new RigidModel2D() ); break; case 2: tiles[i] = new Tile< SimilarityModel2D >( new SimilarityModel2D() ); break; case 3: tiles[i] = new Tile< AffineModel2D >( new AffineModel2D() ); break; case 4: tiles[i] = new Tile< HomographyModel2D >( new HomographyModel2D() ); break; default: throw new RuntimeException( "Unknown desired model" ); } } return tiles; } */ private static List< CorrespondenceSpec > matchLayersByMaxPMCC( final Params param, final AbstractModel< ? > model, final TileSpec[] ts1, final TileSpec[] ts2, int mipmapLevel, final List< Integer > fixedLayers ) { final List< CorrespondenceSpec > corr_data = new ArrayList< CorrespondenceSpec >(); /* final TileConfiguration initMeshes = new TileConfiguration(); */ final int layer1 = ts1[0].layer; final int layer2 = ts2[0].layer; final boolean layer1Fixed = fixedLayers.contains( layer1 ); final boolean layer2Fixed = fixedLayers.contains( layer2 ); if ( layer1Fixed && layer2Fixed ) { // Both layers are fixed, nothing to do... // Returns an empty correspondence spec list return corr_data; } // Compute bounding box of the two layers long startTime = System.currentTimeMillis(); // Create the meshes for the tiles /* final List< TileSpec[] > tsList = new ArrayList< TileSpec[] >(); tsList.add( ts1 ); tsList.add( ts2 ); final List< SpringMesh > meshes = Utils.createMeshes( tsList, param.imageWidth, param.imageHeight, param.springLengthSpringMesh, param.stiffnessSpringMesh, param.maxStretchSpringMesh, param.layerScale, param.dampSpringMesh ); */ final int meshWidth = ( int )Math.ceil( param.imageWidth * param.layerScale ); final int meshHeight = ( int )Math.ceil( param.imageHeight * param.layerScale ); final SpringMesh[] meshes = new SpringMesh[2]; for ( int i = 0; i < meshes.length; i++ ) meshes[i] = new SpringMesh( param.resolutionSpringMesh, meshWidth, meshHeight, param.stiffnessSpringMesh, param.maxStretchSpringMesh * param.layerScale, param.dampSpringMesh ); long endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("Creating mesh took: " + ((endTime - startTime) / 1000.0) + " sec"); //final int blockRadius = Math.max( 32, meshWidth / p.resolutionSpringMesh / 2 ); // final int param_blockRadius = param.imageWidth / param.resolution / 2; final int orig_param_resolution = 16; final int param_blockRadius; if ( param.blockRadius < 0 ) param_blockRadius = param.imageWidth / orig_param_resolution / 2; else param_blockRadius = param.blockRadius; final int blockRadius = Math.max( 16, mpicbg.util.Util.roundPos( param.layerScale * param_blockRadius ) ); // final int blockRadius = Math.max( mpicbg.util.Util.roundPos( 16 / param.layerScale ), param.blockRadius ); System.out.println( "effective block radius = " + blockRadius ); /* scale pixel distances */ final int searchRadius = ( int )Math.round( param.layerScale * param.searchRadius ); // final int searchRadius = param.searchRadius; final float localRegionSigma = param.layerScale * param.localRegionSigma; final float maxLocalEpsilon = param.layerScale * param.maxLocalEpsilon; // final float localRegionSigma = param.localRegionSigma; // final float maxLocalEpsilon = param.maxLocalEpsilon; startTime = System.currentTimeMillis(); final AbstractModel< ? > localSmoothnessFilterModel = Util.createModel( param.localModelIndex ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("Creating model took: " + ((endTime - startTime) / 1000.0) + " sec"); final SpringMesh m1 = meshes[ 0 ]; final SpringMesh m2 = meshes[ 1 ]; final ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); final ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final ArrayList< Vertex > v1 = m1.getVertices(); final ArrayList< Vertex > v2 = m2.getVertices(); //if ( !( layer1Fixed && layer2Fixed ) ) /* Load images and masks into FloatProcessor objects */ System.out.println( "Rendering layers" ); startTime = System.currentTimeMillis(); final TileSpecsImage layer1Img = new TileSpecsImage( ts1 ); final TileSpecsImage layer2Img = new TileSpecsImage( ts2 ); layer1Img.setThreadsNum( param.numThreads ); layer2Img.setThreadsNum( param.numThreads ); /* final BoundingBox layer1BBox = layer1Img.getBoundingBox(); final BoundingBox layer2BBox = layer2Img.getBoundingBox(); final int img1Width = (int) (layer1BBox.getWidth() * param.layerScale); final int img1Height = (int) (layer1BBox.getHeight() * param.layerScale); final int img2Width = (int) (layer2BBox.getWidth() * param.layerScale); final int img2Height = (int) (layer2BBox.getHeight() * param.layerScale); final FloatProcessor ip1 = new FloatProcessor( img1Width, img1Height ); final FloatProcessor ip2 = new FloatProcessor( img2Width, img2Height ); final FloatProcessor ip1Mask = new FloatProcessor( img1Width, img1Height ); final FloatProcessor ip2Mask = new FloatProcessor( img2Width, img2Height ); */ // TODO: load the tile specs to FloatProcessor objects final FloatProcessor ip1 = tilespecToFloatAndMask( layer1Img, layer1, mipmapLevel, param.layerScale, param.meshesDir1 ); final FloatProcessor ip2 = tilespecToFloatAndMask( layer2Img, layer2, mipmapLevel, param.layerScale, param.meshesDir2 ); // tilespecToFloatAndMask( layer1Img, layer1, ip1, ip1Mask, mipmapLevel, param.layerScale, param.meshesDir1 ); // tilespecToFloatAndMask( layer2Img, layer2, ip2, ip2Mask, mipmapLevel, param.layerScale, param.meshesDir2 ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("Creating images took: " + ((endTime - startTime) / 1000.0) + " sec"); //final float springConstant = 1.0f / ( layer2 - layer1 ); // Scale the affine transformation final AffineTransform scaleDown = new AffineTransform(); scaleDown.scale( param.layerScale, param.layerScale ); final AffineModel2D scaleDownModel = new AffineModel2D(); scaleDownModel.set( scaleDown ); final CoordinateTransformList< CoordinateTransform > scaledModel = new CoordinateTransformList< CoordinateTransform >(); scaledModel.add( scaleDownModel.createInverse() ); scaledModel.add( ( CoordinateTransform )model ); scaledModel.add( scaleDownModel ); final CoordinateTransformList< CoordinateTransform > scaledInverseModel = new CoordinateTransformList< CoordinateTransform >(); scaledInverseModel.add( scaleDownModel.createInverse() ); scaledInverseModel.add( ( ( InvertibleCoordinateTransform )model ).createInverse() ); scaledInverseModel.add( scaleDownModel ); if ( ! layer1Fixed ) { try { startTime = System.currentTimeMillis(); BlockMatching.matchByMaximalPMCC( ip1, ip2, null,//ip1Mask, null,//ip2Mask, 1.0f, scaledInverseModel, //( ( InvertibleCoordinateTransform )model ).createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, param.minR, param.rodR, param.maxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("Block matching 1 took: " + ((endTime - startTime) / 1000.0) + " sec"); } catch ( final InterruptedException e ) { System.err.println( "Block matching interrupted." ); //IJ.showProgress( 1.0 ); throw new RuntimeException( e ); } catch ( final ExecutionException e ) { System.out.println( "Block matching interrupted." ); throw new RuntimeException( e ); } if ( Thread.interrupted() ) { System.err.println( "Block matching interrupted." ); //IJ.showProgress( 1.0 ); throw new RuntimeException( "Block matching interrupted." ); } if ( param.useLocalSmoothnessFilter ) { startTime = System.currentTimeMillis(); System.out.println( layer1 + " > " + layer2 + ": found " + pm12.size() + " correspondence candidates." ); localSmoothnessFilterModel.localSmoothnessFilter( pm12, pm12, localRegionSigma, maxLocalEpsilon, param.maxLocalTrust ); System.out.println( layer1 + " > " + layer2 + ": " + pm12.size() + " candidates passed local smoothness filter." ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("local smooth filter 1 took: " + ((endTime - startTime) / 1000.0) + " sec"); } else { System.out.println( layer1 + " > " + layer2 + ": found " + pm12.size() + " correspondences." ); } /* <visualisation> */ // final List< Point > s1 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm12, s1 ); // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // imp1.show(); // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // imp1.updateAndDraw(); /* </visualisation> */ /* for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m2.addPassiveVertex( p2 ); } */ /* * adding Tiles to the initialing TileConfiguration, adding a Tile * multiple times does not harm because the TileConfiguration is * backed by a Set. */ /* if ( pm12.size() > model.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t1.connect( t2, pm12 ); } */ // Remove Vertex (spring mesh) details from points final ArrayList< PointMatch > pm12_strip = new ArrayList< PointMatch >(); for (PointMatch pm: pm12) { PointMatch actualPm; try { actualPm = new PointMatch( new Point( pm.getP1().getL(), scaleDownModel.applyInverse( pm.getP1().getW() ) ), new Point( pm.getP2().getL(), scaleDownModel.applyInverse( pm.getP2().getW() ) ) ); pm12_strip.add( actualPm ); } catch (NoninvertibleModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO: Export / Import master sprint mesh vertices no calculated individually per tile (v1, v2). corr_data.add(new CorrespondenceSpec( mipmapLevel, param.inputfile1, param.inputfile2, pm12_strip, ( pm12.size() > model.getMinNumMatches() ) )); } if ( !layer2Fixed ) { try { startTime = System.currentTimeMillis(); BlockMatching.matchByMaximalPMCC( ip2, ip1, null,//ip2Mask, null,//ip1Mask, 1.0f, scaledModel, //model, blockRadius, blockRadius, searchRadius, searchRadius, param.minR, param.rodR, param.maxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("Block matching 2 took: " + ((endTime - startTime) / 1000.0) + " sec"); } catch ( final InterruptedException e ) { System.out.println( "Block matching interrupted." ); //IJ.showProgress( 1.0 ); throw new RuntimeException( e ); } catch ( final ExecutionException e ) { System.out.println( "Block matching interrupted." ); throw new RuntimeException( e ); } if ( Thread.interrupted() ) { System.out.println( "Block matching interrupted." ); //IJ.showProgress( 1.0 ); throw new RuntimeException( "Block matching interrupted." ); } if ( param.useLocalSmoothnessFilter ) { startTime = System.currentTimeMillis(); System.out.println( layer1 + " < " + layer2 + ": found " + pm21.size() + " correspondence candidates." ); localSmoothnessFilterModel.localSmoothnessFilter( pm21, pm21, localRegionSigma, maxLocalEpsilon, param.maxLocalTrust ); System.out.println( layer1 + " < " + layer2 + ": " + pm21.size() + " candidates passed local smoothness filter." ); endTime = System.currentTimeMillis(); if ( PRINT_TIME_PER_STEP ) System.out.println("local smooth filter 2 took: " + ((endTime - startTime) / 1000.0) + " sec"); } else { System.out.println( layer1 + " < " + layer2 + ": found " + pm21.size() + " correspondences." ); } /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ /* for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m1.addPassiveVertex( p2 ); } */ /* * adding Tiles to the initialing TileConfiguration, adding a Tile * multiple times does not harm because the TileConfiguration is * backed by a Set. */ /* if ( pm21.size() > model.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t2.connect( t1, pm21 ); } */ // Remove Vertex (spring mesh) details from points final ArrayList< PointMatch > pm21_strip = new ArrayList< PointMatch >(); for (PointMatch pm: pm21) { PointMatch actualPm; try { actualPm = new PointMatch( new Point( pm.getP1().getL(), scaleDownModel.applyInverse( pm.getP1().getW() ) ), new Point( pm.getP2().getL(), scaleDownModel.applyInverse( pm.getP2().getW() ) ) ); pm21_strip.add( actualPm ); } catch (NoninvertibleModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO: Export / Import master sprint mesh vertices no calculated individually per tile (v1, v2). corr_data.add(new CorrespondenceSpec( mipmapLevel, param.inputfile2, param.inputfile1, pm21_strip, ( pm21.size() > model.getMinNumMatches() ) )); } //System.out.println( layer1 + " <> " + layer2 + " spring constant = " + springConstant ); return corr_data; } private static List<CorrespondenceSpec> createEmptyCorrespondece( final int layer1, final int layer2, final Params param, final int mipmapLevel, final List<Integer> fixedLayers ) { final List< CorrespondenceSpec > corr_data = new ArrayList< CorrespondenceSpec >(); final boolean layer1Fixed = fixedLayers.contains( layer1 ); final boolean layer2Fixed = fixedLayers.contains( layer2 ); if ( layer1Fixed && layer2Fixed ) { // Both layers are fixed, nothing to do... // Returns an empty correspondence spec list return corr_data; } if ( ! layer1Fixed ) { corr_data.add(new CorrespondenceSpec( mipmapLevel, param.inputfile1, param.inputfile2, null, false )); } if ( ! layer2Fixed ) { corr_data.add(new CorrespondenceSpec( mipmapLevel, param.inputfile2, param.inputfile1, null, false )); } return corr_data; } public static void main( final String[] args ) { final Params params = new Params(); try { final JCommander jc = new JCommander( params, args ); if ( params.help ) { jc.usage(); return; } } catch ( final Exception e ) { e.printStackTrace(); final JCommander jc = new JCommander( params ); jc.setProgramName( "java [-options] -cp render.jar org.janelia.alignment.RenderTile" ); jc.usage(); return; } // The mipmap level to work on // TODO: Should be a parameter from the user, // and decide whether or not to create the mipmaps if they are missing int mipmapLevel = 0; /* Open the tilespecs */ TileSpec[] tilespecs1 = TileSpecUtils.readTileSpecFile( params.inputfile1 ); TileSpec[] tilespecs2 = TileSpecUtils.readTileSpecFile( params.inputfile2 ); /* open the models */ long startTime = System.currentTimeMillis(); CoordinateTransform model = null; try { final ModelSpec[] modelSpecs; final Gson gson = new Gson(); URL url = new URL( params.modelsfile1 ); modelSpecs = gson.fromJson( new InputStreamReader( url.openStream() ), ModelSpec[].class ); for ( ModelSpec ms : modelSpecs ) { if ( (( params.inputfile1.equals( ms.url1 ) ) && ( params.inputfile2.equals( ms.url2 ) )) || (( params.inputfile1.equals( ms.url2 ) ) && ( params.inputfile2.equals( ms.url1 ) )) ) { model = ms.createModel(); } } if ( model == null ) { if ( params.autoAddModel ) model = new IdentityModel(); else { // Write an "empty" file final List< CorrespondenceSpec > corr_data = createEmptyCorrespondece( tilespecs1[0].layer, tilespecs2[0].layer, params, mipmapLevel, params.fixedLayers ); System.out.println( "Writing an empty correspondece match file between layers: " + params.inputfile1 + " and " + params.inputfile2 ); try { Writer writer = new FileWriter(params.targetPath); //Gson gson = new GsonBuilder().create(); Gson gsonOut = new GsonBuilder().setPrettyPrinting().create(); gsonOut.toJson(corr_data, writer); writer.close(); return; } catch ( final IOException e ) { System.err.println( "Error writing JSON file: " + params.targetPath ); e.printStackTrace( System.err ); } } } } catch ( final MalformedURLException e ) { System.err.println( "URL malformed." ); e.printStackTrace( System.err ); return; } catch ( final JsonSyntaxException e ) { System.err.println( "JSON syntax malformed." ); e.printStackTrace( System.err ); return; } catch ( final Exception e ) { e.printStackTrace( System.err ); return; } long endTime = System.currentTimeMillis(); System.out.println("Parsing files took: " + ((endTime - startTime) / 1000.0) + " ms"); startTime = System.currentTimeMillis(); final List< CorrespondenceSpec > corr_data = matchLayersByMaxPMCC( params, (AbstractModel< ? >)model, tilespecs1, tilespecs2, mipmapLevel, params.fixedLayers ); endTime = System.currentTimeMillis(); System.out.println("Entire match process took: " + ((endTime - startTime) / 1000.0) + " ms"); // In case no correspondence points are found, write an "empty" file startTime = System.currentTimeMillis(); try { Writer writer = new FileWriter(params.targetPath); //Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(corr_data, writer); writer.close(); } catch ( final IOException e ) { System.err.println( "Error writing JSON file: " + params.targetPath ); e.printStackTrace( System.err ); } endTime = System.currentTimeMillis(); System.out.println("Writing output took: " + ((endTime - startTime) / 1000.0) + " ms"); } }
package org.jtrfp.trcl.conf; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashSet; import javax.swing.DefaultListModel; import org.jtrfp.trcl.core.Feature; import org.jtrfp.trcl.core.FeatureFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.flow.GameVersion; import org.springframework.stereotype.Component; /** * This is a temporary stand-in for TRConfiguration to provide backwards compatability with pre-Feature configs. * @author Chuck Ritola * */ //TODO: Migrate into TR class and/or other Features. @Component public class TRConfigurationFactory implements FeatureFactory<TR>{ public static final String ACTIVE_AUDIO_DRIVER = "activeAudioDriver", ACTIVE_AUDIO_DEVICE = "activeAudioDevice", ACTIVE_AUDIO_OUTPUT = "activeAudioOutput", ACTIVE_AUDIO_FORMAT = "activeAudioFormat", AUDIO_BUFFER_LAG = "audioBufferLag", AUDIO_BUFFER_SIZE = "audioBufferSize", CROSSHAIRS_ENABLED = "crosshairsEnabled"; public static class TRConfiguration implements Feature<TR>{ private GameVersion gameVersion=GameVersion.F3; private Boolean usingTextureBufferUnmap, debugMode, waitForProfiler; private int targetFPS =60, audioBufferSize = 4096; private String skipToLevel; private String voxFile; private boolean audioLinearFiltering=false, audioBufferLag=true, crosshairsEnabled = true; private HashSet<String> missionList = new HashSet<String>(); private String activeAudioDriver = "org.jtrfp.trcl.snd.JavaSoundSystemAudioOutput", activeAudioDevice, activeAudioOutput, activeAudioFormat; //private HashSet<String> podList = new HashSet<String>(); //private DefaultListModel podList=new DefaultListModel(); private double modStereoWidth=.3; public static final String AUTO_DETECT = "Auto-detect"; private String fileDialogStartDir; //private Map<String,Object> componentConfigs; private ConfigRootFeature.FeatureTreeElement featureTreeElements; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); public TRConfiguration(){//DEFAULTS missionList.add(AUTO_DETECT); missionList.add("Fury3"); missionList.add("TV"); missionList.add("FurySE"); } //@Transient public GameVersion _getGameVersion() { return gameVersion; } //@Transient public void _setGameVersion(GameVersion gameVersion){ this.gameVersion=gameVersion; } public boolean isUsingTextureBufferUnmap() { if(usingTextureBufferUnmap!=null)return usingTextureBufferUnmap; boolean result=true; if(System.getProperties().containsKey("org.jtrfp.trcl.Renderer.unmapTextureBuffer")){ if(System.getProperty("org.jtrfp.trcl.Renderer.unmapTextureBuffer").toUpperCase().contains("FALSE")) result=false; }//end if(contains key) usingTextureBufferUnmap=result; return result; }//end isUsingTextureBufferUnmap() public boolean isDebugMode() { if(debugMode!=null)return debugMode; boolean result=false; if(System.getProperties().containsKey("org.jtrfp.trcl.debugMode")){ if(System.getProperty("org.jtrfp.trcl.debugMode").toUpperCase().contains("TRUE")) result=true; }//end if(contains key) debugMode=result; return result; }//end isDebugMode() public int getTargetFPS() { return targetFPS; }//end getTargetFPS() public String skipToLevel() { if(skipToLevel==null){ skipToLevel = System.getProperty("org.jtrfp.trcl.flow.Game.skipToLevel"); }//end if(skipToLevel==null) return skipToLevel; }//end skipToLevel /** * @return the voxFile */ public String getVoxFile() { String result = voxFile; if(result==null) result = voxFile = AUTO_DETECT; return result; } /** * @param voxFile the voxFile to set */ public void setVoxFile(String voxFile) { this.voxFile = voxFile; } public boolean isWaitForProfiler() { if(waitForProfiler!=null)return waitForProfiler; boolean result=false; if(System.getProperties().containsKey("org.jtrfp.trcl.dbg.waitForProfiler")){ if(System.getProperty("org.jtrfp.trcl.dbg.waitForProfiler").toUpperCase().contains("TRUE")) result=true; }//end if(contains key) waitForProfiler=result; return result; } /** * @return the audioLinearFiltering */ public boolean isAudioLinearFiltering() { return audioLinearFiltering; } /** * @param audioLinearFiltering the audioLinearFiltering to set */ public void setAudioLinearFiltering(boolean audioLinearFiltering) { this.audioLinearFiltering = audioLinearFiltering; } /** * @return the missionList */ public HashSet<String> getMissionList() { return missionList; } /** * @param missionList the missionList to set */ public void setMissionList(HashSet<String> missionList) { this.missionList = missionList; } /** * @return the modStereoWidth */ public double getModStereoWidth() { return modStereoWidth; } /** * @param modStereoWidth the modStereoWidth to set */ public void setModStereoWidth(double modStereoWidth) { this.modStereoWidth = modStereoWidth; } public String getFileDialogStartDir() { if(fileDialogStartDir!=null) return fileDialogStartDir; return System.getProperty("user.home"); } /** * @param fileDialogStartDir the fileDialogStartDir to set */ public void setFileDialogStartDir(String fileDialogStartDir) { this.fileDialogStartDir = fileDialogStartDir; } /** * @return the soundDriver */ public String getActiveAudioDriver() { return activeAudioDriver; } /** * @param soundDriver the soundDriver to set */ public void setActiveSoundDriver(String soundDriver) { pcs.firePropertyChange(ACTIVE_AUDIO_DRIVER,this.activeAudioDriver,soundDriver); this.activeAudioDriver = soundDriver; } /** * @return the audioOutput */ public String getActiveAudioOutput() { return activeAudioOutput; } /** * @param audioOutput the audioOutput to set */ public void setActiveAudioOutput(String audioOutput) { pcs.firePropertyChange(ACTIVE_AUDIO_OUTPUT,this.activeAudioOutput,audioOutput); this.activeAudioOutput = audioOutput; } /** * @return the activeAudioDevice */ public String getActiveAudioDevice() { return activeAudioDevice; } /** * @param activeAudioDevice the activeAudioDevice to set */ public void setActiveAudioDevice(String activeAudioDevice) { pcs.firePropertyChange(ACTIVE_AUDIO_DEVICE,this.activeAudioDevice,activeAudioDevice); this.activeAudioDevice = activeAudioDevice; } /** * @return the activeAudioFormat */ public String getActiveAudioFormat() { return activeAudioFormat; } /** * @param activeAudioFormat the activeAudioFormat to set */ public void setActiveAudioFormat(String activeAudioFormat) { pcs.firePropertyChange(ACTIVE_AUDIO_FORMAT,this.activeAudioFormat,activeAudioFormat); this.activeAudioFormat = activeAudioFormat; } /** * @param listener * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener) */ public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } /** * @param propertyName * @param listener * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } /** * @return * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners() */ public PropertyChangeListener[] getPropertyChangeListeners() { return pcs.getPropertyChangeListeners(); } /** * @param propertyName * @return * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners(java.lang.String) */ public PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { return pcs.getPropertyChangeListeners(propertyName); } /** * @param propertyName * @return * @see java.beans.PropertyChangeSupport#hasListeners(java.lang.String) */ public boolean hasListeners(String propertyName) { return pcs.hasListeners(propertyName); } /** * @param listener * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener) */ public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } /** * @param propertyName * @param listener * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.removePropertyChangeListener(propertyName, listener); } /** * @return the audioBufferLag */ public boolean isAudioBufferLag() { return audioBufferLag; } /** * @param audioBufferLag the audioBufferLag to set */ public void setAudioBufferLag(boolean audioBufferLag) { pcs.firePropertyChange(AUDIO_BUFFER_LAG, this.audioBufferLag, audioBufferLag); this.audioBufferLag = audioBufferLag; } /** * @return the audioBufferSize */ public int getAudioBufferSize() { return audioBufferSize; } /** * @param audioBufferSize the audioBufferSize to set */ public void setAudioBufferSize(int audioBufferSize) { pcs.firePropertyChange(AUDIO_BUFFER_SIZE, this.audioBufferSize, audioBufferSize); this.audioBufferSize = audioBufferSize; } public boolean isCrosshairsEnabled() { return crosshairsEnabled; } /** * @param crosshairsEnabled the crosshairsEnabled to set */ public void setCrosshairsEnabled(boolean crosshairsEnabled) { final boolean oldValue = this.crosshairsEnabled; this.crosshairsEnabled = crosshairsEnabled; pcs.firePropertyChange(CROSSHAIRS_ENABLED,oldValue,crosshairsEnabled); } /* public Map<String, Object> getComponentConfigs() { if(componentConfigs==null) componentConfigs = new HashMap<String,Object>(); return componentConfigs; } public void setComponentConfigs(Map<String, Object> componentConfigs) { this.componentConfigs = componentConfigs; }*/ public ConfigRootFeature.FeatureTreeElement getFeatureTreeElements() { return featureTreeElements; } public void setFeatureTreeElements( ConfigRootFeature.FeatureTreeElement featureTreeElements) { this.featureTreeElements = featureTreeElements; } @Override public void apply(TR target) { // TODO Auto-generated method stub } @Override public void destruct(TR target) { // TODO Auto-generated method stub } }//end TRConfiguration @Override public Feature<TR> newInstance(TR target) { return new TRConfiguration(); } @Override public Class<TR> getTargetClass() { return TR.class; } @Override public Class<? extends Feature> getFeatureClass() { return TRConfiguration.class; } }//end TRConfiguration