answer
stringlengths
17
10.2M
package org.zwobble.mammoth.tests; import org.junit.Test; import org.zwobble.mammoth.DocumentConverter; import org.zwobble.mammoth.Result; import org.zwobble.mammoth.images.ImageConverter; import org.zwobble.mammoth.internal.archives.InMemoryArchive; import org.zwobble.mammoth.internal.docx.EmbeddedStyleMap; import org.zwobble.mammoth.internal.styles.parsing.ParseException; import org.zwobble.mammoth.internal.util.Base64Encoding; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Function; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.zwobble.mammoth.internal.util.Lists.list; import static org.zwobble.mammoth.internal.util.Maps.map; import static org.zwobble.mammoth.tests.ResultMatchers.isResult; import static org.zwobble.mammoth.tests.ResultMatchers.isSuccess; import static org.zwobble.mammoth.tests.util.MammothAsserts.assertThrows; public class MammothTests { @Test public void docxContainingOneParagraphIsConvertedToSingleParagraphElement() throws IOException { assertThat( convertToHtml("single-paragraph.docx"), isSuccess("<p>Walking on imported air</p>")); } @Test public void canReadFilesWithUtf8Bom() throws IOException { assertThat( convertToHtml("utf8-bom.docx"), isSuccess("<p>This XML has a byte order mark.</p>")); } @Test public void emptyParagraphsAreIgnoredByDefault() throws IOException { assertThat( convertToHtml("empty.docx"), isSuccess("")); } @Test public void emptyParagraphsArePreservedIfIgnoreEmptyParagraphsIsFalse() throws IOException { assertThat( convertToHtml("empty.docx", mammoth -> mammoth.preserveEmptyParagraphs()), isSuccess("<p></p>")); } @Test public void simpleListIsConvertedToListElements() throws IOException { assertThat( convertToHtml("simple-list.docx"), isSuccess("<ul><li>Apple</li><li>Banana</li></ul>")); } @Test public void wordTablesAreConvertedToHtmlTables() throws IOException { assertThat( convertToHtml("tables.docx"), isSuccess( "<p>Above</p>" + "<table>" + "<tr><td><p>Top left</p></td><td><p>Top right</p></td></tr>" + "<tr><td><p>Bottom left</p></td><td><p>Bottom right</p></td></tr>" + "</table>" + "<p>Below</p>")); } @Test public void inlineImagesReferencedByPathRelativeToPartAreIncludedInOutput() throws IOException { assertThat( convertToHtml("tiny-picture.docx"), isSuccess("<p><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOvgAADr4B6kKxwAAAABNJREFUKFNj/M+ADzDhlWUYqdIAQSwBE8U+X40AAAAASUVORK5CYII=\" /></p>")); } @Test public void inlineImagesReferencedByPathRelativeToBaseAreIncludedInOutput() throws IOException { assertThat( convertToHtml("tiny-picture-target-base-relative.docx"), isSuccess("<p><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOvgAADr4B6kKxwAAAABNJREFUKFNj/M+ADzDhlWUYqdIAQSwBE8U+X40AAAAASUVORK5CYII=\" /></p>")); } @Test public void imagesStoredOutsideOfDocumentAreIncludedInOutput() throws IOException { Path tempDirectory = Files.createTempDirectory("mammoth-"); try { Path documentPath = tempDirectory.resolve("external-picture.docx"); Files.copy(TestData.file("external-picture.docx").toPath(), documentPath); Files.copy(TestData.file("tiny-picture.png").toPath(), tempDirectory.resolve("tiny-picture.png")); assertThat( new DocumentConverter().convertToHtml(documentPath.toFile()), isSuccess("<p><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOvgAADr4B6kKxwAAAABNJREFUKFNj/M+ADzDhlWUYqdIAQSwBE8U+X40AAAAASUVORK5CYII=\" /></p>")); } finally { tempDirectory.toFile().delete(); } } @Test public void warnIfDocumentHasImagesStoredOutsideOfDocumentWhenPathOfDocumentIsUnknown() throws IOException { Path tempDirectory = Files.createTempDirectory("mammoth-"); try { Path documentPath = tempDirectory.resolve("external-picture.docx"); Files.copy(TestData.file("external-picture.docx").toPath(), documentPath); assertThat( new DocumentConverter().convertToHtml(documentPath.toUri().toURL().openStream()), allOf( hasProperty("value", equalTo("")), hasProperty("warnings", contains( startsWith("could not open external image 'tiny-picture.png': path of document is unknown, but is required for relative URI"))))); } finally { tempDirectory.toFile().delete(); } } @Test public void warnIfImagesStoredOutsideOfDocumentAreNotFound() throws IOException { Path tempDirectory = Files.createTempDirectory("mammoth-"); try { Path documentPath = tempDirectory.resolve("external-picture.docx"); Files.copy(TestData.file("external-picture.docx").toPath(), documentPath); assertThat( new DocumentConverter().convertToHtml(documentPath.toFile()), allOf( hasProperty("value", equalTo("")), hasProperty("warnings", contains( startsWith("could not open external image 'tiny-picture.png'"))))); } finally { tempDirectory.toFile().delete(); } } @Test public void imageConversionCanBeCustomised() throws IOException { ImageConverter.ImgElement imageConverter = image -> { String base64 = Base64Encoding.streamToBase64(image::getInputStream); String src = base64.substring(0, 2) + "," + image.getContentType(); return map("src", src); }; assertThat( convertToHtml("tiny-picture.docx", converter -> converter.imageConverter(imageConverter)), isSuccess("<p><img src=\"iV,image/png\" /></p>") ); } @Test public void contentTypesAreRead() throws IOException { assertThat( convertToHtml("tiny-picture-custom-content-type.docx"), isSuccess("<p><img src=\"data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOvgAADr4B6kKxwAAAABNJREFUKFNj/M+ADzDhlWUYqdIAQSwBE8U+X40AAAAASUVORK5CYII=\" /></p>")); } @Test public void footnotesAreAppendedToText() throws IOException { assertThat( convertToHtml("footnotes.docx", mammoth -> mammoth.idPrefix("doc-42-")), isSuccess( "<p>Ouch" + "<sup><a href=\"#doc-42-footnote-1\" id=\"doc-42-footnote-ref-1\">[1]</a></sup>." + "<sup><a href=\"#doc-42-footnote-2\" id=\"doc-42-footnote-ref-2\">[2]</a></sup></p>" + "<ol><li id=\"doc-42-footnote-1\"><p> A tachyon walks into a bar. <a href=\" "<li id=\"doc-42-footnote-2\"><p> Fin. <a href=\" } @Test public void endNotesAreAppendedToText() throws IOException { assertThat( convertToHtml("endnotes.docx", mammoth -> mammoth.idPrefix("doc-42-")), isSuccess( "<p>Ouch" + "<sup><a href=\"#doc-42-endnote-2\" id=\"doc-42-endnote-ref-2\">[1]</a></sup>." + "<sup><a href=\"#doc-42-endnote-3\" id=\"doc-42-endnote-ref-3\">[2]</a></sup></p>" + "<ol><li id=\"doc-42-endnote-2\"><p> A tachyon walks into a bar. <a href=\" "<li id=\"doc-42-endnote-3\"><p> Fin. <a href=\" } @Test public void whenStyleMappingIsDefinedForCommentReferencesThenCommentsAreIncluded() throws IOException { assertThat( convertToHtml("comments.docx", mammoth -> mammoth.idPrefix("doc-42-").addStyleMap("comment-reference => sup")), isSuccess( "<p>Ouch" + "<sup><a href=\"#doc-42-comment-0\" id=\"doc-42-comment-ref-0\">[MW1]</a></sup>." + "<sup><a href=\"#doc-42-comment-2\" id=\"doc-42-comment-ref-2\">[MW2]</a></sup></p>" + "<dl><dt id=\"doc-42-comment-0\">Comment [MW1]</dt><dd><p>A tachyon walks into a bar. <a href=\" "<dt id=\"doc-42-comment-2\">Comment [MW2]</dt><dd><p>Fin. <a href=\" )); } @Test public void relationshipsAreReadForEachFileContainingBodyXml() throws IOException { assertThat( convertToHtml("footnote-hyperlink.docx", mammoth -> mammoth.idPrefix("doc-42-")), isSuccess( "<p><sup><a href=\"#doc-42-footnote-1\" id=\"doc-42-footnote-ref-1\">[1]</a></sup></p>" + "<ol><li id=\"doc-42-footnote-1\"><p> <a href=\"http://www.example.com\">Example</a> <a href=\" } @Test public void textBoxesAreRead() throws IOException { assertThat( convertToHtml("text-box.docx"), isSuccess("<p>Datum plane</p>")); } @Test public void canUseCustomStyleMap() throws IOException { assertThat( convertToHtml("underline.docx", mammoth -> mammoth.addStyleMap("u => em")), isSuccess("<p><strong>The <em>Sunset</em> Tree</strong></p>")); } @Test public void mostRecentlyAddedStyleMapTakesPrecedence() throws IOException { assertThat( convertToHtml("underline.docx", mammoth -> mammoth.addStyleMap("u => em").addStyleMap("u => strong")), isSuccess("<p><strong>The <strong>Sunset</strong> Tree</strong></p>")); } @Test public void rulesFromPreviouslyAddedStyleMapsStillTakeEffectIfNotOverriden() throws IOException { assertThat( convertToHtml("underline.docx", mammoth -> mammoth.addStyleMap("u => em").addStyleMap("strike => del")), isSuccess("<p><strong>The <em>Sunset</em> Tree</strong></p>")); } @Test public void errorIsRaisedIfStyleMapCannotBeParsed() throws IOException { RuntimeException exception = assertThrows( ParseException.class, () -> new DocumentConverter().addStyleMap("p =>\np[style-name=] =>")); assertThat( exception.getMessage(), equalTo( "error reading style map at line 2, character 14: expected token of type STRING but was of type SYMBOL\n\n" + "p[style-name=] =>\n" + " ^")); } @Test public void canDisableDefaultStyleMap() throws IOException { assertThat( convertToHtml("simple-list.docx", mammoth -> mammoth.disableDefaultStyleMap()), isResult( equalTo("<p>Apple</p><p>Banana</p>"), list("Unrecognised paragraph style: List Paragraph (Style ID: ListParagraph)"))); } @Test public void embeddedStyleMapIsUsedIfPresent() throws IOException { assertThat( convertToHtml("embedded-style-map.docx"), isSuccess("<h1>Walking on imported air</h1>") ); } @Test public void explicitStyleMapTakesPrecedenceOverEmbeddedStyleMap() throws IOException { assertThat( convertToHtml("embedded-style-map.docx", options -> options.addStyleMap("p => p")), isSuccess("<p>Walking on imported air</p>") ); } @Test public void explicitStyleMapIsCombinedWithEmbeddedStyleMap() throws IOException { assertThat( convertToHtml("embedded-style-map.docx", options -> options.addStyleMap("r => strong")), isSuccess("<h1><strong>Walking on imported air</strong></h1>") ); } @Test public void embeddedStyleMapsCanBeDisabled() throws IOException { assertThat( convertToHtml("embedded-style-map.docx", options -> options.disableEmbeddedStyleMap()), isSuccess("<p>Walking on imported air</p>") ); } @Test public void embeddedStyleMapCanBeWrittenAndThenRead() throws IOException { InMemoryArchive archive = InMemoryArchive.fromStream(new FileInputStream(TestData.file("single-paragraph.docx"))); EmbeddedStyleMap.embedStyleMap(archive, "p => h1"); assertThat( new DocumentConverter().convertToHtml(new ByteArrayInputStream(archive.toByteArray())), isSuccess("<h1>Walking on imported air</h1>") ); } @Test public void canExtractRawTextFromFile() throws IOException { assertThat( new DocumentConverter().extractRawText(TestData.file("simple-list.docx")), isSuccess("Apple\n\nBanana\n\n")); } @Test public void canExtractRawTextFromStream() throws IOException { assertThat( new DocumentConverter().extractRawText(TestData.file("simple-list.docx").toURI().toURL().openStream()), isSuccess("Apple\n\nBanana\n\n")); } private Result<String> convertToHtml(String name) throws IOException { File file = TestData.file(name); return new DocumentConverter().convertToHtml(file); } private Result<String> convertToHtml(String name, Function<DocumentConverter, DocumentConverter> configure) throws IOException { File file = TestData.file(name); return configure.apply(new DocumentConverter()).convertToHtml(file); } }
package seedu.todo.guitests; import static org.junit.Assert.assertEquals; import java.time.LocalDateTime; import org.junit.Before; import org.junit.Test; import seedu.todo.commons.util.DateUtil; import seedu.todo.controllers.DestroyController; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.models.Event; import seedu.todo.models.Task; /** * @@author A0093907W */ public class DestroyCommandTest extends GuiTest { private final LocalDateTime oneDayFromNow = LocalDateTime.now().plusDays(1); private final String oneDayFromNowString = DateUtil.formatDate(oneDayFromNow); private final String oneDayFromNowIsoString = DateUtil.formatIsoDate(oneDayFromNow); private final LocalDateTime twoDaysFromNow = LocalDateTime.now().plusDays(2); private final String twoDaysFromNowString = DateUtil.formatDate(twoDaysFromNow); private final String twoDaysFromNowIsoString = DateUtil.formatIsoDate(twoDaysFromNow); private final LocalDateTime oneDayToNow = LocalDateTime.now().minusDays(1); private final String oneDayToNowString = DateUtil.formatDate(oneDayToNow); private final String oneDayToNowIsoString = DateUtil.formatIsoDate(oneDayToNow); String commandAdd1 = String.format("add task Buy KOI by \"%s 8pm\"", oneDayToNowString); Task task1 = new Task(); String commandAdd2 = String.format("add task Buy Milk by \"%s 9pm\"", oneDayFromNowString); Task task2 = new Task(); String commandAdd3 = String.format("add event Some Event from \"%s 4pm\" to \"%s 5pm\"", twoDaysFromNowString, twoDaysFromNowString); Event event3 = new Event(); public DestroyCommandTest() { task1.setName("Buy KOI"); task1.setDueDate(DateUtil.parseDateTime( String.format("%s 20:00:00", oneDayToNowIsoString))); task2.setName("Buy Milk"); task2.setDueDate(DateUtil.parseDateTime( String.format("%s 21:00:00", oneDayFromNowIsoString))); event3.setName("Some Event"); event3.setStartDate(DateUtil.parseDateTime( String.format("%s 16:00:00", twoDaysFromNowIsoString))); event3.setEndDate(DateUtil.parseDateTime( String.format("%s 17:00:00", twoDaysFromNowIsoString))); } @Before public void fixtures() { console.runCommand("clear"); console.runCommand(commandAdd1); console.runCommand(commandAdd2); console.runCommand(commandAdd3); } @Test public void destroy_task_hide() { assertTaskNotVisibleAfterCmd("destroy 1", task1); } @Test public void destroy_event_hide() { assertTaskNotVisibleAfterCmd("destroy 3", task1); } @Test public void destroy_wrongIndex_error() { console.runCommand("destroy 10"); String consoleMessage = Renderer.MESSAGE_DISAMBIGUATE + "\n\n" + DestroyController.MESSAGE_INDEX_OUT_OF_RANGE; assertEquals(consoleMessage, console.getConsoleTextArea()); } @Test public void destroy_invalidIndex_error() { console.runCommand("destroy alamak"); String consoleMessage = Renderer.MESSAGE_DISAMBIGUATE + "\n\n" + DestroyController.MESSAGE_INDEX_NOT_NUMBER; assertEquals(consoleMessage, console.getConsoleTextArea()); } }
package uk.org.okapibarcode.backend; import static java.lang.Integer.toHexString; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.imageio.ImageIO; import org.junit.Assert; import org.junit.ComparisonFailure; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.reflections.Reflections; import uk.org.okapibarcode.output.Java2DRenderer; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.oned.CodaBarReader; import com.google.zxing.oned.Code39Reader; import com.google.zxing.oned.Code93Reader; import com.google.zxing.oned.EAN13Reader; import com.google.zxing.oned.EAN8Reader; import com.google.zxing.oned.UPCAReader; import com.google.zxing.oned.UPCEReader; import com.google.zxing.pdf417.PDF417Reader; /** * <p> * Scans the test resources for file-based bar code tests. * * <p> * Tests that verify successful behavior will contain the following sets of files: * * <pre> * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].properties (bar code initialization attributes) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].codewords (expected intermediate coding of the bar code) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].png (expected final rendering of the bar code) * </pre> * * <p> * Tests that verify error conditions will contain the following sets of files: * * <pre> * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].properties (bar code initialization attributes) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].error (expected error message) * </pre> * * <p> * If a properties file is found with no matching expectation files, we assume that it was recently added to the test suite and * that we need to generate suitable expectation files for it. * * <p> * A single properties file can contain multiple test configurations (separated by an empty line), as long as the expected output * is the same for all of those tests. */ @RunWith(Parameterized.class) public class SymbolTest { /** The type of symbology being tested. */ private final Class< ? extends Symbol > symbolType; /** The test configuration properties. */ private final Map< String, String > properties; /** The file containing the expected intermediate coding of the bar code, if this test verifies successful behavior. */ private final File codewordsFile; /** The file containing the expected final rendering of the bar code, if this test verifies successful behavior. */ private final File pngFile; /** The file containing the expected error message, if this test verifies a failure. */ private final File errorFile; /** * Creates a new test. * * @param symbolType the type of symbol being tested * @param properties the test configuration properties * @param codewordsFile the file containing the expected intermediate coding of the bar code, if this test verifies successful behavior * @param pngFile the file containing the expected final rendering of the bar code, if this test verifies successful behavior * @param errorFile the file containing the expected error message, if this test verifies a failure * @param symbolName the name of the symbol type (used only for test naming) * @param fileBaseName the base name of the test file (used only for test naming) * @throws IOException if there is any I/O error */ public SymbolTest(Class< ? extends Symbol > symbolType, Map< String, String > properties, File codewordsFile, File pngFile, File errorFile, String symbolName, String fileBaseName) throws IOException { this.symbolType = symbolType; this.properties = properties; this.codewordsFile = codewordsFile; this.pngFile = pngFile; this.errorFile = errorFile; } /** * Runs the test. If there are no expectation files yet, we generate them instead of checking against them. * * @throws Exception if any error occurs during the test */ @Test public void test() throws Exception { Symbol symbol = symbolType.newInstance(); try { setProperties(symbol, properties); } catch (InvocationTargetException e) { symbol.error_msg = e.getCause().getMessage(); // TODO: migrate completely to exceptions? } if (codewordsFile.exists() && pngFile.exists()) { verifySuccess(symbol); } else if (errorFile.exists()) { verifyError(symbol); } else { generateExpectationFiles(symbol); } } /** * Verifies that the specified symbol was encoded and rendered in a way that matches expectations. * * @param symbol the symbol to check * @throws IOException if there is any I/O error * @throws ReaderException if ZXing has an issue decoding the barcode image */ private void verifySuccess(Symbol symbol) throws IOException, ReaderException { assertEquals("error message", "", symbol.error_msg); List< String > expectedList = Files.readAllLines(codewordsFile.toPath(), UTF_8); try { // try to verify codewords int[] actualCodewords = symbol.getCodewords(); assertEquals(expectedList.size(), actualCodewords.length); for (int i = 0; i < actualCodewords.length; i++) { int expected = getInt(expectedList.get(i)); int actual = actualCodewords[i]; assertEquals("at codeword index " + i, expected, actual); } } catch (UnsupportedOperationException e) { // codewords aren't supported, try to verify patterns String[] actualPatterns = symbol.pattern; assertEquals(expectedList.size(), actualPatterns.length); for (int i = 0; i < actualPatterns.length; i++) { String expected = expectedList.get(i); String actual = actualPatterns[i]; assertEquals("at pattern index " + i, expected, actual); } } // make sure the barcode images match BufferedImage expected = ImageIO.read(pngFile); BufferedImage actual = draw(symbol); assertEqual(expected, actual); // if possible, ensure an independent third party (ZXing) can read the generated barcode and agrees on what it represents Reader zxingReader = findReader(symbol); if (zxingReader != null) { LuminanceSource source = new BufferedImageLuminanceSource(expected); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Map< DecodeHintType, Boolean > hints = Collections.singletonMap(DecodeHintType.PURE_BARCODE, Boolean.TRUE); Result result = zxingReader.decode(bitmap, hints); String zxingData = removeChecksum(result.getText(), symbol); String okapiData = removeStartStopChars(symbol.getContent(), symbol); assertEquals(okapiData, zxingData); } } /** * Returns a ZXing reader that can read the specified symbol. * * @param symbol the symbol to be read * @return a ZXing reader that can read the specified symbol */ private static Reader findReader(Symbol symbol) { if (symbol instanceof Code93) { return new Code93Reader(); } else if (symbol instanceof Code3Of9) { return new Code39Reader(); } else if (symbol instanceof Codabar) { return new CodaBarReader(); } else if (symbol instanceof Ean) { Ean ean = (Ean) symbol; if (ean.getMode() == Ean.Mode.EAN8) { return new EAN8Reader(); } else { return new EAN13Reader(); } } else if (symbol instanceof Pdf417) { Pdf417 pdf417 = (Pdf417) symbol; if (pdf417.getMode() != Pdf417.Mode.MICRO) { return new PDF417Reader(); } } else if (symbol instanceof Upc) { Upc upc = (Upc) symbol; if (upc.getMode() == Upc.Mode.UPCA) { return new UPCAReader(); } else { return new UPCEReader(); } } // no corresponding ZXing reader exists, or it behaves badly so we don't use it for testing return null; } /** * Removes the checksum from the specified barcode content, according to the type of symbol that encoded the content. * * @param s the barcode content * @param symbol the symbol which encoded the content * @return the barcode content, without the checksum */ private static String removeChecksum(String s, Symbol symbol) { if (symbol instanceof Ean || symbol instanceof Upc) { return s.substring(0, s.length() - 1); } else { return s; } } /** * Removes the start/stop characters from the specified barcode content, according to the type of symbol that encoded the * content. * * @param s the barcode content * @param symbol the symbol which encoded the content * @return the barcode content, without the start/stop characters */ private static String removeStartStopChars(String s, Symbol symbol) { if (symbol instanceof Codabar) { return s.substring(1, s.length() - 1); } else { return s; } } /** * Verifies that the specified symbol encountered the expected error during encoding. * * @param symbol the symbol to check * @throws IOException if there is any I/O error */ private void verifyError(Symbol symbol) throws IOException { String expectedError = Files.readAllLines(errorFile.toPath(), UTF_8).get(0); assertEquals(expectedError, symbol.error_msg); } /** * Generates the expectation files for the specified symbol. * * @param symbol the symbol to generate expectation files for * @throws IOException if there is any I/O error */ private void generateExpectationFiles(Symbol symbol) throws IOException { if (symbol.error_msg != null && !symbol.error_msg.isEmpty()) { generateErrorExpectationFile(symbol); } else { generateCodewordsExpectationFile(symbol); generatePngExpectationFile(symbol); } } /** * Generates the error expectation file for the specified symbol. * * @param symbol the symbol to generate the error expectation file for * @throws IOException if there is any I/O error */ private void generateErrorExpectationFile(Symbol symbol) throws IOException { if (!errorFile.exists()) { PrintWriter writer = new PrintWriter(errorFile); writer.println(symbol.error_msg); writer.close(); } } /** * Generates the codewords expectation file for the specified symbol. * * @param symbol the symbol to generate codewords for * @throws IOException if there is any I/O error */ private void generateCodewordsExpectationFile(Symbol symbol) throws IOException { if (!codewordsFile.exists()) { PrintWriter writer = new PrintWriter(codewordsFile); try { int[] codewords = symbol.getCodewords(); for (int codeword : codewords) { writer.println(codeword); } } catch (UnsupportedOperationException e) { for (String pattern : symbol.pattern) { writer.println(pattern); } } writer.close(); } } /** * Generates the image expectation file for the specified symbol. * * @param symbol the symbol to draw * @throws IOException if there is any I/O error */ private void generatePngExpectationFile(Symbol symbol) throws IOException { if (!pngFile.exists()) { BufferedImage img = draw(symbol); ImageIO.write(img, "png", pngFile); } } /** * Returns the integer contained in the specified string. If the string contains a tab character, it and everything after it * is ignored. * * @param s the string to extract the integer from * @return the integer contained in the specified string */ private static int getInt(String s) { int i = s.indexOf('\t'); if (i != -1) { s = s.substring(0, i); } return Integer.parseInt(s); } /** * Draws the specified symbol and returns the resultant image. * * @param symbol the symbol to draw * @return the resultant image */ private static BufferedImage draw(Symbol symbol) { int magnification = 10; int width = symbol.getWidth() * magnification; int height = symbol.getHeight() * magnification; BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2d = img.createGraphics(); g2d.setPaint(Color.WHITE); g2d.fillRect(0, 0, width, height); Java2DRenderer renderer = new Java2DRenderer(g2d, magnification, 0, Color.WHITE, Color.BLACK); renderer.render(symbol); g2d.dispose(); return img; } /** * Initializes the specified symbol using the specified properties, where keys are attribute names and values are attribute * values. * * @param symbol the symbol to initialize * @param properties the attribute names and values to set * @throws ReflectiveOperationException if there is any reflection error */ private static void setProperties(Symbol symbol, Map< String, String > properties) throws ReflectiveOperationException { for (Map.Entry< String, String > entry : properties.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); String setterName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method setter = getMethod(symbol.getClass(), setterName); invoke(symbol, setter, value); } } /** * Returns the method with the specified name in the specified class, or throws an exception if the specified method cannot be * found. * * @param clazz the class to search in * @param name the name of the method to search for * @return the method with the specified name in the specified class */ private static Method getMethod(Class< ? > clazz, String name) { for (Method method : clazz.getMethods()) { if (method.getName().equals(name)) { return method; } } throw new RuntimeException("Unable to find method: " + name); } @SuppressWarnings("unchecked") private static < E extends Enum< E >> void invoke(Object object, Method setter, Object parameter) throws ReflectiveOperationException, IllegalArgumentException { Class< ? > paramType = setter.getParameters()[0].getType(); if (String.class.equals(paramType)) { setter.invoke(object, parameter.toString()); } else if (boolean.class.equals(paramType)) { setter.invoke(object, Boolean.valueOf(parameter.toString())); } else if (int.class.equals(paramType)) { setter.invoke(object, Integer.parseInt(parameter.toString())); } else if (double.class.equals(paramType)) { setter.invoke(object, Double.parseDouble(parameter.toString())); } else if (Character.class.equals(paramType)) { setter.invoke(object, parameter.toString().charAt(0)); } else if (paramType.isEnum()) { Class< E > e = (Class< E >) paramType; setter.invoke(object, Enum.valueOf(e, parameter.toString())); } else { throw new RuntimeException("Unknown setter type: " + paramType); } } /** * Returns all .properties files in the specified directory, or an empty array if none are found. * * @param dir the directory to search in * @return all .properties files in the specified directory, or an empty array if none are found */ private static File[] getPropertiesFiles(String dir) { File[] files = new File(dir).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".properties"); } }); if (files != null) { return files; } else { return new File[0]; } } /** * Verifies that the specified images match. * * @param expected the expected image to check against * @param actual the actual image */ private static void assertEqual(BufferedImage expected, BufferedImage actual) { int w = expected.getWidth(); int h = expected.getHeight(); Assert.assertEquals("width", w, actual.getWidth()); Assert.assertEquals("height", h, actual.getHeight()); int[] expectedPixels = new int[w * h]; expected.getRGB(0, 0, w, h, expectedPixels, 0, w); int[] actualPixels = new int[w * h]; actual.getRGB(0, 0, w, h, actualPixels, 0, w); for (int i = 0; i < expectedPixels.length; i++) { int expectedPixel = expectedPixels[i]; int actualPixel = actualPixels[i]; if (expectedPixel != actualPixel) { int x = i % w; int y = i / w; throw new ComparisonFailure("pixel at " + x + ", " + y, toHexString(expectedPixel), toHexString(actualPixel)); } } } /** * Extracts test configuration properties from the specified properties file. A single properties file can contain * configuration properties for multiple tests. * * @param propertiesFile the properties file to read * @return the test configuration properties in the specified file * @throws IOException if there is an error reading the properties file */ private static List< Map< String, String > > readProperties(File propertiesFile) throws IOException { byte[] bytes = Files.readAllBytes(propertiesFile.toPath()); String content = new String(bytes, UTF_8); String[] lines = content.split("\r\n"); // useful because sometimes we want to use \n or \r in data, but usually not both together List< Map< String, String > > allProperties = new ArrayList<>(); Map< String, String > properties = new LinkedHashMap<>(); for (String line : lines) { if (line.isEmpty()) { // an empty line signals the start of a new test configuration within this single file if (!properties.isEmpty()) { allProperties.add(properties); properties = new LinkedHashMap<>(); } } else if (!line.startsWith(" int index = line.indexOf('='); if (index != -1) { String name = line.substring(0, index); String value = line.substring(index + 1); properties.put(name, value); } } } if (!properties.isEmpty()) { allProperties.add(properties); } return allProperties; } /** * Finds all test resources and returns the information that JUnit needs to dynamically create the corresponding test cases. * * @return the test data needed to dynamically create the test cases * @throws IOException if there is an error reading a file */ @Parameters(name = "test {index}: {5}: {6}") public static List< Object[] > data() throws IOException { String filter = System.getProperty("okapi.symbol.test"); String backend = "uk.org.okapibarcode.backend"; Reflections reflections = new Reflections(backend); Set< Class< ? extends Symbol >> symbols = reflections.getSubTypesOf(Symbol.class); List< Object[] > data = new ArrayList<>(); for (Class< ? extends Symbol > symbol : symbols) { String symbolName = symbol.getSimpleName().toLowerCase(); if (filter == null || filter.equals(symbolName)) { String dir = "src/test/resources/" + backend.replace('.', '/') + "/" + symbolName; for (File file : getPropertiesFiles(dir)) { String fileBaseName = file.getName().replaceAll(".properties", ""); File codewordsFile = new File(file.getParentFile(), fileBaseName + ".codewords"); File pngFile = new File(file.getParentFile(), fileBaseName + ".png"); File errorFile = new File(file.getParentFile(), fileBaseName + ".error"); for (Map< String, String > properties : readProperties(file)) { data.add(new Object[] { symbol, properties, codewordsFile, pngFile, errorFile, symbolName, fileBaseName }); } } } } return data; } }
package database; import java.util.*; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.ejb.criteria.expression.function.TrimFunction; import model.ListItem; import model.Synonym; import util.CRTLogger; /** * Contains all access methods for the list loading (mesh, etc) * @author ingahege * */ public class DBList extends DBClinReason { /** * Select the ListItem with the given id from the database. * @param id * @return ListItem or null */ public ListItem selectListItemById(long id){ Session s = instance.getInternalSession(Thread.currentThread(), false); Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.eq("item_id", new Long(id))); ListItem li = (ListItem) criteria.uniqueResult(); s.close(); return li; } /** * Learner has chosen to add his/her own entry, so we add this entry marked as "PRIVATE" to the list. * @param entry * @param loc * @return */ public ListItem saveNewEntry(String entry, Locale loc){ if(entry==null || entry.trim().equals("")) return null; ListItem li = new ListItem(loc.getLanguage(), ListItem.TYPE_OWN, entry.trim()); saveAndCommit(li); return li; } /** * Select the ListItem with the given meshId from the database. * Just needed for importing German Mesh List. * @param id * @return ListItem or null */ public ListItem selectListItemByMeshId(String id){ Session s = instance.getInternalSession(Thread.currentThread(), false); Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.eq("mesh_id", id)); ListItem li = (ListItem) criteria.uniqueResult(); s.close(); return li; } /** * Loads ListItems for the given types. CAVE: This returns lots of items, only call during init of application * or for testing! * @param types * @return */ public List<ListItem> selectListItemsByTypesAndLang(Locale loc, String[] types){ Session s = instance.getInternalSession(Thread.currentThread(), false); Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.in("itemType", types)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.eq("language", loc)); //do NOT include items that have been added by learners: criteria.add(Restrictions.ne("itemType", ListItem.TYPE_OWN)); criteria.addOrder(Order.asc("name")); List l = criteria.list(); s.close(); return l; } public Synonym selectSynonymById(long id){ Session s = instance.getInternalSession(Thread.currentThread(), false); Criteria criteria = s.createCriteria(Synonym.class,"Synonym"); criteria.add(Restrictions.eq("id", new Long(id))); Synonym li = (Synonym) criteria.uniqueResult(); s.close(); return li; } /** * We select (based on the code of the MESH item all parent and child items. (e.g. for cough the first parent item would be * "respiratory disorders). * * @param li * @return list of ListItem objects or null */ public List<ListItem> selectParentAndChildListItems(ListItem li){ long startms = System.currentTimeMillis(); if(li==null) return null; String code = li.getFirstCode(); if(code==null || code.indexOf(".")<0) return null; CRTLogger.out("Start selectParentAndChildListItems " + startms + "ms", CRTLogger.LEVEL_PROD); List<ListItem> items = new ArrayList<ListItem>(); Session s = instance.getInternalSession(Thread.currentThread(), false); //select & add childs: List<ListItem> childs = selectChildListItemsByCode(code, s, li.getLanguage()); if(childs!=null && !childs.isEmpty()) items.addAll(childs); //select and add all parents: while(code.indexOf(".")>0){ code = code.substring(0, code.lastIndexOf(".")); if(code==null || code.trim().equals("")) break; ListItem l = selectListItemByCode(code, s, li.getLanguage()); if(l!=null) items.add(l); } s.close(); CRTLogger.out("End selectParentAndChildListItems " + (System.currentTimeMillis() - startms) + "ms", CRTLogger.LEVEL_PROD); return items; } /** * Select the ListItem with the given id from the database. * @param id * @return ListItem or null */ private ListItem selectListItemByCode(String code, Session s, Locale lang){ Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.eq("firstCode", code)); criteria.add(Restrictions.eq("language", lang)); ListItem li = (ListItem) criteria.uniqueResult(); return li; } private List<ListItem> selectChildListItemsByCode(String code, Session s, Locale lang){ Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.like("firstCode", code+".", MatchMode.START)); criteria.add(Restrictions.eq("language", lang)); return criteria.list(); } public List<ListItem> selectListItemBySearchTerm(String searchTerm, Locale lang){ Session s = instance.getInternalSession(Thread.currentThread(), false); Criteria criteria = s.createCriteria(ListItem.class,"ListItem"); criteria.add(Restrictions.eq("language", lang)); criteria.add(Restrictions.eq("ignored", false)); criteria.add(Restrictions.ilike("name", searchTerm, MatchMode.ANYWHERE)); return criteria.list(); } }
package test; import static org.junit.Assert.*; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import clue.BadConfigFormatException; import clue.Board; import clue.BoardCell; public class TestBoardAdjacencies { private static Board board; LinkedList<Integer> list; Set<BoardCell> targets; @Before public void setUp() { board = new Board(); try { board.loadConfigFiles("ClueBoard.csv", "legend.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (BadConfigFormatException e) { e.printStackTrace(); } board.calcAdjacencies(); list = null; targets = null; } // red @Test public void testAdjacenciesInsideRooms() { list = board.getAdjList(board.calcIndex(1, 1)); Assert.assertEquals(0, list.size()); list = board.getAdjList(board.calcIndex(4, 18)); Assert.assertEquals(0, list.size()); list = board.getAdjList(board.calcIndex(11, 6)); Assert.assertEquals(0, list.size()); list = board.getAdjList(board.calcIndex(22, 11)); Assert.assertEquals(0, list.size()); } // purple @Test public void testAdjacenciesRoomExits() { list = board.getAdjList(board.calcIndex(5, 12)); Assert.assertTrue(list.contains(board.calcIndex(6, 12))); Assert.assertEquals(1, list.size()); list = board.getAdjList(board.calcIndex(10, 18)); Assert.assertTrue(list.contains(board.calcIndex(10, 17))); Assert.assertEquals(1, list.size()); list = board.getAdjList(board.calcIndex(11, 7)); Assert.assertTrue(list.contains(board.calcIndex(11, 8))); Assert.assertEquals(1, list.size()); list = board.getAdjList(board.calcIndex(16, 16)); Assert.assertTrue(list.contains(board.calcIndex(15, 16))); Assert.assertEquals(1, list.size()); } // green @Test public void testAdjacenciesRoomEntrances() { list = board.getAdjList(board.calcIndex(6, 13)); assertTrue(list.contains(board.calcIndex(5, 13))); assertTrue(list.contains(board.calcIndex(6, 14))); assertTrue(list.contains(board.calcIndex(7, 13))); assertTrue(list.contains(board.calcIndex(6, 12))); assertEquals(4, list.size()); list = board.getAdjList(board.calcIndex(10, 17)); assertTrue(list.contains(board.calcIndex(9, 17))); assertTrue(list.contains(board.calcIndex(10, 18))); assertTrue(list.contains(board.calcIndex(11, 17))); assertTrue(list.contains(board.calcIndex(10, 16))); assertEquals(4, list.size()); list = board.getAdjList(board.calcIndex(15, 14)); assertTrue(list.contains(board.calcIndex(14, 14))); assertTrue(list.contains(board.calcIndex(15, 15))); assertTrue(list.contains(board.calcIndex(15, 13))); assertEquals(3, list.size()); list = board.getAdjList(board.calcIndex(14, 8)); assertTrue(list.contains(board.calcIndex(13, 8))); assertTrue(list.contains(board.calcIndex(14, 9))); assertTrue(list.contains(board.calcIndex(15, 8))); assertTrue(list.contains(board.calcIndex(14, 7))); assertEquals(4, list.size()); list = board.getAdjList(board.calcIndex(4, 15)); assertTrue(list.contains(board.calcIndex(3, 15))); assertTrue(list.contains(board.calcIndex(5, 15))); assertEquals(2, list.size()); } // light purple @Test public void testAdjacenciesWalkways() { list = board.getAdjList(board.calcIndex(0, 15)); assertTrue(list.contains(board.calcIndex(1, 15))); assertEquals(1, list.size()); list = board.getAdjList(board.calcIndex(5, 18)); assertTrue(list.contains(board.calcIndex(5, 19))); assertTrue(list.contains(board.calcIndex(6, 18))); assertTrue(list.contains(board.calcIndex(5, 17))); assertEquals(3, list.size()); list = board.getAdjList(board.calcIndex(7, 22)); assertTrue(list.contains(board.calcIndex(6, 22))); assertTrue(list.contains(board.calcIndex(7, 21))); assertEquals(2, list.size()); list = board.getAdjList(board.calcIndex(10, 16)); assertTrue(list.contains(board.calcIndex(9, 16))); assertTrue(list.contains(board.calcIndex(10, 17))); assertTrue(list.contains(board.calcIndex(11, 16))); assertTrue(list.contains(board.calcIndex(10, 15))); assertEquals(4, list.size()); list = board.getAdjList(board.calcIndex(16, 0)); assertTrue(list.contains(board.calcIndex(15, 0))); assertTrue(list.contains(board.calcIndex(16, 1))); assertEquals(2, list.size()); } // light blue @Test public void testTargetsOneStep() { board.calcTargets(4, 10, 1); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(3, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 10)))); assertEquals(2, targets.size()); board.calcTargets(14, 13, 1); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 13)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 12)))); assertEquals(3, targets.size()); } // light blue @Test public void testTargetsTwoSteps() { board.calcTargets(4, 10, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(2, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertEquals(3, targets.size()); board.calcTargets(14, 13, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 14)))); assertEquals(4, targets.size()); board.calcTargets(8, 9, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 8)))); assertEquals(6, targets.size()); board.calcTargets(15, 4, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 3)))); assertEquals(4, targets.size()); } // light blue @Test public void testTargetsThreeSteps() { board.calcTargets(4, 10, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(1, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertEquals(4, targets.size()); board.calcTargets(14, 13, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 16)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 15)))); assertEquals(7, targets.size()); board.calcTargets(8, 9, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(11, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 8)))); assertEquals(10, targets.size()); board.calcTargets(15, 4, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 1)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 3)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 5)))); assertEquals(8, targets.size()); } // light blue @Test public void testTargetsFourSteps() { board.calcTargets(4, 10, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(0, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 11)))); assertEquals(7, targets.size()); board.calcTargets(14, 13, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(12, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 16)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 17)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 13)))); // Door assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 16)))); assertEquals(12, targets.size()); board.calcTargets(8, 9, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(11, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 8)))); assertEquals(, targets.size()); board.calcTargets(15, 4, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 1)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 3)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 5)))); assertEquals(, targets.size()); } // light blue @Test public void testTargetsIntoRoom() { } // light green @Test public void testTargetsRoomExits() { list = board.getAdjList(board.calcIndex(5, 1)); assertTrue(list.contains(board.calcIndex(6, 1))); assertEquals(1, list.size()); list = board.getAdjList(board.calcIndex(0, 11)); assertTrue(list.contains(board.calcIndex(0, 10))); assertEquals(1, list.size()); } }
package som.vm; import java.io.IOException; import java.util.HashMap; import som.compiler.Disassembler; import som.vmobjects.Array; import som.vmobjects.BigInteger; import som.vmobjects.Block; import som.vmobjects.Class; import som.vmobjects.Double; import som.vmobjects.Integer; import som.vmobjects.Method; import som.vmobjects.Object; import som.vmobjects.String; import som.vmobjects.Symbol; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.TruffleRuntime; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; public class Universe { public static void main(java.lang.String[] arguments) { // Create Universe Universe u = new Universe(); try { // Start interpretation u.interpret(arguments); } catch (IllegalStateException e) { errorPrintln("ERROR: " + e.getMessage()); } // Exit with error code 0 u.exit(0); } public Object interpret(java.lang.String[] arguments) { // Check for command line switches arguments = handleArguments(arguments); // Initialize the known universe return execute(arguments); } static { /* static initializer */ pathSeparator = System.getProperty("path.separator"); fileSeparator = System.getProperty("file.separator"); } public Universe() { this.truffleRuntime = Truffle.getRuntime(); this.symbolTable = new SymbolTable(); this.avoidExit = false; this.lastExitCode = 0; } public Universe(boolean avoidExit) { this.truffleRuntime = Truffle.getRuntime(); this.symbolTable = new SymbolTable(); this.avoidExit = avoidExit; this.lastExitCode = 0; } public TruffleRuntime getTruffleRuntime() { return truffleRuntime; } public void exit(int errorCode) { // Exit from the Java system if (!avoidExit) { System.exit(errorCode); } else { lastExitCode = errorCode; } } public int lastExitCode() { return lastExitCode; } public void errorExit(java.lang.String message) { errorPrintln("Runtime Error: " + message); exit(1); } private java.lang.String[] handleArguments(java.lang.String[] arguments) { boolean gotClasspath = false; java.lang.String[] remainingArgs = new java.lang.String[arguments.length]; int cnt = 0; for (int i = 0; i < arguments.length; i++) { if (arguments[i].equals("-cp")) { if (i + 1 >= arguments.length) { printUsageAndExit(); } setupClassPath(arguments[i + 1]); ++i; // skip class path gotClasspath = true; } else if (arguments[i].equals("-d")) { printAST = true; } else { remainingArgs[cnt++] = arguments[i]; } } if (!gotClasspath) { // Get the default class path of the appropriate size classPath = setupDefaultClassPath(0); } // Copy the remaining elements from the original array into the new // array arguments = new java.lang.String[cnt]; System.arraycopy(remainingArgs, 0, arguments, 0, cnt); // check remaining args for class paths, and strip file extension for (int i = 0; i < arguments.length; i++) { java.lang.String[] split = getPathClassExt(arguments[i]); if (!("".equals(split[0]))) { // there was a path java.lang.String[] tmp = new java.lang.String[classPath.length + 1]; System.arraycopy(classPath, 0, tmp, 1, classPath.length); tmp[0] = split[0]; classPath = tmp; } arguments[i] = split[1]; } return arguments; } // take argument of the form "../foo/Test.som" and return // "../foo", "Test", "som" private java.lang.String[] getPathClassExt(java.lang.String arg) { // Create a new tokenizer to split up the string of dirs java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(arg, fileSeparator, true); java.lang.String cp = ""; while (tokenizer.countTokens() > 2) { cp = cp + tokenizer.nextToken(); } if (tokenizer.countTokens() == 2) { tokenizer.nextToken(); // throw out delimiter } java.lang.String file = tokenizer.nextToken(); tokenizer = new java.util.StringTokenizer(file, "."); if (tokenizer.countTokens() > 2) { println("Class with . in its name?"); exit(1); } java.lang.String[] result = new java.lang.String[3]; result[0] = cp; result[1] = tokenizer.nextToken(); result[2] = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : ""; return result; } public void setupClassPath(java.lang.String cp) { // Create a new tokenizer to split up the string of directories java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(cp, pathSeparator); // Get the default class path of the appropriate size classPath = setupDefaultClassPath(tokenizer.countTokens()); // Get the directories and put them into the class path array for (int i = 0; tokenizer.hasMoreTokens(); i++) { classPath[i] = tokenizer.nextToken(); } } private java.lang.String[] setupDefaultClassPath(int directories) { // Get the default system class path java.lang.String systemClassPath = System.getProperty("system.class.path"); // Compute the number of defaults int defaults = (systemClassPath != null) ? 2 : 1; // Allocate an array with room for the directories and the defaults java.lang.String[] result = new java.lang.String[directories + defaults]; // Insert the system class path into the defaults section if (systemClassPath != null) { result[directories] = systemClassPath; } // Insert the current directory into the defaults section result[directories + defaults - 1] = "."; // Return the class path return result; } private void printUsageAndExit() { // Print the usage println("Usage: som [-options] [args...] "); println(" "); println("where options include: "); println(" -cp <directories separated by " + pathSeparator + ">"); println(" set search path for application classes"); println(" -d enable disassembling"); // Exit System.exit(0); } /** * Start interpretation by sending the selector to the given class. * This is mostly meant for testing currently. * * @param className * @param selector * @return */ public Object interpret(java.lang.String className, java.lang.String selector) { initializeObjectSystem(); Class clazz = loadClass(symbolFor(className)); // Lookup the initialize invokable on the system class Method initialize = (Method) clazz.getSOMClass(). lookupInvokable(symbolFor(selector)); // Invoke the initialize invokable return initialize.invokeRoot(clazz, new Object[0]); } private Object execute(java.lang.String[] arguments) { Object systemObject = initializeObjectSystem(); // Start the shell if no filename is given if (arguments.length == 0) { Shell shell = new Shell(this); return shell.start(); } // Convert the arguments into an array Array argumentsArray = newArray(arguments); // Lookup the initialize invokable on the system class Method initialize = (Method) systemClass. lookupInvokable(symbolFor("initialize:")); // Invoke the initialize invokable return initialize.invokeRoot(systemObject, new Object[] {argumentsArray}); } protected Object initializeObjectSystem() { // Allocate the nil object nilObject = new Object(null); // Allocate the Metaclass classes metaclassClass = newMetaclassClass(); // Allocate the rest of the system classes objectClass = newSystemClass(); nilClass = newSystemClass(); classClass = newSystemClass(); arrayClass = newSystemClass(); symbolClass = newSystemClass(); methodClass = newSystemClass(); integerClass = newSystemClass(); bigintegerClass = newSystemClass(); primitiveClass = newSystemClass(); stringClass = newSystemClass(); doubleClass = newSystemClass(); // Setup the class reference for the nil object nilObject.setClass(nilClass); // Initialize the system classes. initializeSystemClass(objectClass, null, "Object"); initializeSystemClass(classClass, objectClass, "Class"); initializeSystemClass(metaclassClass, classClass, "Metaclass"); initializeSystemClass(nilClass, objectClass, "Nil"); initializeSystemClass(arrayClass, objectClass, "Array"); initializeSystemClass(methodClass, arrayClass, "Method"); initializeSystemClass(symbolClass, objectClass, "Symbol"); initializeSystemClass(integerClass, objectClass, "Integer"); initializeSystemClass(bigintegerClass, objectClass, "BigInteger"); initializeSystemClass(primitiveClass, objectClass, "Primitive"); initializeSystemClass(stringClass, objectClass, "String"); initializeSystemClass(doubleClass, objectClass, "Double"); // Load methods and fields into the system classes loadSystemClass(objectClass); loadSystemClass(classClass); loadSystemClass(metaclassClass); loadSystemClass(nilClass); loadSystemClass(arrayClass); loadSystemClass(methodClass); loadSystemClass(symbolClass); loadSystemClass(integerClass); loadSystemClass(bigintegerClass); loadSystemClass(primitiveClass); loadSystemClass(stringClass); loadSystemClass(doubleClass); // Load the generic block class blockClass = loadClass(symbolFor("Block")); // Setup the true and false objects trueObject = newInstance(loadClass(symbolFor("True"))); falseObject = newInstance(loadClass(symbolFor("False"))); // Load the system class and create an instance of it systemClass = loadClass(symbolFor("System")); Object systemObject = newInstance(systemClass); // Put special objects and classes into the dictionary of globals setGlobal(symbolFor("nil"), nilObject); setGlobal(symbolFor("true"), trueObject); setGlobal(symbolFor("false"), falseObject); setGlobal(symbolFor("system"), systemObject); setGlobal(symbolFor("System"), systemClass); setGlobal(symbolFor("Block"), blockClass); return systemObject; } public Symbol symbolFor(java.lang.String string) { // Lookup the symbol in the symbol table Symbol result = symbolTable.lookup(string); if (result != null) { return result; } // Create a new symbol and return it result = newSymbol(string); return result; } public Array newArray(int length) { // Allocate a new array and set its class to be the array class Array result = new Array(nilObject); result.setClass(arrayClass); // Set the number of indexable fields to the given value (length) result.setNumberOfIndexableFieldsAndClear(length, nilObject); // Return the freshly allocated array return result; } public Array newArray(java.util.List<?> list) { // Allocate a new array with the same length as the list Array result = newArray(list.size()); // Copy all elements from the list into the array for (int i = 0; i < list.size(); i++) { result.setIndexableField(i, (Object) list.get(i)); } // Return the allocated and initialized array return result; } public Array newArray(java.lang.String[] stringArray) { // Allocate a new array with the same length as the string array Array result = newArray(stringArray.length); // Copy all elements from the string array into the array for (int i = 0; i < stringArray.length; i++) { result.setIndexableField(i, newString(stringArray[i])); } // Return the allocated and initialized array return result; } public Block newBlock(Method method, MaterializedFrame context, int arguments) { // Allocate a new block and set its class to be the block class Block result = new Block(nilObject); result.setClass(getBlockClass(arguments)); // Set the method and context of block result.setMethod(method); result.setContext(context); // Return the freshly allocated block return result; } public Class newClass(Class classClass) { // Allocate a new class and set its class to be the given class class Class result = new Class(classClass.getNumberOfInstanceFields(), this); result.setClass(classClass); // Return the freshly allocated class return result; } public Method newMethod(Symbol signature, som.interpreter.Method truffleInvokable, FrameDescriptor frameDescriptor) { // Allocate a new method and set its class to be the method class Method result = new Method(nilObject, truffleInvokable, frameDescriptor); result.setClass(methodClass); result.setSignature(signature); result.setNumberOfIndexableFieldsAndClear(0, nilObject); // Return the freshly allocated method return result; } public Object newInstance(Class instanceClass) { // Allocate a new instance and set its class to be the given class Object result = new Object(instanceClass.getNumberOfInstanceFields(), nilObject); result.setClass(instanceClass); // Return the freshly allocated instance return result; } public Integer newInteger(int value) { // Allocate a new integer and set its class to be the integer class Integer result = new Integer(nilObject); result.setClass(integerClass); // Set the embedded integer of the newly allocated integer result.setEmbeddedInteger(value); // Return the freshly allocated integer return result; } public BigInteger newBigInteger(java.math.BigInteger value) { // Allocate a new integer and set its class to be the integer class BigInteger result = new BigInteger(nilObject); result.setClass(bigintegerClass); // Set the embedded integer of the newly allocated integer result.setEmbeddedBiginteger(value); // Return the freshly allocated integer return result; } public BigInteger newBigInteger(long value) { // Allocate a new integer and set its class to be the integer class BigInteger result = new BigInteger(nilObject); result.setClass(bigintegerClass); // Set the embedded integer of the newly allocated integer result.setEmbeddedBiginteger(java.math.BigInteger.valueOf(value)); // Return the freshly allocated integer return result; } public Double newDouble(double value) { // Allocate a new integer and set its class to be the double class Double result = new Double(nilObject); result.setClass(doubleClass); // Set the embedded double of the newly allocated double result.setEmbeddedDouble(value); // Return the freshly allocated double return result; } public Class newMetaclassClass() { // Allocate the metaclass classes Class result = new Class(this); result.setClass(new Class(this)); // Setup the metaclass hierarchy result.getSOMClass().setClass(result); // Return the freshly allocated metaclass class return result; } public String newString(java.lang.String embeddedString) { // Allocate a new string and set its class to be the string class String result = new String(nilObject); result.setClass(stringClass); // Put the embedded string into the new string result.setEmbeddedString(embeddedString); // Return the freshly allocated string return result; } public Symbol newSymbol(java.lang.String string) { // Allocate a new symbol and set its class to be the symbol class Symbol result = new Symbol(nilObject); result.setClass(symbolClass); // Put the string into the symbol result.setString(string); // Insert the new symbol into the symbol table symbolTable.insert(result); // Return the freshly allocated symbol return result; } public Class newSystemClass() { // Allocate the new system class Class systemClass = new Class(this); // Setup the metaclass hierarchy systemClass.setClass(new Class(this)); systemClass.getSOMClass().setClass(metaclassClass); // Return the freshly allocated system class return systemClass; } public void initializeSystemClass(Class systemClass, Class superClass, java.lang.String name) { // Initialize the superclass hierarchy if (superClass != null) { systemClass.setSuperClass(superClass); systemClass.getSOMClass().setSuperClass(superClass.getSOMClass()); } else { systemClass.getSOMClass().setSuperClass(classClass); } // Initialize the array of instance fields systemClass.setInstanceFields(newArray(0)); systemClass.getSOMClass().setInstanceFields(newArray(0)); // Initialize the array of instance invokables systemClass.setInstanceInvokables(newArray(0)); systemClass.getSOMClass().setInstanceInvokables(newArray(0)); // Initialize the name of the system class systemClass.setName(symbolFor(name)); systemClass.getSOMClass().setName(symbolFor(name + " class")); // Insert the system class into the dictionary of globals setGlobal(systemClass.getName(), systemClass); } public Object getGlobal(Symbol name) { // Return the global with the given name if it's in the dictionary of // globals if (hasGlobal(name)) { return (Object) globals.get(name); } // Global not found return null; } public void setGlobal(Symbol name, Object value) { // Insert the given value into the dictionary of globals globals.put(name, value); } public boolean hasGlobal(Symbol name) { // Returns if the universe has a value for the global of the given name return globals.containsKey(name); } public Class getBlockClass() { // Get the generic block class return blockClass; } public Class getBlockClass(int numberOfArguments) { // Compute the name of the block class with the given number of // arguments Symbol name = symbolFor("Block" + java.lang.Integer.toString(numberOfArguments)); // Lookup the specific block class in the dictionary of globals and // return it if (hasGlobal(name)) { return (Class) getGlobal(name); } // Get the block class for blocks with the given number of arguments Class result = loadClass(name, null); // Add the appropriate value primitive to the block class result.addInstancePrimitive(Block.getEvaluationPrimitive(numberOfArguments, this)); // Insert the block class into the dictionary of globals setGlobal(name, result); // Return the loaded block class return result; } public Class loadClass(Symbol name) { // Check if the requested class is already in the dictionary of globals if (hasGlobal(name)) { return (Class) getGlobal(name); } // Load the class Class result = loadClass(name, null); // Load primitives (if necessary) and return the resulting class if (result != null && result.hasPrimitives()) { result.loadPrimitives(); } return result; } public void loadSystemClass(Class systemClass) { // Load the system class Class result = loadClass(systemClass.getName(), systemClass); if (result == null) { throw new IllegalStateException(systemClass.getName().getString() + " class could not be loaded. " + "It is likely that the class path has not been initialized properly. " + "Please set system property 'system.class.path' or " + "pass the '-cp' command-line parameter."); } // Load primitives if necessary if (result.hasPrimitives()) { result.loadPrimitives(); } } public Class loadClass(Symbol name, Class systemClass) { // Try loading the class from all different paths for (java.lang.String cpEntry : classPath) { try { // Load the class from a file and return the loaded class Class result = som.compiler.SourcecodeCompiler.compileClass(cpEntry + fileSeparator, name.getString(), systemClass, this); if (printAST) { Disassembler.dump(result.getSOMClass()); Disassembler.dump(result); } return result; } catch (IOException e) { // Continue trying different paths } } // The class could not be found. return null; } public Class loadShellClass(java.lang.String stmt) throws IOException { // java.io.ByteArrayInputStream in = new // java.io.ByteArrayInputStream(stmt.getBytes()); // Load the class from a stream and return the loaded class Class result = som.compiler.SourcecodeCompiler.compileClass(stmt, null, this); if (printAST) { Disassembler.dump(result); } return result; } public static void errorPrint(java.lang.String msg) { // Checkstyle: stop System.err.print(msg); // Checkstyle: resume } public static void errorPrintln(java.lang.String msg) { // Checkstyle: stop System.err.println(msg); // Checkstyle: resume } public static void errorPrintln() { // Checkstyle: stop System.err.println(); // Checkstyle: resume } public static void print(java.lang.String msg) { // Checkstyle: stop System.err.print(msg); // Checkstyle: resume } public static void println(java.lang.String msg) { // Checkstyle: stop System.err.println(msg); // Checkstyle: resume } public static void println() { // Checkstyle: stop System.err.println(); // Checkstyle: resume } public Object nilObject; public Object trueObject; public Object falseObject; public Class objectClass; public Class classClass; public Class metaclassClass; public Class nilClass; public Class integerClass; public Class bigintegerClass; public Class arrayClass; public Class methodClass; public Class symbolClass; public Class primitiveClass; public Class stringClass; public Class systemClass; public Class blockClass; public Class doubleClass; private HashMap<Symbol, som.vmobjects.Object> globals = new HashMap<Symbol, som.vmobjects.Object>(); private java.lang.String[] classPath; private boolean printAST; public static final java.lang.String pathSeparator; public static final java.lang.String fileSeparator; private final TruffleRuntime truffleRuntime; private final SymbolTable symbolTable; // TODO: this is not how it is supposed to be... it is just a hack to cope // with the use of system.exit in SOM to enable testing private boolean avoidExit; private int lastExitCode; }
package translator; import java.io.*; import java.net.URL; import java.nio.charset.Charset; //import org.json.JSONArray; //import org.json.JSONObject; //import org.json.*; //import org.json.simple.*; //import org.json.simple.parser.JSONParser; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import org.json.simple.parser.*; import utils.Constants; //import java.util.*; //import org.json.simple.parser.*; class json { public String subString(org.json.JSONObject json_main, String str) throws JSONException { return (json_main.get(str)).toString(); } public String subString_2(JSONObject json_main, String str) throws JSONException { return (json_main.get(str)).toString(); } public JSONArray subArray(Object obj, String str) throws ParseException { JSONParser parser = new JSONParser(); obj = parser.parse(str); return (JSONArray) obj; } public String subStringFromsubArray(JSONArray arr) { String s = (arr.get(0)).toString(); return s; } public String posTagConvertor(String str) { if (str == null) { return "null"; } char c= str.charAt(0); try{ switch(c) { case 'V' : { str="verb"; break; } case 'N': { str="noun"; break; } case 'R': { str="adverb"; break; } case 'J': { str="adjective"; break; } case 'D': { str="determiner"; break; } case 'W': case 'P': { str="pronoun"; break; } case 'I': { str="preposition"; break; } case 'C': { str="conjunction"; break; } case 'U': { str="interjunction"; break; } default: { str="null"; break; } } } catch (Exception e) { if (Constants.DEBUG) { System.out.println("pos is null"); } return null; } return str; } }
import java.sql.*; public class tweetscrapeUser { //User -- from obj class User private int userID; //private int uniqueTwitterID; private String screenName; private String userDescription; //ts_twitteruser //twitter_id //twitter_username //uniqueTwitterID //twitter_bio public tweetscrapeUser() { } public tweetscrapeUser(int inc_userID, String inc_screenName) { } /** * setuserID * Description - used for setting the userID of object * @param inc_userID - the ID of the user obj inside local database */ public void setuserID(int inc_userID) { userID = inc_userID; } /** * setscreenName * Description - used for setting the screenName of object * @param inc_screenName - Incomming String of the twitter user's username */ public void setscreenName(String inc_screenName) { screenName = inc_screenName; } /** * setuserDescription * Description - used for setting the userDescription of object, userDescription will be the twitter bio of user's profile at first tweet * @param inc_userDescription - Incomming string of the twitter user's bio */ public void setuserDescription(String inc_userDescription) { userDescription = inc_userDescription; } /** * getuserID * Description - used for getting the userID of object * @return userID - the ID of the user obj inside local database */ public int getuserID() { return userID; } /** * getscreenName * Description - used for setting the screenName of object * @return screenName - String of the twitter user's username */ public String getscreenName() { return screenName; } /** * getuserDescription * Description - userDescription will be the twitter bio of user's profile at first tweet * @return userDescription - string of the twitter user's bio */ public String getuserDescription() { return userDescription; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.game; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import playn.core.util.Clock; import static playn.core.PlayN.graphics; import static playn.core.PlayN.pointer; import tripleplay.game.trans.FlipTransition; import tripleplay.game.trans.PageTurnTransition; import tripleplay.game.trans.SlideTransition; import tripleplay.util.Paintable; import static tripleplay.game.Log.log; /** * Manages a stack of screens. The stack supports useful manipulations: pushing a new screen onto * the stack, replacing the screen at the top of the stack with a new screen, popping a screen from * the stack. * * <p> Care is taken to preserve stack invariants even in the face of errors thrown by screens when * being added, removed, shown or hidden. Users can override {@link #handleError} and either simply * log the error, or rethrow it if they would prefer that a screen failure render their entire * screen stack unusable. </p> */ public class ScreenStack implements Paintable { /** Implements a particular screen transition. */ public interface Transition { /** Direction constants, used by transitions. */ enum Dir { UP, DOWN, LEFT, RIGHT; } /** Allows the transition to pre-compute useful values. This will immediately be followed * by call to {@link #update} with an elapsed time of zero. */ void init (Screen oscreen, Screen nscreen); /** Called every frame to update the transition * @param oscreen the outgoing screen. * @param nscreen the incoming screen. * @param elapsed the elapsed time since the transition started (in millis if that's what * your game is sending to {@link ScreenStack#update}). * @return false if the transition is not yet complete, true when it is complete. */ boolean update (Screen oscreen, Screen nscreen, float elapsed); /** Called when the transition is complete. This is where the transition should clean up * any temporary bits and restore the screens to their original state. The stack will * automatically destroy/hide the old screen after calling this method. Also note that this * method may be called <em>before</em> the transition signals completion, if a new * transition is started and this transition needs be aborted. */ void complete (Screen oscreen, Screen nscreen); } /** Used to operate on screens. See {@link #remove(Predicate)}. */ public interface Predicate { /** Returns true if the screen matches the predicate. */ boolean apply (Screen screen); } /** Simply puts the new screen in place and removes the old screen. */ public static final Transition NOOP = new Transition() { public void init (Screen oscreen, Screen nscreen) {} // noopski! public boolean update (Screen oscreen, Screen nscreen, float elapsed) { return true; } public void complete (Screen oscreen, Screen nscreen) {} // noopski! }; /** The x-coordinate at which screens are located. Defaults to 0. */ public float originX = 0; /** The y-coordinate at which screens are located. Defaults to 0. */ public float originY = 0; /** Creates a slide transition. */ public SlideTransition slide () { return new SlideTransition(this); } /** Creates a page turn transition. */ public PageTurnTransition pageTurn () { return new PageTurnTransition(); } /** Creates a flip transition. */ public FlipTransition flip () { return new FlipTransition(); } /** * {@link #push(Screen,Transition)} with the default transition. */ public void push (Screen screen) { push(screen, defaultPushTransition()); } public void push (Screen screen, Transition trans) { if (_screens.isEmpty()) { addAndShow(screen); } else { final Screen otop = top(); transition(new Transitor(otop, screen, trans) { @Override protected void onComplete() { hide(otop); } }); } } /** * {@link #push(Iterable,Transition)} with the default transition. */ public void push (Iterable<? extends Screen> screens) { push(screens, defaultPushTransition()); } /** * Pushes the supplied set of screens onto the stack, in order. The last screen to be pushed * will also be shown, using the supplied transition. Note that the transition will be from the * screen that was on top prior to this call. */ public void push (Iterable<? extends Screen> screens, Transition trans) { if (!screens.iterator().hasNext()) { throw new IllegalArgumentException("Cannot push empty list of screens."); } if (_screens.isEmpty()) { for (Screen screen : screens) add(screen); justShow(top()); } else { final Screen otop = top(); Screen last = null; for (Screen screen : screens) { if (last != null) add(last); last = screen; } transition(new Transitor(otop, last, trans) { @Override protected void onComplete() { hide(otop); } }); } } /** * {@link #popTo(Screen,Transition)} with the default transition. */ public void popTo (Screen newTopScreen) { popTo(newTopScreen, defaultPopTransition()); } /** * Pops the top screen from the stack until the specified screen has become the * topmost/visible screen. If newTopScreen is null or is not on the stack, this will remove * all screens. */ public void popTo (Screen newTopScreen, Transition trans) { // if the desired top screen is already the top screen, then NOOP if (top() == newTopScreen) return; // remove all intervening screens while (_screens.size() > 1 && _screens.get(1) != newTopScreen) { justRemove(_screens.get(1)); } // now just pop the top screen remove(top(), trans); } /** * {@link #replace(Screen,Transition)} with the default transition. */ public void replace (Screen screen) { replace(screen, defaultPushTransition()); } public void replace (Screen screen, Transition trans) { if (_screens.isEmpty()) { addAndShow(screen); } else { final Screen otop = _screens.remove(0); // log.info("Removed " + otop + ", new top " + top()); transition(new Transitor(otop, screen, trans) { @Override protected void onComplete () { hide(otop); wasRemoved(otop); } }); } } /** * {@link #remove(Screen,Transition)} with the default transition. */ public boolean remove (Screen screen) { return remove(screen, defaultPopTransition()); } /** * Removes the specified screen from the stack. If it is the currently visible screen, it will * first be hidden, and the next screen below in the stack will be made visible. * * @return true if the screen was found in the stack and removed, false if the screen was not * in the stack. */ public boolean remove (Screen screen, Transition trans) { if (top() != screen) return justRemove(screen); if (_screens.size() > 1) { final Screen otop = _screens.remove(0); // log.info("Removed " + otop + ", new top " + top()); transition(new Untransitor(otop, top(), trans) { @Override protected void onComplete () { hide(otop); wasRemoved(otop); } }); } else { hide(screen); justRemove(screen); } return true; } /** * {@link #remove(Predicate,Transition)} with the default transition. */ public void remove (Predicate pred) { remove(pred, defaultPopTransition()); } /** * Removes all screens that match the supplied predicate, from lowest in the stack to highest. * If the top screen is removed (as the last action), the supplied transition will be used. */ public void remove (Predicate pred, Transition trans) { // first, remove any non-top screens that match the predicate if (_screens.size() > 1) { Iterator<Screen> iter = _screens.iterator(); iter.next(); // skip top while (iter.hasNext()) { Screen screen = iter.next(); if (pred.apply(screen)) { iter.remove(); wasRemoved(screen); // log.info("Pred removed " + screen + ", new top " + top()); } } } // last, remove the top screen if it matches the predicate if (_screens.size() > 0 && pred.apply(top())) remove(top(), trans); } /** * Returns the top screen on the stack, or null if the stack contains no screens. */ public Screen top () { return _screens.isEmpty() ? null : _screens.get(0); } /** * Searches from the top-most screen to the bottom-most screen for a screen that matches the * predicate, returning the first matching screen. {@code null} is returned if no matching * screen is found. */ public Screen find (Predicate pred) { for (Screen screen : _screens) if (pred.apply(screen)) return screen; return null; } /** * Returns true if we're currently transitioning between screens. */ public boolean isTransiting () { return _transitor != null; } /** * Returns the number of screens on the stack. */ public int size () { return _screens.size(); } /** * Called from your game's {@code update} method. Calls {@link Screen#update} on top screen. */ public void update (int delta) { if (_transitor != null) _transitor.update(delta); else if (!_screens.isEmpty()) top().update(delta); } /** * Called from your game's {@code paint} method. Calls {@link Screen#paint} on top screen. */ public void paint (Clock clock) { if (_transitor != null) _transitor.paint(clock); else if (!_screens.isEmpty()) top().paint(clock); } protected Transition defaultPushTransition () { return NOOP; } protected Transition defaultPopTransition () { return NOOP; } protected void add (Screen screen) { if (_screens.contains(screen)) { throw new IllegalArgumentException("Cannot add screen to stack twice."); } _screens.add(0, screen); // log.info("Added " + screen + ", new top " + top()); try { screen.wasAdded(); } catch (RuntimeException e) { handleError(e); } } protected void addAndShow (Screen screen) { add(screen); justShow(screen); } protected void justShow (Screen screen) { graphics().rootLayer().addAt(screen.layer, originX, originY); try { screen.wasShown(); } catch (RuntimeException e) { handleError(e); } } protected void hide (Screen screen) { graphics().rootLayer().remove(screen.layer); try { screen.wasHidden(); } catch (RuntimeException e) { handleError(e); } } protected boolean justRemove (Screen screen) { boolean removed = _screens.remove(screen); if (removed) wasRemoved(screen); // log.info("Just removed " + screen + ", new top " + top()); return removed; } protected void wasRemoved (Screen screen) { try { screen.wasRemoved(); } catch (RuntimeException e) { handleError(e); } } protected void transition (Transitor transitor) { if (_transitor != null) _transitor.complete(); _transitor = transitor; _transitor.init(); } /** * A hacky mechanism to allow a game to force a transition to skip some number of frames at its * start. If a game's screens tend to do a lot of image loading in wasAdded or immediately * after, that will cause an unpleasant jerk at the start of the transition as the first frame * or two have order of magnitude larger frame deltas than subsequent frames. Having those * render as t=0 and then starting the timer after the skipped frames are done delays the * transition by a bit, but ensures that when things are actually animating, that they are nice * and smooth. */ protected int transSkipFrames () { return 0; } protected class Transitor { public Transitor (Screen oscreen, Screen nscreen, Transition trans) { _oscreen = oscreen; _nscreen = nscreen; _trans = trans; } public void init () { _oscreen.hideTransitionStarted(); showNewScreen(); _trans.init(_oscreen, _nscreen); // disable pointer interactions while we transition; disallowing interaction pointer().setEnabled(false); // Force a complete if the Transition is a noop, so that we don't have to wait until // the next update. We should consider checking some property of the Transition object // rather than checking against noop, in the odd case that we have a custom 0-duration // transition. if (_trans == NOOP) { complete(); } } public void update (int delta) { _oscreen.update(delta); _nscreen.update(delta); if (_complete) complete(); } public void paint (Clock clock) { _oscreen.paint(clock); _nscreen.paint(clock); if (_skipFrames > 0) _skipFrames -= 1; else _elapsed += clock.dt(); _complete = _trans.update(_oscreen, _nscreen, _elapsed); } public void complete () { _transitor = null; // let the transition know that it's complete _trans.complete(_oscreen, _nscreen); // make sure the new screen is in the right position _nscreen.layer.setTranslation(originX, originY); _nscreen.showTransitionCompleted(); // reenable pointer interactions pointer().setEnabled(true); onComplete(); } protected void showNewScreen () { addAndShow(_nscreen); } protected void onComplete () {} protected final Screen _oscreen, _nscreen; protected final Transition _trans; protected int _skipFrames = transSkipFrames(); protected float _elapsed; protected boolean _complete; } protected class Untransitor extends Transitor { public Untransitor (Screen oscreen, Screen nscreen, Transition trans) { super(oscreen, nscreen, trans); } @Override protected void showNewScreen () { justShow(_nscreen); } } /** Called if any exceptions are thrown by the screen calldown functions. */ protected void handleError (RuntimeException error) { log.warning("Screen choked", error); } /** The currently executing transition, or null. */ protected Transitor _transitor; /** Containts the stacked screens from top-most, to bottom-most. */ protected final List<Screen> _screens = new ArrayList<Screen>(); }
package GameOfLife; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; public class Cell extends JPanel implements MouseListener { private boolean alive; private int x; private int y; private Color aliveColour = Color.WHITE; private Color deadColour = Color.BLACK; Cell(int x, int y){ this.addMouseListener(this); this.x = x; this.y = y; } public Color getAliveColour() { return aliveColour; } public void setAliveColour(Color aliveColour) { this.aliveColour = aliveColour; } public Color getDeadColour() { return deadColour; } public void setDeadColour(Color deadColour) { this.deadColour = deadColour; } public boolean isAlive() { return alive; } public void setAlive(boolean alive) { this.alive = alive; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(alive){ g.setColor(aliveColour); }else{ g.setColor(deadColour); } g.fillRect(0, 0, 20, 20); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { if (e.isMetaDown()) Life.flipSquareState(this.x, this.y); } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { Life.flipSquareState(this.x, this.y); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }
package water.hdfs; import java.io.File; import water.H2O; import water.Log; import H2OInit.Boot; public class Hdfs { private static final String DEFAULT_HDFS_VERSION = "cdh4"; private static final String MAPRFS_HDFS_VERSION = "0.20.2"; public static boolean initialize() { assert (H2O.OPT_ARGS.hdfs != null); if (H2O.OPT_ARGS.hdfs.equals("resurrect")) { throw new Error("HDFS resurrection is unimplemented"); } else { // Load the HDFS backend for existing hadoop installations. // understands -hdfs=hdfs://server:port OR -hdfs=maprfs:///mapr/node_name/volume // -hdfs-root=root // -hdfs-config=config file String version = H2O.OPT_ARGS.hdfs_version==null ? DEFAULT_HDFS_VERSION : H2O.OPT_ARGS.hdfs_version; // If HDFS URI is MapR-fs - Switch two MapR version of hadoop version = version.equals("mapr") || (H2O.OPT_ARGS.hdfs.startsWith("maprfs://")) ? MAPRFS_HDFS_VERSION : version; try { if( Boot._init.fromJar() ) { File f = new File(version); if( f.exists() ) { Boot._init.addExternalJars(f); } else { Boot._init.addInternalJars("hadoop/"+version+"/"); } } } catch(Exception e) { e.printStackTrace(); Log.die("[hdfs] Unable to initialize hadoop version " + version + " please use different version."); return false; } PersistHdfs.ROOT.toString(); // Touch & thus start HDFS return true; } } }
package web.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import web.Conexion; import web.exception.ErrorBandException; import web.vo.BandVO; /** * Clase que implementa un patrn de acceso a BBDD de tipo Table Data Gateway, * en este caso, para la tabla de la BBDD que almacena los datos de un usuario * de tipo banda. Tambin implementan un Singleton, permitiendose una sola instancia * de esta clase en ejecucin. */ public class BandDAO{ private static BandDAO bandDAO; private Conexion c; public BandDAO(){ c = Conexion.getConexion(); bandDAO = this; } public static BandDAO getDAO(){ if(bandDAO==null){ return new BandDAO(); }else{ return bandDAO; } } /** * Funcin que se encarga de insertar los datos de una banda en la BBDD, incluidos los * datos que se almacenan en la tabla banda y los de la tabla pertenece que indica los generos * musicales que interpreta este usuario banda. * Si no puede insertarlos lanza una excepcin. * * @param b Objeto de tipo BandVO que contiene la informacin de un usuario * de tipo banda que se ha de almacenar en la BBDD. */ public void addBand(BandVO b){ try { Statement s = c.getConnection().createStatement(); s.execute( "INSERT INTO `banda` (`nombre`,`password`,`fotoperfil`,`email`,`descripcion`)" + " VALUES ('" + b.getNombre() + "','" + b.getPassword() + "','" + b.getFotoPerfil() + "','" + b.getEmail() + "','" + b.getDescripcion() + "');"); ArrayList<String> generos = b.getGeneros(); for (String genero : generos) { s.execute("INSERT INTO `pertenecer` (`banda_email`,`genero_nombre`)" + " VALUES ('" + b.getEmail() + "','" + genero + "');"); } } catch (SQLException ex) { System.out.println("Error al insertar BANDA"); } } /** * Funcin que se encarga de comprobar si el email de la banda introducido * por parametros se encuentra almacenado en la BBDD. * * @param email Cadena de caracteres que identifica al usuario de tipo * banda a comprobar. * @return Variable booleana con valor true si la banda indicada se encuentra * en la BBDD y false si no est almacenada en esta. */ public boolean existeBanda(String email){ try { Statement s = c.getConnection().createStatement(); ResultSet rs = s.executeQuery("SELECT email FROM banda WHERE email='" + email + "'"); while (rs.next()) { if (rs.getString("email") != null) { rs.close(); return true; } } rs.close(); return false; } catch (SQLException ex) { System.out.println("Error al comprobar banda"); return false; } } /** * Funcin que se encarga de realizar la query a la base de datos que * permite obtener todos los generos msicales almacenados en esta. * * @return Lista con los generos musicales almacenado en la tabla de la * base de datos "genero". */ public ArrayList<String> totalGeneros () { try { Statement s = c.getConnection().createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM genero"); ArrayList<String> generos = new ArrayList<String>(); while (rs.next()) { generos.add(rs.getString("nombre")); } rs.close(); return generos; } catch (SQLException ex) { System.out.println("Error al comprobar los generos"); return null; } } /** * Funcin que se encarga de realizar la query a la base de datos que * permite obtener todos los generos msicales que pertenecen a la banda indicada * como parmetro. * * @param email Cadena de caracteres que identifica al usuario de tipo * banda a comprobar. * @return Lista con los generos musicales almacenados en la tabla pertenecer con * relacin a la banda introducida por parmetros. */ public ArrayList<String> getGeneros (String email) { try { Statement s = c.getConnection().createStatement(); ResultSet rs = s.executeQuery("SELECT genero_nombre FROM banda, pertenecer WHERE email='"+email+"' AND email=banda_email"); ArrayList<String> generos = new ArrayList<String>(); while (rs.next()) { generos.add(rs.getString("genero_nombre")); } rs.close(); return generos; } catch (SQLException ex) { System.out.println("Error al comprobar los generos"); return null; } } /** * Funcin que se encarga de buscar en la base de datos los datos del usuario de * tipo banda que se identifican a partir del email introducido como parmetro * en la funcin. * * @param email Cadena de caracteres que identifica al usuario de tipo * banda a buscar. * @return Objeto de tipo FanVO con toda la informacin almacenada sobre * un usuario de tipo banda en la tabla de la base de datos "banda" que se * identifica a partir del email introducido como parmetro. */ public BandVO buscarBanda(String email) throws ErrorBandException{ try { Statement s = c.getConnection().createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM banda WHERE email='" + email + "'"); BandVO res; if (rs.next()) { res = new BandVO(rs.getString(1),rs.getString(2),rs.getString(3),email, getGeneros(email), rs.getString(5)); }else{ res=null; } rs.close(); return res; } catch (SQLException ex) { System.out.println("Error SQL al comprobar banda"); return null; } } public void updateInfo(String email, String info) throws ErrorBandException{ try { Statement s = c.getConnection().createStatement(); System.out.println("Email banda: "+email); System.out.println("Info banda: "+info); s.execute("UPDATE banda SET descripcion='"+info+"' WHERE email='" + email + "'"); } catch (SQLException ex) { System.out.println("Error SQL al actualizar info banda"); throw new ErrorBandException(); } } /** * Funcin que se encarga de hacer una bsqueda en la BBDD sobre las * bandas que cumplen con la keyWord introducida como parmetro. * * @param keyWord Cadena de caracteres que representa el nombre de la banda introducido en la bsqueda * @param generos Cadena de caracteres que representa el nombre de la banda introducido en la bsqueda * @return Lista de objetos de tipo Banda con las bandas obtenidas como respuesta a la query */ public List<BandVO> search(String keyWord, ArrayList<String> generos){ try { Statement s = c.getConnection().createStatement(); ResultSet rs; String query; if (keyWord == null && (generos == null || generos.size()==0)) rs = s.executeQuery("SELECT * FROM banda"); else if (keyWord != null && (generos == null || generos.size()==0)) rs = s.executeQuery("SELECT * FROM banda WHERE UPPER(nombre) LIKE UPPER('%"+keyWord+"%')"); else if (keyWord == null && generos.size()>0){ query = "SELECT DISTINCT banda.* FROM banda, pertenecer WHERE email=banda_email AND ("; for(int i=0; i<generos.size();i++){ if(i!=generos.size()-1) query+=" UPPER(genero_nombre) LIKE UPPER('%"+generos.get(i)+"%') OR"; else query+=" UPPER(genero_nombre) LIKE UPPER('%"+generos.get(i)+"%'))"; } System.out.println(query); rs = s.executeQuery(query); } else{ //Se han introducido keyword y generos por los que filtrar query = "SELECT DISTINCT banda.* FROM banda, pertenecer WHERE email=banda_email AND UPPER(nombre) LIKE UPPER('%"+keyWord+"%') AND ("; for(int i=0; i<generos.size();i++){ if(i!=generos.size()-1) query+=" UPPER(genero_nombre) LIKE UPPER('%"+generos.get(i)+"%') OR"; else query+=" UPPER(genero_nombre) LIKE UPPER('%"+generos.get(i)+"%'))"; } System.out.println(query); rs = s.executeQuery(query); } List<BandVO> bands=new ArrayList<BandVO>(); while(rs.next()){ bands.add(new BandVO(rs.getString(1),rs.getString(2),rs.getString(3) ,rs.getString(4),getGeneros(rs.getString(4)),rs.getString(5))); } rs.close(); return bands; } catch (SQLException ex) { System.out.println("Error al buscar bandas"); return null; } } /** * Funcin que se encarga de hacer actualizar en la tabla de la BBDD que almacena * las banda la informacin introducida en el parmetro "band" y de actualizar en * la tabla "pertenecer" que gneros musicales se relacionan con la banda. * * @param band Objeto de tipo VO que almacena la nueva informacin de la banda */ public void updateBand(BandVO band) { try { Statement s = c.getConnection().createStatement(); s.execute( "UPDATE banda SET nombre='" + band.getNombre() + "', fotoperfil='" + band.getFotoPerfil() + "', password='" + band.getPassword() + "' " + "WHERE email='" + band.getEmail() + "';"); ArrayList<String> generos = band.getGeneros(); if (generos != null) { s.execute( "DELETE FROM pertenecer WHERE banda_email='" + band.getEmail() + "';"); for (String genero : generos) { s.execute("INSERT INTO pertenecer (banda_email,genero_nombre)" + " VALUES ('" + band.getEmail() + "','" + genero + "');"); } } } catch (SQLException ex) { System.out.println("Error al insertar BANDA" + ex.getMessage()); } } }
package jump; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; import javax.swing.Timer; public class Game implements ActionListener, KeyListener{ public static Game jumper; public final int WIDTH = 800, HEIGHT = 800; public Render renderObject; public Rectangle hero; public ArrayList<Rectangle> columns; public int ticks, jump, score; public boolean gameOver, started; public Random rand; public Game(){ JFrame jframe = new JFrame(); Timer timer = new Timer(20, this); renderObject = new Render(); rand = new Random(); hero = new Rectangle(WIDTH - 750, HEIGHT - 140, 20, 20); columns = new ArrayList<Rectangle>(); jframe.add(renderObject); jframe.setTitle(" JUMPER "); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setSize(WIDTH, HEIGHT); jframe.setLocationRelativeTo(null); jframe.addKeyListener(this); jframe.setResizable(false); jframe.setVisible(true); addColumn(true); addColumn(true); addColumn(true); addColumn(true); timer.start(); } public void addColumn(boolean start){ int space = 800; int width = 20 + rand.nextInt(150); int height = 50 + rand.nextInt(100); if (start){ columns.add(new Rectangle(WIDTH + width + columns.size() * 300, HEIGHT - height - 120, width, height)); columns.add(new Rectangle(WIDTH + width + (columns.size() - 1) * 300, 0, width, HEIGHT - height - space)); } else { columns.add(new Rectangle(columns.get(columns.size() - 1).x + 600, HEIGHT - height - 120, width, height)); columns.add(new Rectangle(columns.get(columns.size() - 1).x, 0, width, HEIGHT - height - space)); } } public void paintColumn(Graphics g, Rectangle column){ g.setColor(Color.red); g.fillRect(column.x, column.y, column.width, column.height); } public void jump(){ if (gameOver){ hero = new Rectangle(WIDTH - 750, HEIGHT - 140, 20, 20); columns.clear(); jump = 0; score = 0; addColumn(true); addColumn(true); addColumn(true); addColumn(true); gameOver = false; } if (!started){ started = true; } else if (!gameOver && hero.y == HEIGHT - 140) { if (jump > 0){ jump = 0; } jump -= 35; } } public void actionPerformed(ActionEvent e){ int speed = 12; ticks++; if (started){ for (int i = 0; i < columns.size(); i++){ Rectangle column = columns.get(i); column.x -= speed; } if (ticks % 2 == 0 && jump < 15){ jump += 5; } for (int i = 0; i < columns.size(); i++){ Rectangle column = columns.get(i); if (column.x + column.width < 0){ columns.remove(column); if (column.y == 0){ addColumn(false); } } } hero.y += jump; for (Rectangle column : columns){ if (column.y == 0 && hero.x + hero.width / 2 > column.x + column.width / 2 - 3 && hero.x + hero.width / 2 < column.x + column.width / 2 + 10){ score++; } if (column.intersects(hero)){ gameOver = true; if (hero.y <= column.x){ hero.y = column.x - hero.width; } else { if (column.y != 0){ hero.y = column.y - hero.height; } else if (hero.y < column.height){ hero.y = column.height; } } } } if (hero.y + jump >= HEIGHT - 120){ hero.y = HEIGHT - 120 - hero.height; } } renderObject.repaint(); } public void repaint(Graphics g){ g.setColor(Color.black); g.fillRect(0, 0, WIDTH, HEIGHT); g.setColor(Color.gray); g.fillRect(0, HEIGHT - 120, WIDTH, 120); g.setColor(Color.yellow); g.fillRect(0, HEIGHT - 120, WIDTH, 20); g.setColor(Color.blue); g.fillRect(0, HEIGHT - 800, WIDTH, 65); g.setColor(Color.green); g.fillRect(hero.x, hero.y, hero.width, hero.height); for (Rectangle column : columns){ paintColumn(g, column); } g.setColor(Color.white); g.setFont(new Font("Arial", 1, 40)); if (!started){ g.drawString("Press Space Bar to Jump Over Obstacles!", 0, HEIGHT / 2 - 50); } if (gameOver){ g.drawString("Game Over!", 300, HEIGHT / 2 - 50); } if (!gameOver && started){ g.drawString(String.valueOf(score), WIDTH / 2 - 25, 100); } } public static void main(String[] args){ jumper = new Game(); } public void keyReleased(KeyEvent e){ if (e.getKeyCode() == KeyEvent.VK_SPACE){ jump(); } } public void keyTyped(KeyEvent e){ } public void keyPressed(KeyEvent e){ } }
package com.echo.primestudio.dota2knowthyheroes; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.text.Layout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import java.util.Arrays; public class Main extends ActionBarActivity { private ViewPager pager; public static SlidingTabLayout tabLayout; public static ScrollView heroPreview; public static View skillTemplate; public static String prevHero; public static String[] skillDesc, skillSpec, skillNames; public static int[] skillIcons; public static TextView heroLore; public static ImageView heroImage; // public static ListView skillLV; public static Context applicationContext; public static LinearLayout heroIntro; public static Resources appResource; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); //Declaration heroPreview = (ScrollView) findViewById(R.id.hero_preview); heroLore = (TextView) findViewById(R.id.hero_lore); heroImage = (ImageView) findViewById(R.id.hero_image); heroIntro = (LinearLayout) findViewById(R.id.hero_introduction); if (skillTemplate == null) { Log.d("SKILLTEMPLATE", " FROM MAIN IS NULL"); } pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(new pagerAdapter(getSupportFragmentManager())); tabLayout = (SlidingTabLayout) findViewById(R.id.tabs); tabLayout.setViewPager(pager); //Setting Context Context appContext = getApplicationContext(); applicationContext = appContext; //Setting resources Resources res = getResources(); appResource = res; } @Override public void onBackPressed() { if (isPanelShown()) { slideIn(); } else super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement return super.onOptionsItemSelected(item); } public static void tabsSlideIn() { Log.d("TABS","IN SLIDE IN"); if (isTypeShown()) { // Hide the panel Animation topOut = AnimationUtils.loadAnimation(applicationContext, R.anim.top_out); tabLayout.startAnimation(topOut); tabLayout.setVisibility(View.GONE); } else { // Show the Panel // Animation rightOut = AnimationUtils.loadAnimation(applicationContext, // R.anim.right_out); // tabLayout.startAnimation(rightOut); tabLayout.setVisibility(View.VISIBLE); } } private static boolean isTypeShown() { return tabLayout.getVisibility() == View.VISIBLE; } public static void slideIn() { if (!isPanelShown()) { // Show the panel Animation rightIn = AnimationUtils.loadAnimation(applicationContext, R.anim.right_in); heroPreview.startAnimation(rightIn); tabsSlideIn(); heroPreview.setVisibility(View.VISIBLE); } else { // Hide the Panel Animation rightOut = AnimationUtils.loadAnimation(applicationContext, R.anim.right_out); heroPreview.startAnimation(rightOut); tabLayout.setVisibility(View.VISIBLE); heroPreview.setVisibility(View.GONE); } } private static boolean isPanelShown() { return heroPreview.getVisibility() == View.VISIBLE; } //Pager Adapter class pagerAdapter extends FragmentPagerAdapter { String[] tabs; public pagerAdapter(FragmentManager fm) { super(fm); tabs = getResources().getStringArray(R.array.type); } @Override public CharSequence getPageTitle(int position) { return tabs[position]; } @Override public Fragment getItem(int position) { typeFragement fragement = typeFragement.getInstance(position); return fragement; } @Override public int getCount() { return 3; } } public static class typeFragement extends Fragment { public static ListView heroesLV; public static typeFragement getInstance(int position) { typeFragement fragment = new typeFragement(); Bundle args = new Bundle(); args.putInt("type", position); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.lists, container, false); heroesLV = (ListView) layout.findViewById(R.id.heroesList); Bundle bundle = getArguments(); if (bundle != null) { switch (bundle.getInt("type")) { case 0: String[] sHeroes = getResources().getStringArray(R.array.strength_heroes); int[] sIcons = {R.drawable.abaddon_icon, R.drawable.alchemist_icon, R.drawable.axe_icon, R.drawable.beastmaster_icon, R.drawable.brewmaster_icon, R.drawable.bristleback_icon, R.drawable.centaur_warrunner_icon, R.drawable.chaos_knight_icon, R.drawable.clockwerk_icon, R.drawable.doom_bringer_icon, R.drawable.dragon_knight_icon, R.drawable.earthshaker_icon, R.drawable.earth_spirit_icon, R.drawable.elder_titan_icon, R.drawable.huskar_icon, R.drawable.io_icon, R.drawable.kunkka_icon, R.drawable.legion_commander_icon, R.drawable.lifestealer_icon, R.drawable.lycan_icon, R.drawable.magnus_icon, R.drawable.night_stalker_icon, R.drawable.omniknight_icon, R.drawable.phoenix_icon, R.drawable.pudge_icon, R.drawable.sand_king_icon, R.drawable.slardar_icon, R.drawable.spirit_breaker_icon, R.drawable.sven_icon, R.drawable.tidehunter_icon, R.drawable.timbersaw_icon, R.drawable.tiny_icon, R.drawable.treant_protector_icon, R.drawable.tusk_icon, R.drawable.undying_icon, R.drawable.wraith_king_icon}; heroesAdapter sAdapter = new heroesAdapter(getContext(), sHeroes, sIcons); heroesLV.setAdapter(sAdapter); break; case 1: String[] aHeroes = getResources().getStringArray(R.array.agility_heroes); int[] aIcons = {R.drawable.anti_mage_icon, R.drawable.arc_warden_icon, R.drawable.bloodseeker_icon, R.drawable.broodmother_icon, R.drawable.bounty_hunter_icon, R.drawable.clinkz_icon, R.drawable.drow_ranger_icon, R.drawable.ember_spirit_icon, R.drawable.faceless_void_icon, R.drawable.gyrocopter_icon, R.drawable.juggernaut_icon, R.drawable.lone_druid_icon, R.drawable.luna_icon, R.drawable.medusa_icon, R.drawable.meepo_icon, R.drawable.mirana_icon, R.drawable.morphling_icon, R.drawable.naga_siren_icon, R.drawable.nyx_assassin_icon, R.drawable.phantom_assassin_icon, R.drawable.phantom_lancer_icon, R.drawable.razor_icon, R.drawable.riki_icon, R.drawable.shadow_fiend_icon, R.drawable.slark_icon, R.drawable.sniper_icon, R.drawable.spectre_icon, R.drawable.templar_assassin_icon, R.drawable.terrorblade_icon, R.drawable.troll_warlord_icon, R.drawable.ursa_icon, R.drawable.vengeful_spirit_icon, R.drawable.venomancer_icon, R.drawable.viper_icon, R.drawable.weaver_icon}; heroesAdapter aAdapter = new heroesAdapter(getContext(), aHeroes, aIcons); heroesLV.setAdapter(aAdapter); break; case 2: String[] iHeroes = getResources().getStringArray(R.array.intelligence_heroes); int[] iIcons = {R.drawable.ancient_apparition_icon, R.drawable.bane_icon, R.drawable.batrider_icon, R.drawable.chen_icon, R.drawable.crystal_maiden_icon, R.drawable.dark_seer_icon, R.drawable.dazzle_icon, R.drawable.death_prophet_icon, R.drawable.disruptor_icon, R.drawable.enchantress_icon, R.drawable.enigma_icon, R.drawable.invoker_icon, R.drawable.jakiro_icon, R.drawable.keeper_of_the_light_icon, R.drawable.leshrac_icon, R.drawable.lich_icon, R.drawable.lina_icon, R.drawable.lion_icon, R.drawable.natures_prophet_icon, R.drawable.necrophos_icon, R.drawable.ogre_magi_icon, R.drawable.oracle_icon, R.drawable.outworld_devourer_icon, R.drawable.puck_icon, R.drawable.pugna_icon, R.drawable.queen_of_pain_icon, R.drawable.rubick_icon, R.drawable.silencer_icon, R.drawable.storm_spirit_icon, R.drawable.shadow_demon_icon, R.drawable.shadow_shaman_icon, R.drawable.tinker_icon, R.drawable.warlock_icon, R.drawable.windranger_icon, R.drawable.winter_wyvern_icon, R.drawable.witch_doctor_icon, R.drawable.zeus_icon}; heroesAdapter iAdapter = new heroesAdapter(getContext(), iHeroes, iIcons); heroesLV.setAdapter(iAdapter); break; } } typeFragement.heroesLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { slideIn(); TextView heroName = (TextView) view.findViewById(R.id.hero_name); String hero = (String) heroName.getText(); if (prevHero != hero) { heroPreview.scrollTo(0, 0); } prevHero = hero; getHeroDetails(hero); for (int i = 0; i < skillNames.length; i++) { if (skillTemplate == null) { Log.d("SKILLTEMPLATE", " IS NULL"); } LayoutInflater layoutInflater = (LayoutInflater) applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); skillTemplate = layoutInflater.inflate(R.layout.skill_template, heroIntro, false); ImageView skillIV = (ImageView) skillTemplate.findViewById(R.id.skill_image); TextView skillNameTV = (TextView) skillTemplate.findViewById(R.id.skill_name); TextView skillDesTV = (TextView) skillTemplate.findViewById(R.id.skill_description); TextView skillSpecTV = (TextView) skillTemplate.findViewById(R.id.skill_specifications); skillIV.setImageResource(skillIcons[i]); skillNameTV.setText(skillNames[i]); skillDesTV.setText(skillDesc[i]); skillSpecTV.setText(skillSpec[i]); skillDesTV.setTextColor(Color.DKGRAY); skillNameTV.setTextColor(Color.DKGRAY); skillSpecTV.setTextColor(Color.DKGRAY); heroIntro.addView(skillTemplate); } } }); return layout; } } public static void getHeroDetails(String hero) { heroIntro.removeAllViewsInLayout(); switch (hero) { case "Ancient Apparition": heroImage.setImageResource(R.drawable.ancient_apparition); heroLore.setText(appResource.getString(R.string.ancient_apparition_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.cold_feet_icon, R.drawable.ice_vortex_icon, R.drawable.chilling_touch_icon, R.drawable.ice_blast_icon, R.drawable.release_icon}; skillNames = appResource.getStringArray(R.array.ancient_apparition_skill_names); skillDesc = appResource.getStringArray(R.array.ancient_apparition_skill_description); skillSpec = appResource.getStringArray(R.array.ancient_apparition_skills_specifications); break; case "Bane": heroImage.setImageResource(R.drawable.bane); heroLore.setText(appResource.getString(R.string.bane_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.enfeeble_icon, R.drawable.brain_sap_icon, R.drawable.nightmare_icon, R.drawable.fiends_grip_icon, R.drawable.nightmare_end_icon}; skillNames = appResource.getStringArray(R.array.bane_skill_names); skillDesc = appResource.getStringArray(R.array.bane_skill_description); skillSpec = appResource.getStringArray(R.array.bane_skills_specifications); break; case "Batrider": heroImage.setImageResource(R.drawable.batrider); heroLore.setText(appResource.getString(R.string.batrider_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.sticky_napalm_icon, R.drawable.flamebreak_icon, R.drawable.firefly_icon, R.drawable.flaming_lasso_icon}; skillNames = appResource.getStringArray(R.array.batrider_skill_names); skillDesc = appResource.getStringArray(R.array.batrider_skill_description); skillSpec = appResource.getStringArray(R.array.batrider_skills_specifications); break; case "Chen": heroImage.setImageResource(R.drawable.chen); heroLore.setText(appResource.getString(R.string.chen_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.arcane_orb_icon, R.drawable.astral_imprisonment_icon, R.drawable.essence_aura_icon, R.drawable.sanitys_eclipse_icon}; skillNames = appResource.getStringArray(R.array.outworld_devourer_skill_names); skillDesc = appResource.getStringArray(R.array.outworld_devourer_skill_description); skillSpec = appResource.getStringArray(R.array.outworld_devourer_skills_specifications); break; case "Crystal Maiden": heroImage.setImageResource(R.drawable.crystal_maiden); heroLore.setText(appResource.getString(R.string.crystal_maiden_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.crystal_nova_icon, R.drawable.frostbite_icon, R.drawable.arcane_aura_icon, R.drawable.freezing_field_icon}; skillNames = appResource.getStringArray(R.array.crystal_maiden_skill_names); skillDesc = appResource.getStringArray(R.array.crystal_maiden_skill_description); skillSpec = appResource.getStringArray(R.array.crystal_maiden_skills_specifications); break; case "Dark Seer": heroImage.setImageResource(R.drawable.dark_seer); heroLore.setText(appResource.getString(R.string.dark_seer_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.vacuum_icon, R.drawable.ion_shell_icon, R.drawable.surge_icon, R.drawable.wall_of_replica_icon}; skillNames = appResource.getStringArray(R.array.dark_seer_skill_names); skillDesc = appResource.getStringArray(R.array.dark_seer_skill_description); skillSpec = appResource.getStringArray(R.array.dark_seer_skills_specifications); break; case "Dazzle": heroImage.setImageResource(R.drawable.dazzle); heroLore.setText(appResource.getString(R.string.dazzle_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.poison_touch_icon, R.drawable.shallow_grave_icon, R.drawable.shadow_wave_icon, R.drawable.weave_icon}; skillNames = appResource.getStringArray(R.array.dazzle_skill_names); skillDesc = appResource.getStringArray(R.array.dazzle_skill_description); skillSpec = appResource.getStringArray(R.array.dazzle_skills_specifications); break; case "Death Prophet": heroImage.setImageResource(R.drawable.death_prophet); heroLore.setText(appResource.getString(R.string.death_prophet_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.crypt_swarm_icon, R.drawable.silence_icon, R.drawable.spirit_siphon_icon, R.drawable.exorcism_icon}; skillNames = appResource.getStringArray(R.array.death_prophet_skill_names); skillDesc = appResource.getStringArray(R.array.death_prophet_skill_description); skillSpec = appResource.getStringArray(R.array.death_prophet_skills_specifications); break; case "Disruptor": heroImage.setImageResource(R.drawable.disruptor); heroLore.setText(appResource.getString(R.string.disruptor_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.thunder_strike_icon, R.drawable.glimpse_icon, R.drawable.kinetic_field_icon, R.drawable.static_storm_icon}; skillNames = appResource.getStringArray(R.array.disruptor_skill_names); skillDesc = appResource.getStringArray(R.array.disruptor_skill_description); skillSpec = appResource.getStringArray(R.array.disruptor_skills_specifications); break; case "Enchantress": heroImage.setImageResource(R.drawable.enchantress); heroLore.setText(appResource.getString(R.string.enchantress_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.untouchable_icon, R.drawable.enchant_icon, R.drawable.natures_attendants_icon, R.drawable.impetus_icon}; skillNames = appResource.getStringArray(R.array.enchantress_skill_names); skillDesc = appResource.getStringArray(R.array.enchantress_skill_description); skillSpec = appResource.getStringArray(R.array.enchantress_skills_specifications); break; case "Enigma": heroImage.setImageResource(R.drawable.enigma); heroLore.setText(appResource.getString(R.string.enigma_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.malefice_icon, R.drawable.demonic_conversion_icon, R.drawable.midnight_pulse_icon, R.drawable.black_hole_icon}; skillNames = appResource.getStringArray(R.array.enigma_skill_names); skillDesc = appResource.getStringArray(R.array.enigma_skill_description); skillSpec = appResource.getStringArray(R.array.enigma_skills_specifications); break; case "Invoker": heroImage.setImageResource(R.drawable.invoker); heroLore.setText(appResource.getString(R.string.invoker_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.quas_icon, R.drawable.wex_icon, R.drawable.exort_icon, R.drawable.invoke_icon, R.drawable.cold_snap_icon, R.drawable.ghost_walk_icon, R.drawable.tornado_icon, R.drawable.emp_icon, R.drawable.alacrity_icon, R.drawable.chaos_meteor_icon, R.drawable.sun_strike_icon, R.drawable.forge_spirit_icon, R.drawable.ice_wall_icon, R.drawable.deafening_blast_icon}; skillNames = appResource.getStringArray(R.array.invoker_skill_names); skillDesc = appResource.getStringArray(R.array.invoker_skill_description); skillSpec = appResource.getStringArray(R.array.invoker_skills_specifications); break; case "Jakiro": heroImage.setImageResource(R.drawable.jakiro); heroLore.setText(appResource.getString(R.string.jakiro_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.dual_breath_icon, R.drawable.ice_path_icon, R.drawable.liquid_fire_icon, R.drawable.macropyre_icon}; skillNames = appResource.getStringArray(R.array.jakiro_skill_names); skillDesc = appResource.getStringArray(R.array.jakiro_skill_description); skillSpec = appResource.getStringArray(R.array.jakiro_skills_specifications); break; case "Keeper of the Light": heroImage.setImageResource(R.drawable.keeper_of_the_light); heroLore.setText(appResource.getString(R.string.keeper_of_the_light_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.illuminate_icon, R.drawable.mana_leak_icon, R.drawable.chakra_magic_icon, R.drawable.recall_icon, R.drawable.blinding_light_icon, R.drawable.spirit_form_icon, R.drawable.release_illuminate_icon, R.drawable.illuminate_spirit_form_icon}; skillNames = appResource.getStringArray(R.array.keeper_of_the_light_skill_names); skillDesc = appResource.getStringArray(R.array.keeper_of_the_light_skill_description); skillSpec = appResource.getStringArray(R.array.keeper_of_the_light_skills_specifications); break; case "Leshrac": heroImage.setImageResource(R.drawable.leshrac); heroLore.setText(appResource.getString(R.string.leshrac_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.split_earth_icon, R.drawable.diabolic_edict_icon, R.drawable.lightning_storm_icon, R.drawable.pulse_nova_icon}; skillNames = appResource.getStringArray(R.array.leshrac_skill_names); skillDesc = appResource.getStringArray(R.array.leshrac_skill_description); skillSpec = appResource.getStringArray(R.array.leshrac_skills_specifications); break; case "Lich": heroImage.setImageResource(R.drawable.lich); heroLore.setText(appResource.getString(R.string.lich_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.frost_blast_icon, R.drawable.ice_armor_icon, R.drawable.sacrifice_icon, R.drawable.chain_frost_icon}; skillNames = appResource.getStringArray(R.array.lich_skill_names); skillDesc = appResource.getStringArray(R.array.lich_skill_description); skillSpec = appResource.getStringArray(R.array.lich_skills_specifications); break; case "Lina": heroImage.setImageResource(R.drawable.lina); heroLore.setText(appResource.getString(R.string.lina_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.dragon_slave_icon, R.drawable.light_strike_array_icon, R.drawable.fiery_soul_icon, R.drawable.laguna_blade_icon}; skillNames = appResource.getStringArray(R.array.lina_skill_names); skillDesc = appResource.getStringArray(R.array.lina_skill_description); skillSpec = appResource.getStringArray(R.array.lina_skills_specifications); break; case "Lion": heroImage.setImageResource(R.drawable.lion); heroLore.setText(appResource.getString(R.string.lion_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.earth_spike_icon, R.drawable.hex_lion_icon, R.drawable.mana_drain_icon, R.drawable.finger_of_death_icon}; skillNames = appResource.getStringArray(R.array.lion_skill_names); skillDesc = appResource.getStringArray(R.array.lion_skill_description); skillSpec = appResource.getStringArray(R.array.lion_skills_specifications); break; case "Natures Prophet": heroImage.setImageResource(R.drawable.natures_prophet); heroLore.setText(appResource.getString(R.string.natures_prophet_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.sprout_icon, R.drawable.teleportation_icon, R.drawable.natures_call_icon, R.drawable.wrath_of_nature_icon}; skillNames = appResource.getStringArray(R.array.natures_prophet_skill_names); skillDesc = appResource.getStringArray(R.array.natures_prophet_skill_description); skillSpec = appResource.getStringArray(R.array.natures_prophet_skills_specifications); break; case "Necrophos": heroImage.setImageResource(R.drawable.necrophos); heroLore.setText(appResource.getString(R.string.necrophos_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.death_pulse_icon, R.drawable.heartstopper_aura_icon, R.drawable.sadist_icon, R.drawable.reapers_scythe_icon}; skillNames = appResource.getStringArray(R.array.necrophos_skill_names); skillDesc = appResource.getStringArray(R.array.necrophos_skill_description); skillSpec = appResource.getStringArray(R.array.necrophos_skills_specifications); break; case "Ogre Magi": heroImage.setImageResource(R.drawable.ogre_magi); heroLore.setText(appResource.getString(R.string.ogre_magi_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.fireblast_icon, R.drawable.ignite_icon, R.drawable.bloodlust_icon, R.drawable.multicast_icon}; skillNames = appResource.getStringArray(R.array.ogre_magi_skill_names); skillDesc = appResource.getStringArray(R.array.ogre_magi_skill_description); skillSpec = appResource.getStringArray(R.array.ogre_magi_skills_specifications); break; case "Oracle": heroImage.setImageResource(R.drawable.oracle); heroLore.setText(appResource.getString(R.string.oracle_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.fortunes_end_icon, R.drawable.fates_edict_icon, R.drawable.purifying_flames_icon, R.drawable.false_promise_icon}; skillNames = appResource.getStringArray(R.array.oracle_skill_names); skillDesc = appResource.getStringArray(R.array.oracle_skill_description); skillSpec = appResource.getStringArray(R.array.oracle_skills_specifications); break; case "Outworld Devourer": heroImage.setImageResource(R.drawable.outworld_devourer); heroLore.setText(appResource.getString(R.string.outworld_devourer_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.arcane_orb_icon, R.drawable.astral_imprisonment_icon, R.drawable.essence_aura_icon, R.drawable.sanitys_eclipse_icon}; skillNames = appResource.getStringArray(R.array.outworld_devourer_skill_names); skillDesc = appResource.getStringArray(R.array.outworld_devourer_skill_description); skillSpec = appResource.getStringArray(R.array.outworld_devourer_skills_specifications); break; case "Puck": heroImage.setImageResource(R.drawable.puck); heroLore.setText(appResource.getString(R.string.puck_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.illusory_orb_icon, R.drawable.waning_rift_icon, R.drawable.phase_shift_icon, R.drawable.ethereal_jaunt_icon, R.drawable.dream_coil_icon}; skillNames = appResource.getStringArray(R.array.puck_skill_names); skillDesc = appResource.getStringArray(R.array.puck_skills_description); skillSpec = appResource.getStringArray(R.array.puck_skill_specifications); break; case "Pugna": heroImage.setImageResource(R.drawable.pugna); heroLore.setText(appResource.getString(R.string.pugna_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.nether_blast_icon, R.drawable.decrepify_icon, R.drawable.nether_ward_icon, R.drawable.life_drain_icon}; skillNames = appResource.getStringArray(R.array.pugna_skill_names); skillDesc = appResource.getStringArray(R.array.pugna_skills_description); skillSpec = appResource.getStringArray(R.array.pugna_skill_specifications); break; case "Queen of Pain": heroImage.setImageResource(R.drawable.queen_of_pain); heroLore.setText(appResource.getString(R.string.queen_of_pain_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.shadow_strike_icon, R.drawable.blink_queen_of_pain_icon, R.drawable.scream_of_pain_icon, R.drawable.sonic_wave_icon}; skillNames = appResource.getStringArray(R.array.queen_of_pain_skill_names); skillDesc = appResource.getStringArray(R.array.queen_of_pain_skill_description); skillSpec = appResource.getStringArray(R.array.queen_if_pain_skills_specifications); break; case "Rubick": heroImage.setImageResource(R.drawable.rubick); heroLore.setText(appResource.getString(R.string.rubick_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.telekinesis_icon, R.drawable.telekinesis_land_icon, R.drawable.fade_bolt_icon, R.drawable.null_field_icon, R.drawable.spell_steal_icon}; skillNames = appResource.getStringArray(R.array.rubick_skill_names); skillDesc = appResource.getStringArray(R.array.rubick_skill_description); skillSpec = appResource.getStringArray(R.array.rubick_skills_specifications); break; case "Silencer": heroImage.setImageResource(R.drawable.silencer); heroLore.setText(appResource.getString(R.string.silencer_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.arcane_curse_icon, R.drawable.glaives_of_wisdom_icon, R.drawable.last_word_icon, R.drawable.global_silence_icon}; skillNames = appResource.getStringArray(R.array.silencer_skill_names); skillDesc = appResource.getStringArray(R.array.silencer_skill_description); skillSpec = appResource.getStringArray(R.array.silencer_skills_specifications); break; case "Strom Spirit": heroImage.setImageResource(R.drawable.storm_spirit); heroLore.setText(appResource.getString(R.string.storm_spirit_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.static_remnant_icon, R.drawable.electric_vortex_icon, R.drawable.overload_icon, R.drawable.ball_lightning_icon}; skillNames = appResource.getStringArray(R.array.storm_spirit_skill_names); skillDesc = appResource.getStringArray(R.array.storm_spirit_skill_description); skillSpec = appResource.getStringArray(R.array.storm_spirit_skills_specifications); break; case "Shadow Demon": heroImage.setImageResource(R.drawable.shadow_demon); heroLore.setText(appResource.getString(R.string.shadow_demon_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.disruption_icon, R.drawable.soul_catcher_icon, R.drawable.shadow_poison_icon, R.drawable.shadow_poison_release_icon, R.drawable.demonic_purge_icon}; skillNames = appResource.getStringArray(R.array.shadow_demon_skill_names); skillDesc = appResource.getStringArray(R.array.shadow_demon_skill_description); skillSpec = appResource.getStringArray(R.array.shadow_demon_skills_specifications); break; case "Shadow Shaman": heroImage.setImageResource(R.drawable.shadow_shaman); heroLore.setText(appResource.getString(R.string.shadow_shaman_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.ether_shock_icon, R.drawable.hex_shadow_shaman_icon, R.drawable.shackles_icon, R.drawable.mass_serpent_ward_icon}; skillNames = appResource.getStringArray(R.array.shadow_shaman_skill_names); skillDesc = appResource.getStringArray(R.array.shadow_shaman_skill_description); skillSpec = appResource.getStringArray(R.array.shadow_shaman_skills_specifications); break; case "Tinker": heroImage.setImageResource(R.drawable.tinker); heroLore.setText(appResource.getString(R.string.tinker_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.laser_icon, R.drawable.heat_seeking_missile_icon, R.drawable.march_of_the_machines_icon, R.drawable.rearm_icon}; skillNames = appResource.getStringArray(R.array.tinker_skill_names); skillDesc = appResource.getStringArray(R.array.tinker_skill_description); skillSpec = appResource.getStringArray(R.array.tinker_skills_specifications); break; case "Warlock": heroImage.setImageResource(R.drawable.warlock); heroLore.setText(appResource.getString(R.string.warlock_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.fatal_bonds_icon, R.drawable.shadow_word_icon, R.drawable.upheaval_icon, R.drawable.chaotic_offering_icon}; skillNames = appResource.getStringArray(R.array.warlock_skill_names); skillDesc = appResource.getStringArray(R.array.warlock_skill_description); skillSpec = appResource.getStringArray(R.array.warlock_skills_specifications); break; case "Windranger": heroImage.setImageResource(R.drawable.windranger); heroLore.setText(appResource.getString(R.string.windranger_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.shackleshot_icon, R.drawable.powershot_icon, R.drawable.windrun_icon, R.drawable.focus_fire_icon}; skillNames = appResource.getStringArray(R.array.windranger_skill_names); skillDesc = appResource.getStringArray(R.array.windranger_skill_description); skillSpec = appResource.getStringArray(R.array.windranger_skills_specifications); break; case "Winter Wyvern": heroImage.setImageResource(R.drawable.winter_wyvern); heroLore.setText(appResource.getString(R.string.winter_wyvern_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.arctic_burn_icon, R.drawable.splinter_blast_icon, R.drawable.cold_embrace_icon, R.drawable.winters_curse_icon}; skillNames = appResource.getStringArray(R.array.winter_wyvern_skill_names); skillDesc = appResource.getStringArray(R.array.winter_wyvern_skill_description); skillSpec = appResource.getStringArray(R.array.winter_wyvern_skills_specifications); break; case "Witch Doctor": heroImage.setImageResource(R.drawable.witch_doctor); heroLore.setText(appResource.getString(R.string.witch_doctor_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.paralyzing_cask_icon, R.drawable.voodoo_restoration_icon, R.drawable.maledict_icon, R.drawable.death_ward_icon}; skillNames = appResource.getStringArray(R.array.witch_doctor_skill_names); skillDesc = appResource.getStringArray(R.array.witch_doctor_skill_description); skillSpec = appResource.getStringArray(R.array.witch_doctor_skills_specifications); break; case "Zeus": heroImage.setImageResource(R.drawable.zeus); heroLore.setText(appResource.getString(R.string.zeus_lore)); heroLore.setTextColor(Color.DKGRAY); skillIcons = new int[]{R.drawable.arc_lightning_icon, R.drawable.lightning_bolt_icon, R.drawable.static_field_icon, R.drawable.thundergods_wrath_icon}; skillNames = appResource.getStringArray(R.array.zeus_skill_names); skillDesc = appResource.getStringArray(R.array.zeus_skill_description); skillSpec = appResource.getStringArray(R.array.zeus_skills_specifications); break; } } }
import java.util.InputMismatchException; import java.util.Scanner; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class Main { private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Oracle JDBC Driver not found!"); e.printStackTrace(); return; } System.out.println("Oracle JDBC Driver registered!"); Connection connection = null; try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@toldb.oulu.fi:1521:toldb11", "STU31", "delrix123"); } catch (SQLException e) { System.out.println("Connection failed!"); e.printStackTrace(); return; } if (connection != null) { System.out.println("Connection to database successful!"); } else { System.out.println("Failed to make connection!"); } System.out.print("\n\n"); System.out.println("1: Show items."); System.out.println("2: Show customers."); System.out.println("Make selection and press ENTER."); switch (getUserInput()) { case 1: showItems(); break; case 2: showCustomers(); break; } try { connection.close(); } catch (SQLException e) { System.out.println("Error while closing connection!"); e.printStackTrace(); } } private static int getUserInput() { int choice = 0; while (true) { try { choice = scan.nextInt(); if (choice != 1 && choice != 2) { scan.nextLine(); System.out.println("Please select 1 or 2."); } else { scan.nextLine(); break; } } catch (InputMismatchException ime) { System.out.println("Please select 1 or 2."); scan.nextLine(); } } return choice; } private static void showCustomers() { } private static void showItems() { } }
package fr.areaX.smartcard; import javax.smartcardio.CardChannel; import javax.smartcardio.CardException; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; import fr.areaX.crypto.XCryptoKeys; public class SmartIdentityCard implements SmartCardInterface { private SmartCardDrive drive; public SmartIdentityCard() throws CardException { drive = new SmartCardDrive(); drive.selectFirstTerminal(); } @Override public boolean hasCard() { try { drive.connectCard(); } catch (CardException e) { e.printStackTrace(); return false; } return true; } @Override public byte[] read(int userArea) throws CardException { CardChannel channel = drive.getCurrentCard().getBasicChannel(); CommandAPDU commande; if (userArea == 1) commande = new CommandAPDU(0x80,0xBE,0x00,0x10,0x40); else commande = new CommandAPDU(0x80,0xBE,0x00,0x28,0x40); ResponseAPDU r = channel.transmit(commande); return r.getData(); } @Override public void write(byte[] stream, int userArea) throws CardException { CardChannel channel = drive.getCurrentCard().getBasicChannel(); CommandAPDU commande ; byte[] header; if (userArea == 1) header = new byte[]{(byte)0x80,(byte) 0xDE,(byte)0x00,(byte)0x10,(byte)0x40}; else header = new byte[]{(byte)0x80,(byte) 0xDE,(byte)0x00,(byte)0x28,(byte)0x40}; byte[] writeStream = new byte[64+5]; for(int i=0; i<5; i++){ writeStream[i] = header[i]; } int wi = 5; for(int i=0; i<stream.length; i++){ writeStream[wi++] = stream[i]; } for(int i = stream.length; i<64; i++){ writeStream[5+i] = (byte)0x00; } ResponseAPDU r; byte apdu[]={(byte)0x00,(byte) 0x20,(byte)0x00,(byte)0x07,(byte)0x04,(byte)0xAA,(byte)0xAA,(byte)0xAA,(byte)0xAA}; commande = new CommandAPDU(apdu);//test code pin r = channel.transmit(commande); System.out.println("pre reponse : " + "SW1 : 0x"+Integer.toHexString(r.getSW1())+" SW2 : 0x"+Integer.toHexString(r.getSW2())+" data : "+drive.toString(r.getData())); //byte apdu2[]=,(byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01}; commande = new CommandAPDU(writeStream);//test code pin r = channel.transmit(commande); System.out.println("reponse : " + "SW1 : 0x"+Integer.toHexString(r.getSW1())+" SW2 : 0x"+Integer.toHexString(r.getSW2())+" data : "+drive.toString(r.getData())); } public static byte getRandomByte(){ int i = (int) (Math.random()*1000) % 50; byte b = (byte)i; return b; } public static int getRandomIntId(){ int i = 10000; i += (int) Math.random()*1000; return i%10000; } public static int getRandomToken(){ int i = (int) Math.random()*100000; return i%1000000; } public static void initiliazeCard() throws Exception{ SmartIdentityCard sm = new SmartIdentityCard(); XCryptoKeys keys = new XCryptoKeys(); keys.loadPrivateKey("private.key"); keys.loadPublicKey("public.key"); byte[] cardContent = new byte[12]; int randomIntId = getRandomIntId(); int randomIntToken = getRandomToken(); byte[] byteId = SmartCardHelper.fromIntToByte(randomIntId); byte[] byteToken = SmartCardHelper.fromIntToByte(randomIntToken); int i; for(i=0; i<byteId.length; i++){ cardContent[i] = byteId[i]; } int ii=0; for(i=byteId.length; i<12; i++){ cardContent[i] = byteToken[ii++]; } System.out.println("Id generated : " + randomIntId + " " +randomIntToken); System.out.println("Id in byte" + SmartCardHelper.fromByteToInt(cardContent)); byte[] signature = keys.generateSignature(cardContent); if(!sm.hasCard()){ System.err.println("No card present in the reader"); return; } System.out.println("The size of content is :" + cardContent.length); System.out.println("The size of the signature is " + signature.length); System.out.println("Initializing data to the card"); sm.write(cardContent, 1); sm.write(signature, 2); System.out.println("Writing to the card user area 1/2 terminated"); System.out.println("Verifying the written content"); byte[] read1 = sm.read(1); byte[] read2 = sm.read(2); System.out.println("Card content 1 o : " + SmartCardDrive.toString(cardContent)); System.out.println("Card content 1 r : " + SmartCardDrive.toString(read1)); System.out.println("Card content 2 o : " + SmartCardDrive.toString(signature)); System.out.println("Card content 2 r : " + SmartCardDrive.toString(read2)); boolean equal = true; for(i = 0; i<cardContent.length; i++){ System.out.print(cardContent[i] + " " +read1[i]+"\t"); if (cardContent[i]!=read1[i]){ equal = false; break; } } System.out.println(""); if (!equal){ System.out.println("Read 1 and cardContent not equal"); } equal = true; for(i = 0; i<signature.length; i++){ System.out.print(signature[i] + " " +read2[i]+"\t"); if (signature[i]!=read2[i]){ equal = false; break; } } System.out.println(""); if (!equal){ System.out.println("Read 2 and signature not equal"); } } public static void main(String[] args) throws Exception { initiliazeCard(); System.exit(0); SmartIdentityCard sm = new SmartIdentityCard(); if (!sm.hasCard()){ System.out.println("No card in the drive"); return; } byte writeData[] = new byte[64]; for (int i=0; i<64; i++){ writeData[i] = getRandomByte(); } sm.write(writeData, 1); byte[] read = sm.read(1); String readStr = SmartCardDrive.toString(read); String toWriteStr = SmartCardDrive.toString(writeData); System.out.println("The size of readBuffer is: " + read.length); System.out.println("Read content: " + readStr); System.out.println("To write content: " + toWriteStr); } }
package com.ctrip.hermes.broker.queue; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unidal.tuple.Pair; import com.ctrip.hermes.broker.ack.internal.AckHolder; import com.ctrip.hermes.broker.ack.internal.AckHolder.AckHolderType; import com.ctrip.hermes.broker.ack.internal.BatchResult; import com.ctrip.hermes.broker.ack.internal.ContinuousRange; import com.ctrip.hermes.broker.ack.internal.DefaultAckHolder; import com.ctrip.hermes.broker.ack.internal.EnumRange; import com.ctrip.hermes.broker.ack.internal.ForwardOnlyAckHolder; import com.ctrip.hermes.broker.config.BrokerConfig; import com.ctrip.hermes.broker.queue.DefaultMessageQueueManager.Operation; import com.ctrip.hermes.broker.queue.storage.MessageQueueStorage; import com.ctrip.hermes.core.bo.Tpp; import com.ctrip.hermes.core.lease.Lease; import com.ctrip.hermes.core.message.TppConsumerMessageBatch.MessageMeta; import com.ctrip.hermes.core.meta.MetaService; import com.ctrip.hermes.core.transport.command.SendMessageCommand.MessageBatchWithRawData; import com.ctrip.hermes.core.utils.PlexusComponentLocator; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; /** * @author Leo Liang(jhliang@ctrip.com) * */ public abstract class AbstractMessageQueue implements MessageQueue { private static final Logger log = LoggerFactory.getLogger(AbstractMessageQueue.class); protected String m_topic; protected int m_partition; protected AtomicReference<MessageQueueDumper> m_dumper = new AtomicReference<>(null); protected MessageQueueStorage m_storage; protected ConcurrentMap<String, AtomicReference<MessageQueueCursor>> m_cursors = new ConcurrentHashMap<>(); protected AtomicBoolean m_stopped = new AtomicBoolean(false); // TODO while consumer disconnect, clear holder and offset protected Map<Pair<Boolean, String>, AckHolder<MessageMeta>> m_ackHolders; protected Map<Pair<Boolean, String>, AckHolder<MessageMeta>> m_resendAckHolders; protected Map<Pair<Boolean, String>, AckHolder<MessageMeta>> m_forwardOnlyAckHolders; private BlockingQueue<Operation> m_opQueue; private AckTask m_ackTask; private BrokerConfig m_config; private MetaService m_metaService; private ScheduledExecutorService m_ackOpExecutor; public AbstractMessageQueue(String topic, int partition, MessageQueueStorage storage, ScheduledExecutorService ackOpExecutor) { m_topic = topic; m_partition = partition; m_storage = storage; m_ackHolders = new ConcurrentHashMap<>(); m_resendAckHolders = new ConcurrentHashMap<>(); m_forwardOnlyAckHolders = new ConcurrentHashMap<>(); m_ackOpExecutor = ackOpExecutor; m_config = PlexusComponentLocator.lookup(BrokerConfig.class); m_metaService = PlexusComponentLocator.lookup(MetaService.class); init(); } private void init() { m_opQueue = new LinkedBlockingQueue<>(m_config.getAckOpQueueSize()); m_ackTask = new AckTask(); m_ackOpExecutor.schedule(m_ackTask, m_config.getMessageQueueCheckIntervalMillis(), TimeUnit.MILLISECONDS); } @Override public ListenableFuture<Map<Integer, Boolean>> appendMessageAsync(boolean isPriority, MessageBatchWithRawData batch, Lease lease) { if (m_stopped.get()) { return null; } MessageQueueDumper existingDumper = m_dumper.get(); if (existingDumper == null || existingDumper.getLease().getId() != lease.getId()) { MessageQueueDumper newDumper = createDumper(lease); if (m_dumper.compareAndSet(existingDumper, newDumper)) { newDumper.start(); } } SettableFuture<Map<Integer, Boolean>> future = SettableFuture.create(); m_dumper.get().submit(future, batch, isPriority); return future; } @Override public MessageQueueCursor getCursor(String groupId, Lease lease) { if (m_stopped.get()) { return null; } m_cursors.putIfAbsent(groupId, new AtomicReference<MessageQueueCursor>(null)); MessageQueueCursor existingCursor = m_cursors.get(groupId).get(); if (existingCursor == null || existingCursor.getLease().getId() != lease.getId() || existingCursor.hasError()) { MessageQueueCursor newCursor = create(groupId, lease); if (m_cursors.get(groupId).compareAndSet(existingCursor, newCursor)) { clearHolders(groupId); newCursor.init(); } } MessageQueueCursor cursor = m_cursors.get(groupId).get(); return cursor.isInited() ? cursor : new NoopMessageQueueCursor(); } private void clearHolders(String groupId) { m_ackHolders.remove(new Pair<Boolean, String>(true, groupId)); m_ackHolders.remove(new Pair<Boolean, String>(false, groupId)); m_resendAckHolders.remove(new Pair<Boolean, String>(true, groupId)); m_resendAckHolders.remove(new Pair<Boolean, String>(false, groupId)); m_forwardOnlyAckHolders.remove(new Pair<Boolean, String>(true, groupId)); m_forwardOnlyAckHolders.remove(new Pair<Boolean, String>(false, groupId)); } @Override public void nack(boolean resend, boolean isPriority, String groupId, List<Pair<Long, MessageMeta>> msgId2Metas) { if (!m_stopped.get()) { doNack(resend, isPriority, groupId, msgId2Metas); } } @Override public void ack(boolean resend, boolean isPriority, String groupId, long msgSeq) { if (!m_stopped.get()) { doAck(resend, isPriority, groupId, msgSeq); } } @Override public void stop() { if (m_stopped.compareAndSet(false, true)) { MessageQueueDumper dumper = m_dumper.get(); if (dumper != null) { dumper.stop(); } for (AtomicReference<MessageQueueCursor> cursorRef : m_cursors.values()) { MessageQueueCursor cursor = cursorRef.get(); if (cursor != null) { cursor.stop(); } } m_ackTask.run(); doStop(); } } @Override public void checkHolders() { for (Entry<Pair<Boolean, String>, AckHolder<MessageMeta>> entry : m_forwardOnlyAckHolders.entrySet()) { BatchResult<MessageMeta> result = entry.getValue().scan(); doCheckHolders(entry.getKey(), result, false); } for (Entry<Pair<Boolean, String>, AckHolder<MessageMeta>> entry : m_ackHolders.entrySet()) { BatchResult<MessageMeta> result = entry.getValue().scan(); doCheckHolders(entry.getKey(), result, false); } for (Entry<Pair<Boolean, String>, AckHolder<MessageMeta>> entry : m_resendAckHolders.entrySet()) { BatchResult<MessageMeta> result = entry.getValue().scan(); doCheckHolders(entry.getKey(), result, true); } } protected void doCheckHolders(Pair<Boolean, String> pg, BatchResult<MessageMeta> result, boolean isResend) { if (result != null) { Tpp tpp = new Tpp(m_topic, m_partition, pg.getKey()); String groupId = pg.getValue(); ContinuousRange doneRange = result.getDoneRange(); EnumRange<MessageMeta> failRange = result.getFailRange(); if (failRange != null) { if (log.isDebugEnabled()) { log.debug( "Nack messages(topic={}, partition={}, priority={}, groupId={}, isResend={}, msgIdToRemainingRetries={}).", tpp.getTopic(), tpp.getPartition(), tpp.isPriority(), groupId, isResend, failRange.getOffsets()); } try { doNack(isResend, pg.getKey(), groupId, failRange.getOffsets()); } catch (Exception e) { log.error( "Failed to nack messages(topic={}, partition={}, priority={}, groupId={}, isResend={}, msgIdToRemainingRetries={}).", tpp.getTopic(), tpp.getPartition(), tpp.isPriority(), groupId, isResend, failRange.getOffsets(), e); } } if (doneRange != null) { if (log.isDebugEnabled()) { log.debug("Ack messages(topic={}, partition={}, priority={}, groupId={}, isResend={}, endOffset={}).", tpp.getTopic(), tpp.getPartition(), tpp.isPriority(), groupId, isResend, doneRange.getEnd()); } try { doAck(isResend, pg.getKey(), groupId, doneRange.getEnd()); } catch (Exception e) { log.error("Ack messages(topic={}, partition={}, priority={}, groupId={}, isResend={}, endOffset={}).", tpp.getTopic(), tpp.getPartition(), tpp.isPriority(), groupId, isResend, doneRange.getEnd(), e); } } } } private class AckTask implements Runnable { private List<Operation> m_todos = new ArrayList<Operation>(); @Override public void run() { try { handleOperations(); checkHolders(); } catch (Exception e) { log.error("Exception occurred while executing ack task.", e); } finally { if (!m_stopped.get()) { m_ackOpExecutor .schedule(m_ackTask, m_config.getMessageQueueCheckIntervalMillis(), TimeUnit.MILLISECONDS); } } } @SuppressWarnings("unchecked") private void handleOperations() { try { if (m_todos.isEmpty()) { m_opQueue.drainTo(m_todos, m_config.getAckOpHandlingBatchSize()); } if (m_todos.isEmpty()) { return; } for (Operation op : m_todos) { AckHolder<MessageMeta> holder = findHolder(op); switch (op.getType()) { case ACK: holder.acked((Long) op.getData(), true); break; case NACK: holder.acked((Long) op.getData(), false); break; case DELIVERED: holder.delivered((List<Pair<Long, MessageMeta>>) op.getData(), op.getCreateTime()); break; default: break; } } m_todos.clear(); } catch (Exception e) { log.error("Exception occurred while handling operations.", e); } } private AckHolder<MessageMeta> findHolder(Operation op) { Map<Pair<Boolean, String>, AckHolder<MessageMeta>> holders = findHolders(op); AckHolder<MessageMeta> holder = null; holder = holders.get(op.getKey()); if (holder == null) { int timeout = m_metaService.getAckTimeoutSecondsByTopicAndConsumerGroup(m_topic, op.getKey().getValue()) * 1000; holder = isForwordOnly(op) ? new ForwardOnlyAckHolder<MessageMeta>() : new DefaultAckHolder<MessageMeta>( timeout); holders.put(op.getKey(), holder); } return holder; } private Map<Pair<Boolean, String>, AckHolder<MessageMeta>> findHolders(Operation op) { return isForwordOnly(op) ? m_forwardOnlyAckHolders : (op.isResend() ? m_resendAckHolders : m_ackHolders); } private boolean isForwordOnly(Operation op) { return AckHolderType.FORWARD_ONLY == op.getAckHolderType(); } } @Override public boolean offer(Operation operation) { return m_opQueue.offer(operation); } protected abstract void doStop(); protected abstract MessageQueueDumper createDumper(Lease lease); protected abstract MessageQueueCursor create(String groupId, Lease lease); protected abstract void doNack(boolean resend, boolean isPriority, String groupId, List<Pair<Long, MessageMeta>> msgId2Metas); protected abstract void doAck(boolean resend, boolean isPriority, String groupId, long msgSeq); }
package org.jboss.as.jpa.hibernate4; import java.util.Properties; import org.hibernate.cfg.AvailableSettings; import org.jboss.as.clustering.infinispan.subsystem.CacheConfigurationService; import org.jboss.as.jpa.hibernate4.infinispan.InfinispanRegionFactory; import org.jboss.as.jpa.hibernate4.infinispan.SharedInfinispanRegionFactory; import org.jboss.as.jpa.spi.PersistenceUnitMetadata; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; /** * Second level cache setup. * * @author Scott Marlow */ public class HibernateSecondLevelCache { private static final String DEFAULT_REGION_FACTORY = SharedInfinispanRegionFactory.class.getName(); public static void addSecondLevelCacheDependencies(ServiceRegistry registry, ServiceTarget target, ServiceBuilder<?> builder, PersistenceUnitMetadata pu) { Properties properties = pu.getProperties(); if (properties.getProperty(AvailableSettings.CACHE_REGION_PREFIX) == null) { // cache entries for this PU will be identified by scoped pu name + Entity class name properties.put(AvailableSettings.CACHE_REGION_PREFIX, pu.getScopedPersistenceUnitName()); } String regionFactory = properties.getProperty(AvailableSettings.CACHE_REGION_FACTORY); if (regionFactory == null) { regionFactory = DEFAULT_REGION_FACTORY; properties.setProperty(AvailableSettings.CACHE_REGION_FACTORY, regionFactory); } if (regionFactory.equals(DEFAULT_REGION_FACTORY)) { // Set infinispan defaults String container = properties.getProperty(InfinispanRegionFactory.CACHE_CONTAINER); if (container == null) { container = InfinispanRegionFactory.DEFAULT_CACHE_CONTAINER; properties.setProperty(InfinispanRegionFactory.CACHE_CONTAINER, container); } String entity = properties.getProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, InfinispanRegionFactory.DEF_ENTITY_RESOURCE); String collection = properties.getProperty(InfinispanRegionFactory.COLLECTION_CACHE_RESOURCE_PROP, InfinispanRegionFactory.DEF_ENTITY_RESOURCE); String query = properties.getProperty(InfinispanRegionFactory.QUERY_CACHE_RESOURCE_PROP, InfinispanRegionFactory.DEF_QUERY_RESOURCE); String timestamps = properties.getProperty(InfinispanRegionFactory.TIMESTAMPS_CACHE_RESOURCE_PROP, InfinispanRegionFactory.DEF_QUERY_RESOURCE); builder.addDependency(CacheConfigurationService.getServiceName(container, entity)); builder.addDependency(CacheConfigurationService.getServiceName(container, collection)); builder.addDependency(CacheConfigurationService.getServiceName(container, timestamps)); builder.addDependency(CacheConfigurationService.getServiceName(container, query)); } } }
package io.hops.hopsworks.common.dataset; import javax.xml.bind.annotation.XmlRootElement; /** * Provides information on the previewed file in Datasets. * <p> */ @XmlRootElement public class FilePreviewDTO { private String type; private String content; private String extension; public FilePreviewDTO() { } public FilePreviewDTO(String type, String extension, String content) { this.type = type; this.extension = extension; this.content = content; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } @Override /** * Formats a JSON to be displayed by the browser. */ public String toString() { return "{\"filePreviewDTO\":[{\"type\":\"" + type + "\", \"extension\":\"" + extension + "\", \"content\":\"" + content.replace("\\", "\\\\'"). replace("\"", "\\\"").replace("\n", "\\n"). replace("\r", "\\r").replace("\t", "\\t"). replaceAll("[\\p{Cntrl}]", "") + "\"}]}"; } }
package com.showcast.hvscroll.draw; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import com.showcast.hvscroll.entity.AbsCellEntity; import com.showcast.hvscroll.entity.AbsRowEntity; import com.showcast.hvscroll.entity.AbsTableEntity; import com.showcast.hvscroll.params.GlobalParams; import com.showcast.hvscroll.params.TableParams; import com.showcast.hvscroll.touchhelper.MoveAndScaleTouchHelper; import com.showcast.hvscroll.touchhelper.TouchEventHelper; public class HorizontalVerticalScrollDraw implements TouchEventHelper.OnToucheEventListener, MoveAndScaleTouchHelper.IMoveEvent, MoveAndScaleTouchHelper.IScaleEvent, MoveAndScaleTouchHelper.INotificationEvent { private TouchEventHelper mTouchHelper; private MoveAndScaleTouchHelper mMsActionHelper; private View mDrawView; private AbsTableEntity mTable; private BaseTableDrawStyle mRowStyle; private BaseTableDrawStyle mCellStyle; private TableParams mTableParams; private GlobalParams mGlobalParams; //test fields private int mMenuHeight = 80; private int mMenuWidth = 200; private int mStartDrawX = 0; private int mStartDrawY = 0; //the direction for scrolling private boolean mIsScrollInHorizontal = true; //the max width of canvas draws private float mCanvasDrawWidth = 0; //the max height of canvas draws private float mCanvasDrawHeight = 0; private RectF mRecycleRectf; private Rect mRecycleRect; private Point mViewParams; private Point mRecyclePoint; private Paint mPaint; public HorizontalVerticalScrollDraw(@NonNull View drawView) { this(); this.setDrawView(drawView); } private HorizontalVerticalScrollDraw() { mTouchHelper = new TouchEventHelper(this); mMsActionHelper = new MoveAndScaleTouchHelper(this, this); mMsActionHelper.setNoticationEvent(this); mRecycleRectf = new RectF(); mRecycleRect = new Rect(); mRecyclePoint = new Point(); mPaint = new Paint(); } public void setDrawView(@NonNull View drawView) { if (mDrawView != null) { mDrawView.setOnTouchListener(null); } mDrawView = drawView; mDrawView.setOnTouchListener(mTouchHelper); } public void setTable(AbsTableEntity table) { mTable = table; } public void setCellDrawStyle(BaseTableDrawStyle style) { mCellStyle = style; } public void setParams(GlobalParams global, TableParams table) { mGlobalParams = global; mTableParams = table; } public void drawCanvas(Canvas canvas) { if (mTable == null) { return; } int offsetX = (int) mMsActionHelper.getDrawOffsetX(); int offsetY = (int) mMsActionHelper.getDrawOffsetY(); int canvasStartDrawY = 0; int canvasStartDrawX = 0; this.beforeDraw(canvas, offsetX, offsetY); canvasStartDrawY = this.drawRowMenu(mTable, false, mMenuWidth, mMenuHeight, 0, 0, offsetX, 0, mPaint, canvas); canvasStartDrawX = this.drawColumnMenu(mTable, true, mMenuWidth, mMenuHeight, 0, 0, offsetX, offsetY, mPaint, canvas); canvasStartDrawX = this.drawFrozenColumn(mTable, 0, canvasStartDrawY, offsetX, offsetY, 0, mMenuWidth, mMenuHeight, mPaint, canvas); this.drawCellInTable(mTable, canvasStartDrawX, canvasStartDrawY, offsetX, offsetY, mPaint, canvas); } private void beforeDraw(Canvas canvas, int offsetX, int offsetY) { if (mViewParams == null) { mViewParams = this.getViewWidthHeight(mDrawView, mViewParams); } canvas.drawColor(mGlobalParams.getCanvasBgColor()); // //translate the original point(0,0) // canvas.translate(offsetX, offsetY); } private void finishDraw() { } //draw the row menu, menu will fix on the top ,for now //TODO:set textSize/textColor/bgColor etc. private int drawRowMenu(AbsTableEntity table, boolean isFrozen, int menuWidth, int menuHeight, int startDrawX, int startDrawY, int offsetX, int offsetY, Paint paint, Canvas canvas) { float textSize = 60f; paint.setTextSize(textSize); int left, top, right, bottom; float textDrawX = 0; float textDrawY = 0; if (table != null) { //ignore offset values if menu is frozen //so that menu will not be moved if (isFrozen) { offsetX = 0; offsetY = 0; } for (int i = 0; i < table.getMenuCount(0); i++) { //get menu AbsCellEntity menu = table.getRowMenu(i); if (menu != null && menu.isNeedToDraw(AbsTableEntity.MENU_INDEX_ROW, i)) { //calculate each menu cell left = menuWidth * i + offsetX + startDrawX; right = left + menuWidth; top = offsetY + startDrawY; bottom = top + menuHeight; mRecycleRect.set(left, top, right, bottom); //if the draw area cannot be seen,ignore it if (isDrawRectCanSeen(mRecycleRect)) { textDrawX = mRecycleRect.left; textDrawY = mRecycleRect.centerY() + textSize * 2 / 3; this.drawCell(menu, mRecycleRect, textDrawX, textDrawY, paint, canvas); } } } //save row menu max draw width this.updateCanvasDrawWidth(mRecycleRect.right - offsetX); this.updateCanvasDrawHeight(mRecycleRect.bottom - offsetY); } return menuHeight; } private int drawColumnMenu(AbsTableEntity table, boolean isFrozen, int menuWidth, int menuHeight, int startDrawX, int startDrawY, int offsetX, int offsetY, Paint paint, Canvas canvas) { float textSize = 60f; paint.setTextSize(textSize); int left, top, right, bottom; float textDrawX = 0; float textDrawY = 0; if (table != null) { //ignore offset values if menu is frozen //so that menu will not be moved if (isFrozen) { offsetX = 0; offsetY = 0; } for (int i = 0; i < table.getMenuCount(1); i++) { //get menu AbsCellEntity menu = table.getRowMenu(i); if (menu != null && menu.isNeedToDraw(i, AbsTableEntity.MENU_INDEX_COLUMN)) { //calculate each menu cell left = offsetX + startDrawX; right = left + menuWidth; top = offsetY + startDrawY + menuHeight * i; bottom = top + menuHeight; mRecycleRect.set(left, top, right, bottom); //if the draw area cannot be seen,ignore it if (isDrawRectCanSeen(mRecycleRect)) { textDrawX = mRecycleRect.left; textDrawY = mRecycleRect.centerY() + textSize * 2 / 3; this.drawCell(menu, mRecycleRect, textDrawX, textDrawY, paint, canvas); } } } //save row menu max draw width this.updateCanvasDrawWidth(mRecycleRect.right - offsetX); this.updateCanvasDrawHeight(mRecycleRect.bottom - offsetY); } return menuWidth; } //draw all cells on the table private void drawCellInTable(AbsTableEntity table, int startDrawX, int startDrawY, int canvasOffsetX, int canvasOffsetY, Paint paint, Canvas canvas) { if (table != null) { int rowCount = table.getRowCount(); canvas.clipRect(startDrawX, startDrawY, mViewParams.x, mViewParams.y); for (int i = 0; i < rowCount; i++) { this.drawCellInRow(table.getRow(i), i, mMenuWidth, mMenuHeight, startDrawX, startDrawY, canvasOffsetX, canvasOffsetY, paint, canvas); startDrawY += mMenuHeight; } } } //draw the cells of every row //TODO:need to update textSize/textColor/bgColor etc. private void drawCellInRow(AbsRowEntity row, int rowIndex, int cellWidth, int cellHeight, int startDrawX, int startDrawY, int canvasOffsetX, int canvasOffsetY, Paint paint, Canvas canvas) { if (row != null) { int left, top, right, bottom, columnCount; float textDrawX, textDrawY, textSize; textSize = 60; paint.setTextSize(textSize); columnCount = row.getColumnCount(); for (int i = 0; i < columnCount; i++) { AbsCellEntity cell = row.getCell(i); //try draw cell when cell exists or need to draw if (cell == null || cell.isNeedToDraw(rowIndex, i)) { //recyclePoint save the real cell width and height this.calculateCellWidthAndHeight(mRecyclePoint, cell, cellWidth, cellHeight); left = startDrawX + mRecyclePoint.x * i + canvasOffsetX; right = left + mRecyclePoint.x; top = startDrawY + canvasOffsetY; bottom = top + mRecyclePoint.y; mRecycleRect.set(left, top, right, bottom); //draw cell when the cell can be seen if (isDrawRectCanSeen(mRecycleRect)) { textDrawX = mRecycleRect.left; textDrawY = mRecycleRect.centerY() + textSize * 2 / 3; this.drawCell(cell, mRecycleRect, textDrawX, textDrawY, paint, canvas); } } } //save each row max draw width this.updateCanvasDrawWidth(mRecycleRect.right - canvasOffsetX); this.updateCanvasDrawHeight(mRecycleRect.bottom - canvasOffsetY); } } //draw frozen column //TODO:set textSize/textColor etc. private int drawFrozenColumn(AbsTableEntity table, int startDrawX, int startDrawY, int offsetX, int offsetY, int whichColumn, int cellWidth, int cellHeight, Paint paint, Canvas canvas) { int maxDrawWidth = 0; canvas.clipRect(startDrawX, startDrawY, mViewParams.x, mViewParams.y); //check if the table exists if (table != null && whichColumn >= 0) { int left, top, right, bottom, rowCount; float textDrawX, textDrawY, textSize; rowCount = table.getRowCount(); boolean isDraw = false; textSize = 60; paint.setTextSize(textSize); //traverse all row to get the which column for (int i = 0; i < rowCount; i++) { AbsRowEntity row = table.getRow(i); if (row != null && whichColumn < row.getColumnCount()) { AbsCellEntity cell = row.getCell(whichColumn); if (cell != null && cell.isNeedToDraw(i, whichColumn)) { this.calculateCellWidthAndHeight(mRecyclePoint, cell, cellWidth, cellHeight); left = startDrawX; right = left + mRecyclePoint.x; top = startDrawY + offsetY; bottom = top + mRecyclePoint.y; mRecycleRect.set(left, top, right, bottom); textDrawX = mRecycleRect.left; textDrawY = mRecycleRect.centerY() + textSize * 2 / 3; this.drawCell(cell, mRecycleRect, textDrawX, textDrawY, paint, canvas); //record the max width of this row maxDrawWidth = maxDrawWidth < mRecyclePoint.x ? mRecyclePoint.x : maxDrawWidth; isDraw = true; } } //move to next row startDrawY += isDraw ? mRecyclePoint.y : cellHeight; isDraw = false; } this.updateCanvasDrawWidth(mRecycleRect.right - offsetX); this.updateCanvasDrawHeight(mRecycleRect.bottom - offsetY); } return maxDrawWidth; } private void drawFrozenRow() { } private void drawMenu(AbsCellEntity menu, RectF drawRect, Paint paint, Canvas canvas) { } private void drawCell(AbsCellEntity cell, Rect drawRect, float textDrawX, float textDrawY, Paint paint, Canvas canvas) { //draw stroke paint.setColor(Color.LTGRAY); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); canvas.drawRect(drawRect, paint); //draw background paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.FILL); canvas.drawRect(drawRect, paint); //draw text paint.setColor(Color.WHITE); this.drawAutofitWidthText(drawRect.width(), cell.getText(), textDrawX, textDrawY, paint, canvas); } //TODO: calculate cell real width and height,if the cell span other cell (left/right or top/bottom) private void calculateCellWidthAndHeight(Point outPoint, AbsCellEntity cell, int defaultCellWidth, int defaultCellHeight) { int width = cell.getDrawWidth(); int height = cell.getDrawHeight(); width = width <= 0 ? defaultCellWidth * cell.getSpanRowCount() + defaultCellWidth : width; height = height <= 0 ? defaultCellHeight * cell.getSpanColumnCount() + defaultCellHeight : height; outPoint.set(width, height); } private boolean isDrawRectCanSeen(Rect rect) { if (rect != null) { return !(rect.right < 0 || rect.left > mViewParams.x || rect.bottom < 0 || rect.top > mViewParams.y); } else { return false; } } /** * draw text to auto fit the width,when the length is too long,ellipsis will replace the unshown text * * @param charWidth the width of each char at the text,pay attention to english text is different from chinese text * @param maxDrawWidth max width for draw * @param drawText text for draw * @param drawY the bottom axis to begin to draw text * @param drawX the axis begin to draw text * @param paint the paint should set textSize/textColor already * @param canvas */ protected void drawAutofitWidthText(float charWidth, float maxDrawWidth, String drawText, float drawY, float drawX, Paint paint, Canvas canvas) { if (!TextUtils.isEmpty(drawText)) { int maxCharLength = (int) (maxDrawWidth / charWidth); if (drawText.length() > maxCharLength) { float drawLength = paint.measureText(drawText, 0, maxCharLength - 3); canvas.drawText(drawText, 0, maxCharLength - 3, drawX, drawY, paint); canvas.drawText("...", drawX + drawLength, drawY, paint); } else { canvas.drawText(drawText, drawX, drawY, paint); } } } /** * measure one char width * * @param paint * @param textSize textSize for draw * @param isChinese true if the char contains chinese,false otherwise * @return */ protected float measureCharWidth(Paint paint, int textSize, boolean isChinese) { paint.setTextSize(textSize); String ch = isChinese ? "e" : ""; return paint.measureText(ch); } /** * draw text to auto fit the width,when the length is too long,ellipsis will replace the unshown text * * @param maxDrawWidth max width for draw * @param drawText text for draw * @param drawX the bottom axis to begin to draw text * @param drawY the axis begin to draw text * @param paint the paint should set textSize/textColor already * @param canvas */ protected void drawAutofitWidthText(float maxDrawWidth, String drawText, float drawX, float drawY, Paint paint, Canvas canvas) { if (!TextUtils.isEmpty(drawText)) { //measure the text width if all char draw out float textWidth = mPaint.measureText(drawText); if (textWidth > maxDrawWidth) { //estimate max char count can be show int maxCharLength = (int) (drawText.length() * (maxDrawWidth / textWidth)); //save 3 count for ellipsis float drawLength = paint.measureText(drawText, 0, maxCharLength - 3); canvas.drawText(drawText, 0, maxCharLength - 3, drawX, drawY, paint); canvas.drawText("...", drawX + drawLength, drawY, paint); } else { canvas.drawText(drawText, drawX, drawY, paint); } } } /** * get the view width and height before draw canvas. * if get the layout params at the beginning, maybe the view haven't finished its measure and layout, * we can't get the real show area of view. * * @param view * @param outPoint point to save the params * @return */ private Point getViewWidthHeight(View view, Point outPoint) { if (view != null) { if (outPoint == null) { outPoint = new Point(); } outPoint.set(view.getWidth(), view.getHeight()); return outPoint; } else { return null; } } /** * update the canvas width,save the max value * * @param newWidth */ private void updateCanvasDrawWidth(float newWidth) { mCanvasDrawWidth = newWidth > mCanvasDrawWidth ? newWidth : mCanvasDrawWidth; } /** * update the canvas height,save the max value * * @param newHeight */ private void updateCanvasDrawHeight(float newHeight) { mCanvasDrawHeight = newHeight > mCanvasDrawHeight ? newHeight : mCanvasDrawHeight; } @Override public boolean isCanMovedOnX(PointF moveDistancePointF, PointF newOffsetPointF) { //only can move in the positive axis. //when move to a big positive axis(for example from 0 to +int), //the offset distance will be negative. // return mIsScrollInHorizontal && newOffsetX <= 0; float outOfCanvas = mCanvasDrawWidth + 50 - mViewParams.x; if (outOfCanvas > 0) { if (Math.abs(newOffsetPointF.x) > outOfCanvas) { newOffsetPointF.x = outOfCanvas * (newOffsetPointF.x > 0 ? 1 : -1); } else if (newOffsetPointF.x > 0) { newOffsetPointF.x = 0; } } return mIsScrollInHorizontal && newOffsetPointF.x <= 0 && outOfCanvas > 0; } @Override public boolean isCanMovedOnY(PointF moveDistancePointF, PointF newOffsetPointF) { //only can move in the positive axis. // return !mIsScrollInHorizontal && newOffsetY <= 0; float outOfCanvas = mCanvasDrawHeight + 50 - mViewParams.y; if (outOfCanvas > 0) { if (Math.abs(newOffsetPointF.y) > outOfCanvas) { newOffsetPointF.y = outOfCanvas * (newOffsetPointF.y > 0 ? 1 : -1); } else if (newOffsetPointF.y > 0) { newOffsetPointF.y = 0; } } return !mIsScrollInHorizontal && newOffsetPointF.y <= 0 && outOfCanvas > 0; } @Override public void onMove(int suggestEventAction) { mDrawView.invalidate(); } @Override public void onMoveFail(int suggetEventAction) { } @Override public boolean isCanScale(float newScaleRate) { return false; } @Override public void setScaleRate(float newScaleRate, boolean isNeedStoreValue) { } @Override public void onScale(int suggestEventAction) { mDrawView.invalidate(); } @Override public void onScaleFail(int suggetEventAction) { } @Override public void startMove(float mouseDownX, float mouseDownY) { if (mouseDownX < mMenuWidth) { mIsScrollInHorizontal = false; } else { mIsScrollInHorizontal = true; } } @Override public void finishedMove(boolean hasBeenMoved) { mIsScrollInHorizontal = false; } @Override public void startScale(float newScaleRate) { } @Override public void finishedScale(boolean hasBeenScaled) { } @Override public void onSingleTouchEventHandle(MotionEvent event, int extraMotionEvent) { mMsActionHelper.singleTouchEvent(event, extraMotionEvent); } @Override public void onMultiTouchEventHandle(MotionEvent event, int extraMotionEvent) { mMsActionHelper.multiTouchEvent(event, extraMotionEvent); } @Override public void onSingleClickByTime(MotionEvent event) { } @Override public void onSingleClickByDistance(MotionEvent event) { } @Override public void onDoubleClickByTime() { } }
package org.intermine.web.logic.widget.config; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.intermine.api.profile.InterMineBag; import org.intermine.objectstore.ObjectStore; import org.intermine.web.logic.widget.GraphWidget; /** * Configuration object describing details of a graph displayer * * @author Xavier Watkins */ public class GraphWidgetConfig extends WidgetConfig { private static final Logger LOG = Logger.getLogger(GraphWidgetConfig.class); private String domainLabel; private String rangeLabel; private String graphType; private String bagType; private String bagPath; private String categoryPath; private String seriesPath; private String seriesValues; private String seriesLabels; private HttpSession session; private String editable; public static final String ACTUAL_EXPECTED_CRITERIA = "ActualExpectedCriteria"; /** * Get the session * @return the session */ public HttpSession getSession() { return session; } /** * @param session the session to set */ public void setSession(HttpSession session) { this.session = session; } /** * Get the domainLabel * @return the domainLabel */ public String getDomainLabel() { return domainLabel; } /** * Set the value of domainLabel * @param domainLabel a String */ public void setDomainLabel(String domainLabel) { this.domainLabel = domainLabel; } /** * Get the value of rangeLabel * @return the rangeLabel */ public String getRangeLabel() { return rangeLabel; } /** * Set the value of rangeLabel * @param rangeLabel a String */ public void setRangeLabel(String rangeLabel) { this.rangeLabel = rangeLabel; } /** * @param graphType type of graph, e.g. BarChart, StackedBarChart */ public void setGraphType(String graphType) { this.graphType = graphType; } /** * Get the type of this graph, e.g. BarChart, StackedBarChart * @return the type of this graph */ public String getGraphType() { return graphType; } /** * Return an XML String of this Type object * @return a String version of this WebConfig object */ public String toString() { return "< title=\"" + getTitle() + " domainLabel=\"" + domainLabel + " rangeLabel=\"" + rangeLabel + " />"; } public String getBagType() { return bagType; } public void setBagType(String bagType) { this.bagType = bagType; } public String getBagPath() { return bagPath; } public void setBagPath(String bagPath) { this.bagPath = bagPath; } public boolean isBagPathSet() { if (bagPath != null && !"".equals(bagPath)) { return true; } return false; } public String getCategoryPath() { return categoryPath; } public void setCategoryPath(String categoryPath) { this.categoryPath = categoryPath; } public String getSeriesPath() { return seriesPath; } public void setSeriesPath(String seriesPath) { this.seriesPath = seriesPath; } public boolean isActualExpectedCriteria() { if (this.seriesPath.contains(ACTUAL_EXPECTED_CRITERIA)) { return true; } return false; } public String getSeriesValues() { return seriesValues; } public void setSeriesValues(String seriesValues) { this.seriesValues = seriesValues; } public String getSeriesLabels() { return seriesLabels; } public void setSeriesLabels(String seriesLabels) { this.seriesLabels = seriesLabels; } /** * @return the editable attribute */ public String geteditable() { return editable; } /** * @param editable editable */ public void seteditable(String editable) { this.editable = editable; } /** * {@inheritDoc} */ public Map<String, Collection<String>> getExtraAttributes(InterMineBag imBag, ObjectStore os) throws Exception { Collection<String> extraAttributes = new ArrayList<String>(); Map<String, Collection<String>> returnMap = new HashMap<String, Collection<String>>(); /* if (extraAttributeClass != null && extraAttributeClass.length() > 0) { try { Class<?> clazz = TypeUtil.instantiate(extraAttributeClass); Method extraAttributeMethod = clazz.getMethod("getExtraAttributes", new Class[] {ObjectStore.class, InterMineBag.class}); // invoking a static method the first argument is ignored extraAttributes = (Collection<String>) extraAttributeMethod.invoke(null, os, imBag); } catch (Exception e) { LOG.error(e.getMessage()); return returnMap; } } if (extraAttributes.size() > 0) { returnMap.put("Organism", extraAttributes); } if (editable != null && "true".equals(editable)) { returnMap.put("Editable", new ArrayList<String>()); }*/ return returnMap; } /** * {@inheritDoc} */ public GraphWidget getWidget(InterMineBag imBag, ObjectStore os, List<String> selectedExtraAttribute) { return new GraphWidget(this, imBag, os, selectedExtraAttribute.get(0)); } }
package ru.stqa.training.selenium.pageObject.Tests; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; public class TestBase { protected WebDriver driver; protected WebDriverWait wait; DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); public void init(String browserName) { if (browserName.equals("Chrome")) { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("start-maximized"); desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); driver = new ChromeDriver(desiredCapabilities); } else if (browserName.equals("InternetExplorer")) { driver = new InternetExplorerDriver(); driver.manage().window().maximize(); } else if (browserName.equals("Firefox Old Scheme Caps")) { desiredCapabilities.setCapability(FirefoxDriver.MARIONETTE, false); driver = new FirefoxDriver(new FirefoxBinary(new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")), new FirefoxProfile(), desiredCapabilities); driver.manage().window().maximize(); } else if (browserName.equals("Firefox Old Scheme Options")) { FirefoxOptions options = new FirefoxOptions(); options.setLegacy(false); options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); driver = new FirefoxDriver(options); driver.manage().window().maximize(); } else if (browserName.equals("Firefox New Scheme")) { driver = new FirefoxDriver(); driver.manage().window().maximize(); } } @Before public void start() { { init("Chrome"); // init("InternetExplorer"); // init("Firefox Old Scheme Caps"); // init("Firefox Old Scheme Options"); // init("Firefox New Scheme"); wait = new WebDriverWait(driver, 10); } } @After public void quit() { // driver.quit(); } }
package com.java110.common.constant; public final class PrivilegeCodeConstant { private PrivilegeCodeConstant() { } public static final String PRIVILEGE_ENTER_COMMUNITY = "500201904008"; public static final String PRIVILEGE_FLOOR = "500201904011"; public static final String PRIVILEGE_UNIT = "500201904012"; public static final String PRIVILEGE_ROOM = "500201904006"; public static final String PRIVILEGE_SELL_ROOM = "500201904014"; public static final String PRIVILEGE_OWNER_ROOM = "500201904015"; public static final String PRIVILEGE_PROPERTY_CONFIG_FEE = "500201904016"; public static final String PRIVILEGE_PROPERTY_FEE = "500201904004"; public static final String PRIVILEGE_PARKING_SPACE = "500201906017"; public static final String PRIVILEGE_PARKING_SPACE_FOR_OWNER = "500201906020"; public static final String PRIVILEGE_CAR = "500201906019"; public static final String PRIVILEGE_PARKING_SPACE_CONFIG_FEE = "500201904021"; // demo public static final String PRIVILEGE_DEMO = "500201906023"; public static final String AGENT_HAS_LIST_COMMUNITY = "500201906025"; public static final String HAS_LIST_NOTICE = "500201904009"; public static final String AGENT_HAS_LIST_APP = "500201906026"; public static final String AGENT_HAS_LIST_SERVICE = "500201906027"; public static final String AGENT_HAS_LIST_MAPPING = "500201906029"; public static final String AGENT_HAS_LIST_SERVICEREGISTER = "500201907032"; public static final String HAS_LIST_CACHE = "500201907032"; public static final String LIST_SERVICEIMPL = "500201906028"; public static final String MENU = "500201908035"; public static final String BASE_PRIVILEGE = "500201908036"; }
package org.akvo.flow.servlet; import java.io.IOException; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import com.google.appengine.api.utils.SystemProperty; import org.akvo.flow.dao.ReportDao; import org.akvo.flow.domain.persistent.Report; import org.akvo.flow.rest.dto.ReportTaskRequest; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.waterforpeople.mapping.app.web.dto.TaskRequest; import com.gallatinsystems.common.Constants; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.user.dao.UserDao; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; public class ReportServlet extends AbstractRestApiServlet { private static final Logger log = Logger.getLogger(ReportServlet.class.getName()); private static final long serialVersionUID = -9064136799930675167L; private static final String SERVLET_URL = "/app_worker/reportservlet"; private static final Long MAX_ATTEMPTS = 5L; //Give up after this many attempts to start engine private ReportDao rDao; private UserDao uDao; class ReportOptions implements Serializable { /** * Used to send the start command to the report engine */ private static final long serialVersionUID = 1L; public String exportMode; public Long reportId; public Long questionId; //only for GeoJSON public String from; public String to; public Boolean lastCollection; public String imgPrefix; public String uploadUrl; public String flowServices; public String appId; public String email; } class ReportCriteria implements Serializable { /** * Used to send the start command to the report engine */ private static final long serialVersionUID = 1L; public ReportOptions opts; public String exportType; public String appId; public String surveyId; public String baseURL; } public ReportServlet() { rDao = new ReportDao(); uDao = new UserDao(); } @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new ReportTaskRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { ReportTaskRequest stReq = (ReportTaskRequest) req; String action = stReq.getAction(); Long id = stReq.getId(); log.fine("action: " + action + " id: " + id + "attempt:" + stReq.getAttempt()); Report r = rDao.getByKey(id); switch (action) { case ReportTaskRequest.START_ACTION: if (r != null) { if (!r.getState().equals(Report.QUEUED)) { //wrong state log.warning("Cannot start report " + id + " that is " + r.getState()); //TODO do anything else? return null; } log.fine(" ====Starting"); //hit the services server int sts = 0; try { sts = startReportEngine(stReq.getBaseUrl(), r); log.fine(" got " + sts); if (sts == 200) { //Success, we are done! return null; } else if ((sts / 100) == 4) { //4xx: you messed up //permanent error, fail this report r.setState(Report.FINISHED_ERROR); r.setMessage("Unexpected result when starting report " + id + " : " + sts); rDao.save(r); } else { //if we get a transient error, re-queue requeueStart(stReq, r, sts); } } catch (MalformedURLException e) { log.log(Level.SEVERE, "Bad URL"); } catch (IOException e) { log.warning("====IOerror: " + e); //call it a transient error, re-queue requeueStart(stReq, r, sts); } } break; case ReportTaskRequest.PROGRESS_ACTION: if (r != null) { if (!r.getState().equals(Report.QUEUED) && !r.getState().equals(Report.IN_PROGRESS)) { //wrong state log.warning("Cannot set progress on report " + id + " that is " + r.getState()); return null; } r.setState(stReq.getState()); r.setMessage(stReq.getMessage()); r.setFilename(stReq.getFilename()); rDao.save(r); } break; default: log.warning("Unknown action."); break; } return null; } public static void queueStart(String baseUrl, Report r) { Queue queue = QueueFactory.getDefaultQueue(); TaskOptions options = getTaskOptions(baseUrl, 1L, r); //First time log.fine("Forking to task with options: " + options.toString()); queue.add(options); } private static TaskOptions getTaskOptions(String baseUrl, Long attempt, Report r) { return TaskOptions.Builder.withUrl(SERVLET_URL) .param(TaskRequest.ACTION_PARAM, ReportTaskRequest.START_ACTION) .param(ReportTaskRequest.ID_PARAM, Long.toString(r.getKey().getId())) .param(ReportTaskRequest.BASE_URL_PARAM, baseUrl) .param(ReportTaskRequest.ATTEMPT_PARAM, Long.toString(attempt)); } private void requeueStart(ReportTaskRequest req, Report r, int err) { //give up if this has been going on too long if (req.getAttempt() == null || req.getAttempt() >= MAX_ATTEMPTS) { log.warning("Abandoning START task after attempt " + req.getAttempt()); r.setState(Report.FINISHED_ERROR); r.setMessage("Could not start report generation after " + MAX_ATTEMPTS + " attempts: " + err); rDao.save(r); } else { log.warning("Requeuing START task"); Queue queue = QueueFactory.getDefaultQueue(); queue.add(getTaskOptions(req.getBaseUrl(), req.getAttempt() + 1, r)); } } private int startReportEngine(String baseUrl, Report r) throws JsonGenerationException, JsonMappingException, IOException { //look up user final String email = uDao.getByKey(r.getUser()).getEmailAddress(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //Gleaned from export-reports-views.js ReportCriteria criteria = new ReportCriteria(); criteria.opts = new ReportOptions(); criteria.appId = SystemProperty.applicationId.get(); criteria.surveyId = r.getFormId().toString(); criteria.exportType = r.getReportType(); criteria.baseURL = baseUrl; criteria.opts.appId = SystemProperty.applicationId.get(); criteria.opts.exportMode = r.getReportType(); criteria.opts.reportId = r.getKey().getId(); if (r.getStartDate() != null) { criteria.opts.from = sdf.format(r.getStartDate()); } if (r.getEndDate() != null) { criteria.opts.to = sdf.format(r.getEndDate()); } criteria.opts.lastCollection = r.getLastCollectionOnly(); criteria.opts.questionId = r.getQuestionId(); criteria.opts.imgPrefix = PropertyUtil.getProperty("photo_url_root"); criteria.opts.uploadUrl = PropertyUtil.getProperty("surveyuploadurl"); criteria.opts.flowServices = PropertyUtil.getProperty("flowServices"); criteria.opts.email = email; ObjectMapper objectMapper = new ObjectMapper(); String crit = java.net.URLEncoder.encode(objectMapper.writeValueAsString(criteria), "UTF-8"); URL url = new URL(PropertyUtil.getProperty("flowServices") + "/generate?criteria=" + crit); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); log.log(Level.FINE, "Preparing to GET " + url); return con.getResponseCode(); } @Override protected void writeOkResponse(RestResponse resp) throws Exception { // TODO Auto-generated method stub } }
package com.jenjinstudios.core.event; import com.jenjinstudios.core.io.Message; /** * Notified when a MessageInputStream receives a message. * * @author Caleb Brinkman */ public interface MessageReceivedListener extends EventListener { /** * Called when a message has been received. * * @param message The message that was received. */ public void onMessageReceived(Message message); }
package com.github.fhirschmann.clozegen.lib.util; import com.google.common.collect.Lists; import java.lang.reflect.Constructor; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Fabian Hirschmann <fabian@hirschm.net> */ public class CollectionUtilsTest { private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5); @Test public void testAdjacentTo() { assertEquals( Lists.newArrayList(2, 3, 4), CollectionUtils.<Integer>getAdjacentTo(list, 2, 1)); } @Test public void testAdjacentToUpperBound() { assertEquals( Lists.newArrayList(4, 5), CollectionUtils.<Integer>getAdjacentTo(list, 4, 1)); } @Test public void testAdjacentToLowerBound() { assertEquals( Lists.newArrayList(1, 2), CollectionUtils.<Integer>getAdjacentTo(list, 0, 1)); } @Test public void testListAsSetEquals() { assertTrue(CollectionUtils.listAsSetEquals( Lists.newArrayList("foo", "foo", "bar"), Lists.newArrayList("bar", "foo"))); } @Test public void testNullPaddingLeft() { assertEquals( Lists.newArrayList(null, 1, 2), CollectionUtils.<Integer>getNullPaddedAdjacentTo(list, 0, 1)); } @Test public void testNullPaddingRight() { assertEquals( Lists.newArrayList(4, 5, null), CollectionUtils.<Integer>getNullPaddedAdjacentTo(list, 4, 1)); } @Test public void testNullPaddingRight3() { assertEquals( Lists.newArrayList(2, 3, 4, 5, null, null, null), CollectionUtils.<Integer>getNullPaddedAdjacentTo(list, 4, 3)); } /** * Hack to exclude the private constructor from code coverage metrics. */ @Test public void testPrivateConstructor() throws Exception { Constructor<?>[] cons = CollectionUtils.class.getDeclaredConstructors(); cons[0].setAccessible(true); cons[0].newInstance((Object[]) null); } }
package com.nononsenseapps.filepicker; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.util.SortedList; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import static com.nononsenseapps.filepicker.Utils.appendPath; /** * A fragment representing a list of Files. * <p/> * <p/> * Activities containing this fragment MUST implement the {@link * OnFilePickedListener} * interface. */ public abstract class AbstractFilePickerFragment<T> extends Fragment implements LoaderManager.LoaderCallbacks<SortedList<T>>, NewItemFragment.OnNewFolderListener, LogicHandler<T> { // The different preset modes of operation. This impacts the behaviour // and possible actions in the UI. public static final int MODE_FILE = 0; public static final int MODE_DIR = 1; public static final int MODE_FILE_AND_DIR = 2; public static final int MODE_NEW_FILE = 3; // Where to display on open. public static final String KEY_START_PATH = "KEY_START_PATH"; // See MODE_XXX constants above for possible values public static final String KEY_MODE = "KEY_MODE"; // If it should be possible to create directories. public static final String KEY_ALLOW_DIR_CREATE = "KEY_ALLOW_DIR_CREATE"; // Allow multiple items to be selected. public static final String KEY_ALLOW_MULTIPLE = "KEY_ALLOW_MULTIPLE"; // Allow an existing file to be selected under MODE_NEW_FILE public static final String KEY_ALLOW_EXISTING_FILE = "KEY_ALLOW_EXISTING_FILE"; // If file can be selected by clicking only and checkboxes are not visible public static final String KEY_SINGLE_CLICK = "KEY_SINGLE_CLICK"; // Used for saving state. protected static final String KEY_CURRENT_PATH = "KEY_CURRENT_PATH"; protected final HashSet<T> mCheckedItems; protected final HashSet<CheckableViewHolder> mCheckedVisibleViewHolders; protected int mode = MODE_FILE; protected T mCurrentPath = null; protected boolean allowCreateDir = false; protected boolean allowMultiple = false; protected boolean allowExistingFile = true; protected boolean singleClick = false; protected OnFilePickedListener mListener; protected FileItemAdapter<T> mAdapter = null; protected TextView mCurrentDirView; protected EditText mEditTextFileName; protected RecyclerView recyclerView; protected LinearLayoutManager layoutManager; protected SortedList<T> mFiles = null; protected Toast mToast = null; // Keep track if we are currently loading a directory, in case it takes a long time protected boolean isLoading = false; protected View mNewFileButtonContainer = null; protected View mRegularButtonContainer = null; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public AbstractFilePickerFragment() { mCheckedItems = new HashSet<>(); mCheckedVisibleViewHolders = new HashSet<>(); // Retain this fragment across configuration changes, to allow // asynctasks and such to be used with ease. setRetainInstance(true); } protected FileItemAdapter<T> getAdapter() { return mAdapter; } protected FileItemAdapter<T> getDummyAdapter() { return new FileItemAdapter<>(this); } /** * Set before making the fragment visible. This method will re-use the existing * arguments bundle in the fragment if it exists so extra arguments will not * be overwritten. This allows you to set any extra arguments in the fragment * constructor if you wish. * <p/> * The key/value-pairs listed below will be overwritten however. * * @param startPath path to directory the picker will show upon start * @param mode what is allowed to be selected (dirs, files, both) * @param allowMultiple selecting a single item or several? * @param allowDirCreate can new directories be created? * @param allowExistingFile if selecting a "new" file, can existing files be chosen * @param singleClick selecting an item does not require a press on OK */ public void setArgs(@Nullable final String startPath, final int mode, final boolean allowMultiple, final boolean allowDirCreate, final boolean allowExistingFile, final boolean singleClick) { // Validate some assumptions so users don't get surprised (or get surprised early) if (mode == MODE_NEW_FILE && allowMultiple) { throw new IllegalArgumentException( "MODE_NEW_FILE does not support 'allowMultiple'"); } // Single click only makes sense if we are not selecting multiple items if (singleClick && allowMultiple) { throw new IllegalArgumentException("'singleClick' can not be used with 'allowMultiple'"); } // There might have been arguments set elsewhere, if so do not overwrite them. Bundle b = getArguments(); if (b == null) { b = new Bundle(); } if (startPath != null) { b.putString(KEY_START_PATH, startPath); } b.putBoolean(KEY_ALLOW_DIR_CREATE, allowDirCreate); b.putBoolean(KEY_ALLOW_MULTIPLE, allowMultiple); b.putBoolean(KEY_ALLOW_EXISTING_FILE, allowExistingFile); b.putBoolean(KEY_SINGLE_CLICK, singleClick); b.putInt(KEY_MODE, mode); setArguments(b); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflateRootView(inflater, container); Toolbar toolbar = (Toolbar) view.findViewById(R.id.nnf_picker_toolbar); if (toolbar != null) { setupToolbar(toolbar); } recyclerView = (RecyclerView) view.findViewById(android.R.id.list); // improve performance if you know that changes in content // do not change the size of the RecyclerView recyclerView.setHasFixedSize(true); // use a linear layout manager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); // Set Item Decoration if exists configureItemDecoration(inflater, recyclerView); // Set adapter mAdapter = new FileItemAdapter<>(this); recyclerView.setAdapter(mAdapter); view.findViewById(R.id.nnf_button_cancel) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { onClickCancel(v); } }); view.findViewById(R.id.nnf_button_ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { onClickOk(v); } }); view.findViewById(R.id.nnf_button_ok_newfile).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { onClickOk(v); } }); mNewFileButtonContainer = view.findViewById(R.id.nnf_newfile_button_container); mRegularButtonContainer = view.findViewById(R.id.nnf_button_container); mEditTextFileName = (EditText) view.findViewById(R.id.nnf_text_filename); mEditTextFileName.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // deSelect anything selected since the user just modified the name clearSelections(); } }); mCurrentDirView = (TextView) view.findViewById(R.id.nnf_current_dir); // Restore state if (mCurrentPath != null && mCurrentDirView != null) { mCurrentDirView.setText(getFullPath(mCurrentPath)); } return view; } protected View inflateRootView(LayoutInflater inflater, ViewGroup container) { return inflater.inflate( R.layout.nnf_fragment_filepicker, container, false); } /** * Checks if a divider drawable has been defined in the current theme. If it has, will apply * an item decoration with the divider. If no divider has been specified, then does nothing. */ protected void configureItemDecoration(@NonNull LayoutInflater inflater, @NonNull RecyclerView recyclerView) { final TypedArray attributes = getActivity().obtainStyledAttributes(new int[]{R.attr.nnf_list_item_divider}); Drawable divider = attributes.getDrawable(0); attributes.recycle(); if (divider != null) { recyclerView.addItemDecoration(new DividerItemDecoration(divider)); } } /** * Called when the cancel-button is pressed. * * @param view which was clicked. Not used in default implementation. */ public void onClickCancel(@NonNull View view) { if (mListener != null) { mListener.onCancelled(); } } /** * Called when the ok-button is pressed. * * @param view which was clicked. Not used in default implementation. */ public void onClickOk(@NonNull View view) { if (mListener == null) { return; } // Some invalid cases first /*if (MODE_NEW_FILE == mode && !isValidFileName(getNewFileName())) { mToast = Toast.makeText(getActivity(), R.string.nnf_need_valid_filename, Toast.LENGTH_SHORT); mToast.show(); return; }*/ if ((allowMultiple || mode == MODE_FILE) && (mCheckedItems.isEmpty() || getFirstCheckedItem() == null)) { if (mToast == null) { mToast = Toast.makeText(getActivity(), R.string.nnf_select_something_first, Toast.LENGTH_SHORT); } mToast.show(); return; } // New file allows only a single file if (mode == MODE_NEW_FILE) { final String filename = getNewFileName(); final Uri result; if (filename.startsWith("/")) { // Return absolute paths directly result = toUri(getPath(filename)); } else { // Append to current directory result = toUri(getPath(appendPath(getFullPath(mCurrentPath), filename))); } mListener.onFilePicked(result); } else if (allowMultiple) { mListener.onFilesPicked(toUri(mCheckedItems)); } else if (mode == MODE_FILE) { //noinspection ConstantConditions mListener.onFilePicked(toUri(getFirstCheckedItem())); } else if (mode == MODE_DIR) { mListener.onFilePicked(toUri(mCurrentPath)); } else { // single FILE OR DIR if (mCheckedItems.isEmpty()) { mListener.onFilePicked(toUri(mCurrentPath)); } else { mListener.onFilePicked(toUri(getFirstCheckedItem())); } } } /** * * @return filename as entered/picked by the user for the new file */ @NonNull protected String getNewFileName() { return mEditTextFileName.getText().toString(); } /** * Configure the toolbar anyway you like here. Default is to set it as the activity's * main action bar. Override if you already provide an action bar. * Not called if no toolbar was found. * * @param toolbar from layout with id "picker_toolbar" */ protected void setupToolbar(@NonNull Toolbar toolbar) { ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); } public @Nullable T getFirstCheckedItem() { //noinspection LoopStatementThatDoesntLoop for (T file : mCheckedItems) { return file; } return null; } protected @NonNull List<Uri> toUri(@NonNull Iterable<T> files) { ArrayList<Uri> uris = new ArrayList<>(); for (T file : files) { uris.add(toUri(file)); } return uris; } public boolean isCheckable(@NonNull final T data) { final boolean checkable; if (isDir(data)) { checkable = ((mode == MODE_DIR && allowMultiple) || (mode == MODE_FILE_AND_DIR && allowMultiple)); } else { // File checkable = (mode == MODE_FILE || mode == MODE_FILE_AND_DIR || allowExistingFile); } return checkable; } @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (OnFilePickedListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement OnFilePickedListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } /** * Called when the fragment's activity has been created and this * fragment's view hierarchy instantiated. It can be used to do final * initialization once these pieces are in place, such as retrieving * views or restoring state. It is also useful for fragments that use * {@link #setRetainInstance(boolean)} to retain their instance, * as this callback tells the fragment when it is fully associated with * the new activity instance. This is called after {@link #onCreateView} * and before {@link #onViewStateRestored(Bundle)}. * * @param savedInstanceState If the fragment is being re-created from * a previous saved state, this is the state. */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Only if we have no state if (mCurrentPath == null) { if (savedInstanceState != null) { mode = savedInstanceState.getInt(KEY_MODE, mode); allowCreateDir = savedInstanceState .getBoolean(KEY_ALLOW_DIR_CREATE, allowCreateDir); allowMultiple = savedInstanceState .getBoolean(KEY_ALLOW_MULTIPLE, allowMultiple); allowExistingFile = savedInstanceState .getBoolean(KEY_ALLOW_EXISTING_FILE, allowExistingFile); singleClick = savedInstanceState .getBoolean(KEY_SINGLE_CLICK, singleClick); String path = savedInstanceState.getString(KEY_CURRENT_PATH); if (path != null) { mCurrentPath = getPath(path.trim()); } } else if (getArguments() != null) { mode = getArguments().getInt(KEY_MODE, mode); allowCreateDir = getArguments() .getBoolean(KEY_ALLOW_DIR_CREATE, allowCreateDir); allowMultiple = getArguments() .getBoolean(KEY_ALLOW_MULTIPLE, allowMultiple); allowExistingFile = getArguments() .getBoolean(KEY_ALLOW_EXISTING_FILE, allowExistingFile); singleClick = getArguments() .getBoolean(KEY_SINGLE_CLICK, singleClick); if (getArguments().containsKey(KEY_START_PATH)) { String path = getArguments().getString(KEY_START_PATH); if (path != null) { T file = getPath(path.trim()); if (isDir(file)) { mCurrentPath = file; } else { mCurrentPath = getParent(file); mEditTextFileName.setText(getName(file)); } } } } } setModeView(); // If still null if (mCurrentPath == null) { mCurrentPath = getRoot(); } refresh(mCurrentPath); } /** * Hides/Shows appropriate views depending on mode */ protected void setModeView() { boolean nf = mode == MODE_NEW_FILE; mNewFileButtonContainer.setVisibility(nf ? View.VISIBLE : View.GONE); mRegularButtonContainer.setVisibility(nf ? View.GONE : View.VISIBLE); if (!nf && singleClick) { getActivity().findViewById(R.id.nnf_button_ok).setVisibility(View.GONE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.picker_actions, menu); MenuItem item = menu.findItem(R.id.nnf_action_createdir); item.setVisible(allowCreateDir); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (R.id.nnf_action_createdir == menuItem.getItemId()) { Activity activity = getActivity(); if (activity instanceof AppCompatActivity) { NewFolderFragment.showDialog(((AppCompatActivity) activity).getSupportFragmentManager(), AbstractFilePickerFragment.this); } return true; } else { return false; } } @Override public void onSaveInstanceState(Bundle b) { b.putString(KEY_CURRENT_PATH, mCurrentPath.toString()); b.putBoolean(KEY_ALLOW_MULTIPLE, allowMultiple); b.putBoolean(KEY_ALLOW_EXISTING_FILE, allowExistingFile); b.putBoolean(KEY_ALLOW_DIR_CREATE, allowCreateDir); b.putBoolean(KEY_SINGLE_CLICK, singleClick); b.putInt(KEY_MODE, mode); super.onSaveInstanceState(b); } @Override public void onDetach() { super.onDetach(); mListener = null; } protected void refresh(@NonNull T nextPath) { if (hasPermission(nextPath)) { mCurrentPath = nextPath; isLoading = true; getLoaderManager() .restartLoader(0, null, AbstractFilePickerFragment.this); } else { handlePermission(nextPath); } } protected void handlePermission(@NonNull T path) { // Nothing to do by default } protected boolean hasPermission(@NonNull T path) { // Nothing to request by default return true; } /** * Instantiate and return a new Loader for the given ID. * * @param id The ID whose loader is to be created. * @param args Any arguments supplied by the caller. * @return Return a new Loader instance that is ready to start loading. */ @Override public Loader<SortedList<T>> onCreateLoader(final int id, final Bundle args) { return getLoader(); } /** * Called when a previously created loader has finished its load. * * @param loader The Loader that has finished. * @param data The data generated by the Loader. */ @Override public void onLoadFinished(final Loader<SortedList<T>> loader, final SortedList<T> data) { isLoading = false; mCheckedItems.clear(); mCheckedVisibleViewHolders.clear(); mFiles = data; mAdapter.setList(data); if (mCurrentDirView != null) { mCurrentDirView.setText(getFullPath(mCurrentPath)); } // Stop loading now to avoid a refresh clearing the user's selections getLoaderManager().destroyLoader( 0 ); } /** * Called when a previously created loader is being reset, and thus * making its data unavailable. The application should at this point * remove any references it has to the Loader's data. * * @param loader The Loader that is being reset. */ @Override public void onLoaderReset(final Loader<SortedList<T>> loader) { isLoading = false; } /** * @param position 0 - n, where the header has been subtracted * @param data the actual file or directory * @return an integer greater than 0 */ @Override public int getItemViewType(int position, @NonNull T data) { if (isCheckable(data)) { return LogicHandler.VIEWTYPE_CHECKABLE; } else { return LogicHandler.VIEWTYPE_DIR; } } @Override public void onBindHeaderViewHolder(@NonNull HeaderViewHolder viewHolder) { viewHolder.text.setText(".."); } /** * @param parent Containing view * @param viewType which the ViewHolder will contain * @return a view holder for a file or directory */ @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v; switch (viewType) { case LogicHandler.VIEWTYPE_HEADER: v = LayoutInflater.from(getActivity()).inflate(R.layout.nnf_filepicker_listitem_dir, parent, false); return new HeaderViewHolder(v); case LogicHandler.VIEWTYPE_CHECKABLE: v = LayoutInflater.from(getActivity()).inflate(R.layout.nnf_filepicker_listitem_checkable, parent, false); return new CheckableViewHolder(v); case LogicHandler.VIEWTYPE_DIR: default: v = LayoutInflater.from(getActivity()).inflate(R.layout.nnf_filepicker_listitem_dir, parent, false); return new DirViewHolder(v); } } /** * @param vh to bind data from either a file or directory * @param position 0 - n, where the header has been subtracted * @param data the file or directory which this item represents */ @Override public void onBindViewHolder(@NonNull DirViewHolder vh, int position, @NonNull T data) { vh.file = data; vh.icon.setVisibility(isDir(data) ? View.VISIBLE : View.GONE); vh.text.setText(getName(data)); if (isCheckable(data)) { if (mCheckedItems.contains(data)) { mCheckedVisibleViewHolders.add((CheckableViewHolder) vh); ((CheckableViewHolder) vh).checkbox.setChecked(true); } else { //noinspection SuspiciousMethodCalls mCheckedVisibleViewHolders.remove(vh); ((CheckableViewHolder) vh).checkbox.setChecked(false); } } } /** * Animate de-selection of visible views and clear * selected set. */ public void clearSelections() { for (CheckableViewHolder vh : mCheckedVisibleViewHolders) { vh.checkbox.setChecked(false); } mCheckedVisibleViewHolders.clear(); mCheckedItems.clear(); } /** * Called when a header item ("..") is clicked. * * @param view that was clicked. Not used in default implementation. * @param viewHolder for the clicked view */ public void onClickHeader(@NonNull View view, @NonNull HeaderViewHolder viewHolder) { goUp(); } /** * Browses to the parent directory from the current directory. For example, if the current * directory is /foo/bar/, then goUp() will change the current directory to /foo/. It is up to * the caller to not call this in vain, e.g. if you are already at the root. * <p/> * Currently selected items are cleared by this operation. */ public void goUp() { goToDir(getParent(mCurrentPath)); } /** * Called when a non-selectable item, typically a directory, is clicked. * * @param view that was clicked. Not used in default implementation. * @param viewHolder for the clicked view */ public void onClickDir(@NonNull View view, @NonNull DirViewHolder viewHolder) { if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } } /** * Cab be used by the list to determine whether a file should be displayed or not. * Default behavior is to always display folders. If files can be selected, * then files are also displayed. In case a new file is supposed to be selected, * the {@link #allowExistingFile} determines if existing files are visible * * @param file either a directory or file. * @return True if item should be visible in the picker, false otherwise */ protected boolean isItemVisible(final T file) { return (isDir(file) || (mode == MODE_FILE || mode == MODE_FILE_AND_DIR) || (mode == MODE_NEW_FILE && allowExistingFile)); } /** * Browses to the designated directory. It is up to the caller verify that the argument is * in fact a directory. If another directory is in the process of being loaded, this method * will not start another load. * <p/> * Currently selected items are cleared by this operation. * * @param file representing the target directory. */ public void goToDir(@NonNull T file) { if (!isLoading) { mCheckedItems.clear(); mCheckedVisibleViewHolders.clear(); refresh(file); } } /** * Long clicking a non-selectable item does nothing by default. * * @param view which was long clicked. Not used in default implementation. * @param viewHolder for the clicked view * @return true if the callback consumed the long click, false otherwise. */ public boolean onLongClickDir(@NonNull View view, @NonNull DirViewHolder viewHolder) { return false; } /** * Called when a selectable item is clicked. This might be either a file or a directory. * * @param view that was clicked. Not used in default implementation. * @param viewHolder for the clicked view */ public void onClickCheckable(@NonNull View view, @NonNull CheckableViewHolder viewHolder) { if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } else { onLongClickCheckable(view, viewHolder); if (singleClick) { onClickOk(view); } } } /** * Long clicking a selectable item should toggle its selected state. Note that if only a * single item can be selected, then other potentially selected views on screen must be * de-selected. * * @param view which was long clicked. Not used in default implementation. * @param viewHolder for the clicked view * @return true if the callback consumed the long click, false otherwise. */ public boolean onLongClickCheckable(@NonNull View view, @NonNull CheckableViewHolder viewHolder) { if (MODE_NEW_FILE == mode) { mEditTextFileName.setText(getName(viewHolder.file)); } onClickCheckBox(viewHolder); return true; } /** * Called when a selectable item's checkbox is pressed. This should toggle its selected state. * Note that if only a single item can be selected, then other potentially selected views on * screen must be de-selected. The text box for new filename is also cleared. * * @param viewHolder for the item containing the checkbox. */ public void onClickCheckBox(@NonNull CheckableViewHolder viewHolder) { if (mCheckedItems.contains(viewHolder.file)) { viewHolder.checkbox.setChecked(false); mCheckedItems.remove(viewHolder.file); mCheckedVisibleViewHolders.remove(viewHolder); } else { if (!allowMultiple) { clearSelections(); } viewHolder.checkbox.setChecked(true); mCheckedItems.add(viewHolder.file); mCheckedVisibleViewHolders.add(viewHolder); } } public interface OnFilePickedListener { void onFilePicked(@NonNull Uri file); void onFilesPicked(@NonNull List<Uri> files); void onCancelled(); } public class HeaderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { final TextView text; public HeaderViewHolder(View v) { super(v); v.setOnClickListener(this); text = (TextView) v.findViewById(android.R.id.text1); } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { onClickHeader(v, this); } } public class DirViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { public View icon; public TextView text; public T file; public DirViewHolder(View v) { super(v); v.setOnClickListener(this); v.setOnLongClickListener(this); icon = v.findViewById(R.id.item_icon); text = (TextView) v.findViewById(android.R.id.text1); } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { onClickDir(v, this); } /** * Called when a view has been clicked and held. * * @param v The view that was clicked and held. * @return true if the callback consumed the long click, false otherwise. */ @Override public boolean onLongClick(View v) { return onLongClickDir(v, this); } } public class CheckableViewHolder extends DirViewHolder { public CheckBox checkbox; public CheckableViewHolder(View v) { super(v); boolean nf = mode == MODE_NEW_FILE; checkbox = (CheckBox) v.findViewById(R.id.checkbox); checkbox.setVisibility((nf || singleClick) ? View.GONE : View.VISIBLE); checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickCheckBox(CheckableViewHolder.this); } }); } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { onClickCheckable(v, this); } /** * Called when a view has been clicked and held. * * @param v The view that was clicked and held. * @return true if the callback consumed the long click, false otherwise. */ @Override public boolean onLongClick(View v) { return onLongClickCheckable(v, this); } } }
package com.sage42.android.view.pager; import android.database.Cursor; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; public abstract class CursorFragmentPagerAdapter extends FragmentStatePagerAdapter { protected Cursor mCursor; public CursorFragmentPagerAdapter(final FragmentManager fm, final Cursor cursor) { super(fm); this.mCursor = cursor; } @Override public Fragment getItem(final int position) { if (this.mCursor == null) { return null; } this.mCursor.moveToPosition(position); return this.getItem(this.mCursor); } public abstract Fragment getItem(Cursor cursor); @Override public int getCount() { if (this.mCursor == null) { return 0; } else { return this.mCursor.getCount(); } } public void swapCursor(final Cursor c) { if (this.mCursor == c) { return; } this.mCursor = c; this.notifyDataSetChanged(); } public Cursor getCursor() { return this.mCursor; } }
package roart.ml.tensorflow; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.common.config.MyMyConfig; import roart.common.ml.NeuralNetConfig; import roart.common.ml.NeuralNetConfigs; import roart.eureka.util.EurekaUtil; import roart.ml.model.LearnTestPredict; import roart.ml.model.LearnTestPredictResult; import roart.ml.model.MLPredictAccess; import roart.ml.model.MLPredictModel; import roart.pipeline.common.predictor.AbstractPredictor; public class MLPredictTensorflowAccess extends MLPredictAccess { private Logger log = LoggerFactory.getLogger(this.getClass()); private MyMyConfig conf; private String tensorflowServer; public MLPredictTensorflowAccess(MyMyConfig conf) { this.conf = conf; findModels(); tensorflowServer = conf.getTensorflowServer(); } private void findModels() { models = new ArrayList<>(); if (conf.wantLSTM()) { MLPredictModel model = new MLPredictTensorflowLSTMModel(conf); models.add(model); } } @Override public LearnTestPredictResult predictone(NeuralNetConfigs nnconfigs, AbstractPredictor predictor, Double[] list, MLPredictModel model, int size, String period, int outcomes) { return predictInner(nnconfigs, list, size, period, outcomes, model); } @Override public List<MLPredictModel> getModels() { return models; } private LearnTestPredictResult predictInner(NeuralNetConfigs nnconfigs, Double[] list, int size, String period, int outcomes, MLPredictModel model) { LearnTestPredict param = new LearnTestPredict(); model.getModelAndSet(nnconfigs, param); param.modelInt = model.getId(); param.size = size; param.period = period; param.outcomes = outcomes; param.array = list; log.info("evalin {} {}", param.modelInt, period); LearnTestPredictResult result = EurekaUtil.sendMe(LearnTestPredictResult.class, param, tensorflowServer + "/predictone"); return result; } @Override public Double eval(int modelInt, String period, String mapname) { LearnTestPredict param = new LearnTestPredict(); param.modelInt = modelInt; param.period = period; param.mapname = mapname; log.info("evalout {} {} {}", modelInt, period, mapname); System.out.println("NOTHERE0"); LearnTestPredict test = EurekaUtil.sendMe(LearnTestPredict.class, param, tensorflowServer + "/eval"); return test.prob; } @Override public LearnTestPredictResult predict(NeuralNetConfigs nnconfigs, AbstractPredictor predictor, Map<String, Double[]> map, MLPredictModel model, int size, String period, int outcomes) { if (map.isEmpty()) { return null; } return predictInner(nnconfigs, map, model, size, period); } private LearnTestPredictResult predictInner(NeuralNetConfigs nnconfigs, Map<String, Double[]> map, MLPredictModel model, int size, String period) { List<String> retList = new ArrayList<>(); LearnTestPredict param = new LearnTestPredict(); model.getModelAndSet(nnconfigs, param); int i = 0; List<Object[]> objobj = new ArrayList<>(); for (Entry<String, Double[]> entry : map.entrySet()) { String key = entry.getKey(); Double[] value = entry.getValue(); Object[] obj = new Object[value.length]; for (int j = 0; j < value.length; j ++) { obj[j] = value[j]; } objobj.add(obj); retList.add(key); } for(Object[] obj : objobj) { log.info("inner {}", Arrays.asList(obj)); } param.arraylist = objobj; log.info("evalin {} {}", param.modelInt, size); LearnTestPredictResult ret = EurekaUtil.sendMe(LearnTestPredictResult.class, param, tensorflowServer + "/predict"); List<Double[]> arraylist = ret.predictedlist; List<Double> accuracylist = ret.accuracylist; Map<String, Double[]> predictMap = new HashMap<>(); Map<String, Double> accuracyMap = new HashMap<>(); int count = 0; for (Entry<String, Double[]> entry : map.entrySet()) { String key = entry.getKey(); Double accuracy = accuracylist.get(count); Double[] value = arraylist.get(count++); if (accuracy < 0) { continue; } accuracyMap.put(key, accuracy); predictMap.put(key, value); } ret.accuracyMap = accuracyMap; ret.predictMap = predictMap; return ret; } }
package com.macro.mall.portal.service; import com.macro.mall.portal.domain.MemberBrandAttention; import org.springframework.data.domain.Page; public interface MemberAttentionService { int add(MemberBrandAttention memberBrandAttention); int delete(Long brandId); Page<MemberBrandAttention> list(Integer pageNum, Integer pageSize); MemberBrandAttention detail(Long brandId); void clear(); }
class HelloWorld { public static void main (String[] args) { System.out.println("Hello World Folks!\nThis is java test in docker image"); } }
package bisq.apitest; import lombok.extern.slf4j.Slf4j; import static bisq.apitest.Scaffold.EXIT_FAILURE; import static bisq.apitest.Scaffold.EXIT_SUCCESS; import static bisq.apitest.config.BisqAppConfig.alicedaemon; import static java.lang.System.err; import static java.lang.System.exit; import bisq.apitest.config.ApiTestConfig; import bisq.apitest.method.MethodTestSuite; /** * ApiTest Application * * Runs all method tests, scenario tests, and end to end tests (e2e). * * Requires bitcoind v0.19.x */ @Slf4j public class ApiTestMain { public static void main(String[] args) { new ApiTestMain().execute(args); } public void execute(@SuppressWarnings("unused") String[] args) { try { Scaffold scaffold = new Scaffold(args).setUp(); ApiTestConfig config = scaffold.config; if (config.skipTests) { log.info("Skipping tests ..."); } else { new SmokeTestBitcoind(config).run(); GrpcStubs grpcStubs = new GrpcStubs(alicedaemon, config).init(); MethodTestSuite methodTestSuite = new MethodTestSuite(grpcStubs); methodTestSuite.run(); } if (config.shutdownAfterTests) { scaffold.tearDown(); exit(EXIT_SUCCESS); } else { log.info("Not shutting down scaffolding background processes will run until ^C / kill -15 is rcvd ..."); } } catch (Throwable ex) { err.println("Fault: An unexpected error occurred. " + "Please file a report at https://bisq.network/issues"); ex.printStackTrace(err); exit(EXIT_FAILURE); } } }
package functionalTests.component.migration; import static org.junit.Assert.assertEquals; import org.junit.Ignore; import org.objectweb.proactive.api.PAActiveObject; import functionalTests.ComponentTest; /** * This test deploys a distributed component system and makes sure migration is effective by * invoking methods on migrated components (through singleton, collection, gathercast and multicast interfaces) * * @author The ProActive Team */ public class Test extends ComponentTest { public static String MESSAGE = " //ComponentsCache componentsCache; public Test() { super("migration of components", "migration of components"); } /* * (non-Javadoc) * * @see testsuite.test.FunctionalTest#action() */ @org.junit.Test public void GCMDeployment() throws Exception { DummyAO testAO = PAActiveObject.newActive(DummyAO.class, new Object[] {}); assertEquals(true, testAO.goGCMDeployment()); } @Ignore // Fails on debian @org.junit.Test public void OldDeployment() throws Exception { DummyAO testAO = PAActiveObject.newActive(DummyAO.class, new Object[] {}); assertEquals(true, testAO.goOldDeployment()); } }
package be.ibridge.kettle.trans.step.injector; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Executor class to allow a java program to inject rows of data into a transformation. * This step can be used as a starting point in such a "headless" transformation. * * @since 22-jun-2006 */ public class Injector extends BaseStep implements StepInterface { private InjectorMeta meta; private InjectorData data; public Injector(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); meta=(InjectorMeta)getStepMeta().getStepMetaInterface(); data=(InjectorData)stepDataInterface; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { // Get a row from the previous step OR from an extra RowSet Row row = getRow(); if (row==null) // Nothing more to be had from any input rowset { setOutputDone(); return false; } putRow(row); // copy row to possible alternate rowset(s). if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic(Messages.getString("Injector.Log.LineNumber")+linesRead); //$NON-NLS-1$ return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(InjectorMeta)smi; data=(InjectorData)sdi; if (super.init(smi, sdi)) { // Add init code here. return true; } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("Injector.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError(Messages.getString("Injector.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package ca.ualberta.cs.bkhunter_notes; import java.util.ArrayList; import java.util.Collection; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class AddDirectExpense extends Activity { int index; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } private Spinner categorySpinner, currencySpinner; private Button addSingleButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_direct_expense_activity); ClaimListManager.initManager(this.getApplicationContext()); Bundle bundle = getIntent().getExtras(); int index = bundle.getInt("index"); this.setIndex(index); } public void addItemsOnSpinner() { categorySpinner = (Spinner)findViewById(R.id.categorySpinner); List<String> list = new ArrayList<String>(); list.add("list 1"); list.add("list 2"); list.add("list 3"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(adapter); } public void addItemsOnSpinner2() { currencySpinner = (Spinner)findViewById(R.id.currencySpinner); List<String> list = new ArrayList<String>(); list.add("list 1"); list.add("list 2"); list.add("list 3"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); currencySpinner.setAdapter(adapter); } public void addListenerOnSpinnerItemSelection() { categorySpinner = (Spinner) findViewById(R.id.categorySpinner); categorySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener()); } public void addListenerOnSpinnerItemSelection2() { currencySpinner = (Spinner) findViewById(R.id.currencySpinner); currencySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener()); } public void addListenerOnButton() { categorySpinner = (Spinner) findViewById(R.id.categorySpinner); currencySpinner = (Spinner) findViewById(R.id.currencySpinner); addSingleButton = (Button) findViewById(R.id.addSingleButton); addSingleButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(AddDirectExpense.this, "OnClickListener : " + "\nSpinner 1 : " + String.valueOf(currencySpinner.getSelectedItem()),Toast.LENGTH_SHORT).show(); } }); addSingleButton = (Button) findViewById(R.id.addSingleButton); addSingleButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(AddDirectExpense.this, "OnClickListener : " + "\nSpinner 1 : " + String.valueOf(categorySpinner.getSelectedItem()),Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.add_direct_expense, menu); return true; } public void finishAction(View v) { EditText itemTextView = (EditText)findViewById(R.id.itemEditText); EditText descTextView = (EditText)findViewById(R.id.descrText); EditText amountTextView = (EditText)findViewById(R.id.amountView); EditText dateTextView = (EditText)findViewById(R.id.dateEditText); Spinner categorySpinner=(Spinner) findViewById(R.id.categorySpinner); Spinner currencySpinner=(Spinner) findViewById(R.id.currencySpinner); String item = itemTextView.getText().toString(); String date = dateTextView.getText().toString(); String desc = descTextView.getText().toString(); String category = categorySpinner.getSelectedItem().toString(); String currency = currencySpinner.getSelectedItem().toString(); int amt = Integer.valueOf(amountTextView.getText().toString()); if (!item.equals("") && !desc.equals("")) { Collection<Claim> c = ClaimController.getClaimList().getClaims(); ArrayList<Claim> list = new ArrayList<Claim>(c); Claim claim = list.get(this.getIndex()); Expense_Item e = new Expense_Item(item,date, category, desc, amt, currency); claim.addExpense_Item(e); Intent intent = new Intent(AddDirectExpense.this, ExpenseItems.class); Bundle bundle = new Bundle(); bundle.putInt("index", this.getIndex()); intent.putExtras(bundle); startActivity(intent); } else { Toast.makeText(this,"Please fill out all fields", Toast.LENGTH_SHORT).show(); } //Toast.makeText(this,"test", Toast.LENGTH_SHORT).show(); } }
package org.commcare.util.cli; import org.commcare.cases.util.CasePurgeFilter; import org.commcare.cases.util.InvalidCaseGraphException; import org.commcare.core.interfaces.UserSandbox; import org.commcare.core.parse.CommCareTransactionParserFactory; import org.commcare.core.parse.ParseUtils; import org.commcare.core.sandbox.SandboxUtils; import org.commcare.data.xml.DataModelPullParser; import org.commcare.resources.model.InstallCancelledException; import org.commcare.resources.model.ResourceInitializationException; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.session.SessionFrame; import org.commcare.suite.model.Endpoint; import org.commcare.suite.model.FormIdDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.StackFrameStep; import org.commcare.suite.model.StackOperation; import org.commcare.util.CommCarePlatform; import org.commcare.util.engine.CommCareConfigEngine; import org.commcare.util.mocks.CLISessionWrapper; import org.commcare.util.mocks.MockUserDataSandbox; import org.commcare.util.screen.CommCareSessionException; import org.commcare.util.screen.EntityListSubscreen; import org.commcare.util.screen.EntityScreen; import org.commcare.util.screen.MenuScreen; import org.commcare.util.screen.QueryScreen; import org.commcare.util.screen.Screen; import org.commcare.util.screen.SessionUtils; import org.commcare.util.screen.SyncScreen; import org.javarosa.core.model.User; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.engine.XFormPlayer; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.FunctionUtils; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.*; /** * CLI host for running a commcare application which has been configured and instatiated * for the provided user. * * @author ctsims */ public class ApplicationHost { private final CommCareConfigEngine mEngine; private final CommCarePlatform mPlatform; private UserSandbox mSandbox; private CLISessionWrapper mSession; private boolean mUpdatePending = false; private String mUpdateTarget = null; private boolean mSessionHasNextFrameReady = false; private final PrototypeFactory mPrototypeFactory; private final BufferedReader reader; private final PrintStream printStream; private String username; private String qualifiedUsername; private String password; private String mRestoreFile; private boolean mRestoreStrategySet = false; public ApplicationHost(CommCareConfigEngine engine, PrototypeFactory prototypeFactory, BufferedReader reader, PrintStream out) { this.mEngine = engine; this.mPlatform = engine.getPlatform(); this.reader = reader; this.mPrototypeFactory = prototypeFactory; this.printStream = out; } public ApplicationHost(CommCareConfigEngine engine, PrototypeFactory prototypeFactory) { this(engine, prototypeFactory, new BufferedReader(new InputStreamReader(System.in)), System.out); } public void setRestoreToRemoteUser(String username, String password) { this.username = username; this.password = password; String domain = mPlatform.getPropertyManager().getSingularProperty("cc_user_domain"); this.qualifiedUsername = username + "@" + domain; mRestoreStrategySet = true; } public void setRestoreToLocalFile(String filename) { this.mRestoreFile = filename; mRestoreStrategySet = true; } public void setRestoreToDemoUser() { mRestoreStrategySet = true; } public void advanceSessionWithEndpoint(String endpointId, String[] endpointArgs) { if (endpointId == null) { return; } Endpoint endpoint = mPlatform.getEndpoint(endpointId); if (endpoint == null) { throw new RuntimeException(endpointId + " not found"); } if (endpointArgs == null) { endpointArgs = new String[0]; } mSession.clearAllState(); mSession.clearVolatiles(); EvaluationContext evalContext = mSession.getEvaluationContext(); try { Endpoint.populateEndpointArgumentsToEvaluationContext(endpoint, new ArrayList<String>(Arrays.asList(endpointArgs)), evalContext); } catch (Endpoint.InvalidEndpointArgumentsException e) { String missingMessage = ""; if (e.hasMissingArguments()) { missingMessage = String.format(" Missing arguments: %s.", String.join(", ", e.getMissingArguments())); } String unexpectedMessage = ""; if (e.hasUnexpectedArguments()) { unexpectedMessage = String.format(" Unexpected arguments: %s.", String.join(", ", e.getUnexpectedArguments())); } throw new RuntimeException("Invalid arguments for endpoint." + missingMessage + unexpectedMessage); } for (StackOperation op : endpoint.getStackOperations()) { mSession.executeStackOperations(new Vector<>(Arrays.asList(op)), evalContext); Screen s = getNextScreen(); if (s instanceof SyncScreen) { try { s.init(mSession); s.handleInputAndUpdateSession(mSession, "", false); } catch (CommCareSessionException ccse) { printErrorAndContinue("Error during session execution:", ccse); } } } mSessionHasNextFrameReady = true; } public void run(String endpointId, String[] endpointArgs) { if (!mRestoreStrategySet) { throw new RuntimeException("You must set up an application host by calling " + "one of the setRestore*() methods before running the app"); } setupSandbox(); mSession = new CLISessionWrapper(mPlatform, mSandbox); advanceSessionWithEndpoint(endpointId, endpointArgs); try { loop(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } private void loop() throws IOException { boolean keepExecuting = true; while (keepExecuting) { if (!mSessionHasNextFrameReady) { mSession.clearAllState(); } mSessionHasNextFrameReady = false; keepExecuting = loopSession(); if (this.mUpdatePending) { processAppUpdate(); } } } private void processAppUpdate() { mSession.clearAllState(); this.mUpdatePending = false; String updateTarget = mUpdateTarget; this.mUpdateTarget = null; try { mEngine.attemptAppUpdate(updateTarget, username); } catch (UnresolvedResourceException e) { printStream.println("Update Failed! Couldn't find or install one of the remote resources"); e.printStackTrace(); } catch (UnfullfilledRequirementsException e) { printStream.println("Update Failed! This CLI host is incompatible with the app"); e.printStackTrace(); } catch (InstallCancelledException e) { printStream.println("Update Failed! Update was cancelled"); e.printStackTrace(); } catch (ResourceInitializationException e) { printStream.println("Update Failed! Couldn't initialize one of the resources"); e.printStackTrace(); } } private boolean loopSession() throws IOException { Screen s = getNextScreen(); boolean screenIsRedrawing = false; boolean sessionIsLive = true; while (sessionIsLive) { while (s != null) { try { if (!screenIsRedrawing) { s.init(mSession); if (s.shouldBeSkipped()) { s = getNextScreen(); continue; } } printStream.println("\n\n\n\n\n\n"); printStream.println(s.getWrappedDisplaytitle(mSandbox, mPlatform)); printStream.println("===================="); boolean requiresInput = s.prompt(printStream); screenIsRedrawing = false; String input = ""; if (requiresInput) { printStream.print("> "); input = reader.readLine(); } //TODO: Command language if (input.startsWith(":")) { if (input.equals(":exit") || input.equals(":quit")) { return false; } if (input.startsWith(":update")) { mUpdatePending = true; if (input.contains(("--latest")) || input.contains("-f")) { mUpdateTarget = "build"; printStream.println("Updating to most recent build"); } else if (input.contains(("--preview")) || input.contains("-p")) { mUpdateTarget = "save"; printStream.println("Updating to latest app preview"); } else { mUpdateTarget = "release"; printStream.println("Updating to newest Release"); } return true; } if (input.equals(":home")) { return true; } if (input.equals(":back")) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); continue; } if (input.equals(":stack")) { printStack(mSession); continue; } if (input.startsWith(":lang")) { String[] langArgs = input.split(" "); if (langArgs.length != 2) { printStream.println("Command format\n:lang [langcode]"); continue; } String newLocale = langArgs[1]; setLocale(newLocale); continue; } if (input.startsWith(":sync")) { syncAndReport(); continue; } } // When a user selects an entity in the EntityListSubscreen, this sets mCurrentSelection // which ultimately updates the session, so getNextScreen will move onto the form list, // skipping the entity detail. To avoid this, flag that we want to force a redraw in this case. boolean waitForCaseDetail = false; if (s instanceof EntityScreen) { boolean isAction = input.startsWith("action "); // Don't wait for case detail if action if (!isAction && ((EntityScreen) s).getCurrentScreen() instanceof EntityListSubscreen) { waitForCaseDetail = true; } } screenIsRedrawing = !s.handleInputAndUpdateSession(mSession, input, false); if (!screenIsRedrawing && !waitForCaseDetail) { s = getNextScreen(); } } catch (CommCareSessionException ccse) { printErrorAndContinue("Error during session execution:", ccse); //Restart return true; } catch (XPathException xpe) { printErrorAndContinue("XPath Evaluation exception during session execution:", xpe); //Restart return true; } } //We have a session and are ready to fill out a form! printStream.println("Starting form entry with the following stack frame"); printStack(mSession); //Get our form object String formXmlns = mSession.getForm(); if (formXmlns == null) { finishSession(); return true; } else { XFormPlayer player = new XFormPlayer(reader, printStream, null); player.setPreferredLocale(Localization.getGlobalLocalizerAdvanced().getLocale()); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); //If the form saved properly, process the output if (player.getExecutionResult() == XFormPlayer.FormResult.Completed) { if (!processResultInstance(player.getResultStream())) { return true; } finishSession(); return true; } else if (player.getExecutionResult() == XFormPlayer.FormResult.Cancelled) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); } else { //Handle this later return true; } } } //After we finish, continue executing return true; } private void printStack(CLISessionWrapper mSession) { SessionFrame frame = mSession.getFrame(); printStream.println("Live Frame"); printStream.println(" for (StackFrameStep step : frame.getSteps()) { if (step.getType().equals(SessionFrame.STATE_COMMAND_ID)) { printStream.println("COMMAND: " + step.getId()); } else { printStream.println("DATUM : " + step.getId() + " - " + step.getValue()); } } } private void finishSession() { mSession.clearVolatiles(); if (mSession.finishExecuteAndPop(mSession.getEvaluationContext())) { mSessionHasNextFrameReady = true; } } private boolean processResultInstance(InputStream resultStream) { try { DataModelPullParser parser = new DataModelPullParser( resultStream, new CommCareTransactionParserFactory(mSandbox), true, true); parser.parse(); } catch (Exception e) { printErrorAndContinue("Error processing the form result!", e); return false; } finally { try { resultStream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } private void printErrorAndContinue(String error, Exception e) { printStream.println(error); e.printStackTrace(); printStream.println("Press return to restart the session"); try { reader.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } private Screen getNextScreen() { String next = mSession.getNeededData(mSession.getEvaluationContext()); if (next == null) { //XFORM TIME! return null; } else if (next.equals(SessionFrame.STATE_COMMAND_ID)) { return new MenuScreen(); } else if (next.equals(SessionFrame.STATE_DATUM_VAL)) { return new EntityScreen(true); } else if (next.equals(SessionFrame.STATE_QUERY_REQUEST)) { return new QueryScreen(qualifiedUsername, password, System.out); } else if (next.equals(SessionFrame.STATE_SYNC_REQUEST)) { return new SyncScreen(qualifiedUsername, password, System.out); } else if (next.equalsIgnoreCase(SessionFrame.STATE_DATUM_COMPUTED)) { computeDatum(); return getNextScreen(); } throw new RuntimeException("Unexpected Frame Request: " + next); } private void computeDatum() { //compute SessionDatum datum = mSession.getNeededDatum(); XPathExpression form; try { form = XPathParseTool.parseXPath(datum.getValue()); } catch (XPathSyntaxException e) { //TODO: What. e.printStackTrace(); throw new RuntimeException(e.getMessage()); } EvaluationContext ec = mSession.getEvaluationContext(); if (datum instanceof FormIdDatum) { mSession.setXmlns(FunctionUtils.toString(form.eval(ec))); mSession.setDatum("", "awful"); } else { try { mSession.setDatum(datum.getDataId(), FunctionUtils.toString(form.eval(ec))); } catch (XPathException e) { error(e); } } } private void error(Exception e) { e.printStackTrace(); System.exit(-1); } private void setupSandbox() { //Set up our storage MockUserDataSandbox sandbox = new MockUserDataSandbox(mPrototypeFactory); //this gets configured earlier when we installed the app, should point it in the //right direction! sandbox.setAppFixtureStorageLocation((IStorageUtilityIndexed<FormInstance>) mPlatform.getStorageManager().getStorage(FormInstance.STORAGE_KEY)); mSandbox = sandbox; if (username != null && password != null) { SessionUtils.restoreUserToSandbox(mSandbox, mSession, mPlatform, username, password, System.out); } else if (mRestoreFile != null) { restoreFileToSandbox(mSandbox, mRestoreFile); } else { restoreDemoUserToSandbox(mSandbox); } } private void restoreFileToSandbox(UserSandbox sandbox, String restoreFile) { FileInputStream fios = null; try { printStream.println("Restoring user data from local file " + restoreFile); fios = new FileInputStream(restoreFile); } catch (FileNotFoundException e) { printStream.println("No restore file found at" + restoreFile); System.exit(-1); } try { ParseUtils.parseIntoSandbox(new BufferedInputStream(fios), sandbox, false); } catch (Exception e) { printStream.println("Error parsing local restore data from " + restoreFile); e.printStackTrace(); System.exit(-1); } initUser(); } private void initUser() { User u = mSandbox.getUserStorage().read(0); mSandbox.setLoggedInUser(u); printStream.println("Setting logged in user to: " + u.getUsername()); } private void restoreDemoUserToSandbox(UserSandbox sandbox) { try { ParseUtils.parseIntoSandbox(mPlatform.getDemoUserRestore().getRestoreStream(), sandbox, false); } catch (Exception e) { printStream.println("Error parsing demo user restore from app"); e.printStackTrace(); System.exit(-1); } initUser(); } private void setLocale(String locale) { Localizer localizer = Localization.getGlobalLocalizerAdvanced(); String availableLocales = ""; for (String availabile : localizer.getAvailableLocales()) { availableLocales += availabile + "\n"; if (locale.equals(availabile)) { localizer.setLocale(locale); return; } } printStream.println("Locale '" + locale + "' is undefined in this app! Available Locales:"); printStream.println(" printStream.println(availableLocales); } private void syncAndReport() { performCasePurge(mSandbox); if (username != null && password != null) { System.out.println("Requesting sync..."); SessionUtils.restoreUserToSandbox(mSandbox, mSession, mPlatform, username, password, System.out); } else { printStream.println("Syncing is only available when using raw user credentials"); } } public void performCasePurge(UserSandbox sandbox) { printStream.println("Performing Case Purge"); CasePurgeFilter purger = null; try { purger = new CasePurgeFilter(sandbox.getCaseStorage(), SandboxUtils.extractEntityOwners(sandbox)); } catch (InvalidCaseGraphException e) { printStream.println(e.getMessage()); return; } int removedCases = sandbox.getCaseStorage().removeAll(purger).size(); printStream.println(""); printStream.println("Purge Report"); printStream.println("========================="); if (removedCases == 0) { printStream.println("0 Cases Purged"); } else { printStream.println("Cases Removed from device[" + removedCases + "]: " + purger.getRemovedCasesString()); } if (!("".equals(purger.getRemovedCasesString()))) { printStream.println("[Error/Warning] Cases Missing from Device: " + purger.getMissingCasesString()); } if (purger.invalidEdgesWereRemoved()) { printStream.println("[Error/Warning] During Purge Invalid Edges were Detected"); } } }
package view.components.controls.colorLegend; import java.net.URL; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import org.controlsfx.control.RangeSlider; import javafx.event.EventHandler; import javafx.geometry.Orientation; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Label; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.util.Pair; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import model.workspace.TaskType; import model.workspace.tasks.ITaskListener; import view.components.DatapointIDMode; import view.components.VisualizationComponent; /** * Displays color scale for given range of values and selected colors. * Is embedded in other components. * @author RM * */ public class ColorLegend extends VisualizationComponent { /* * GUI elements. * */ /** * Image of color legend. */ private ImageView legend; /** * Label for min. value. */ private Label minLabel; /** * Label for max. value. */ private Label maxLabel; /** * RangeSlider for manually defined cutoff. */ private RangeSlider slider; /** * Rectangle representing border of actual legend. */ private Rectangle legendBorder; /** * Histogram displaying distribution over value range. */ private BarChart<Number, String> histogram; /** * X-axis for prob. dist. barchart. */ private NumberAxis histogram_xAxis; /** * Y-Axis for prob. dist. barchart.. */ private CategoryAxis histogram_yAxis; /* * Data. */ /** * Dataset holding all relevant data. */ private ColorLegendDataset data; /** * Listener to notify once slider value has changed. */ private ITaskListener listener; /* * Metadata. */ private int legendWidth; private int legendHeight; private int legendOffsetX; public ColorLegend(ITaskListener listener) { System.out.println("Creating ColorLegend."); // Remember listener. this.listener = listener; // Initialize root node. initRootNode(); // Initialize labels. initLabels(); // Initialize range slider. initRangeSlider(); // Initialize legend border shape. initLegendBorder(); // Initialize histogram. initHistogram(); // Set preferable width for legend. legendWidth = 7; legendOffsetX = 3; } private void initHistogram() { histogram_xAxis = new NumberAxis(); histogram_yAxis = new CategoryAxis(); histogram = new BarChart<Number, String>(histogram_xAxis, histogram_yAxis); histogram.setAnimated(false); histogram.setLegendVisible(false); histogram.setBackground(Background.EMPTY); histogram_xAxis.setTickMarkVisible(false); histogram_yAxis.setTickMarkVisible(false); histogram_xAxis.setMinorTickVisible(false); // Add to pane. ((AnchorPane) rootNode).getChildren().add(histogram); // Set width. histogram.setPrefWidth(20); // Ensure resizability of barchart. AnchorPane.setTopAnchor(histogram, 0.0); AnchorPane.setBottomAnchor(histogram, 0.0); AnchorPane.setLeftAnchor(histogram, 0.0); AnchorPane.setRightAnchor(histogram, 0.0); } private void initLegendBorder() { legendBorder = new Rectangle(); legendBorder.setStroke(Color.GREY); legendBorder.setFill(Color.TRANSPARENT); } private void initRootNode() { // Create root node. this.rootNode = new AnchorPane(); } private void initRangeSlider() { slider = new RangeSlider(); slider.setMajorTickUnit(5); slider.setMinorTickCount(0); slider.setSnapToTicks(false); slider.setShowTickLabels(false); slider.setShowTickMarks(false); slider.setOrientation(Orientation.VERTICAL); // Initialize event handler. initSliderEventHandler(); } /** * Initializes event handler for slider. */ private void initSliderEventHandler() { // Add listener to refresh during drag. slider.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { refresh(); } }); // Add listener to notify listener after release. slider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { listener.notifyOfTaskCompleted(TaskType.COLOR_LEGEND_MODIFIED); } }); } private void initLabels() { minLabel = new Label(); maxLabel = new Label(); // Add to parent. ((AnchorPane) rootNode).getChildren().add(minLabel); ((AnchorPane) rootNode).getChildren().add(maxLabel); // Set position. minLabel.setLayoutX(20); maxLabel.setLayoutX(20); // Set style. minLabel.setFont(Font.font("Verdana", FontPosture.ITALIC, 9)); maxLabel.setFont(Font.font("Verdana", FontPosture.ITALIC, 9)); } @Override public void initialize(URL arg0, ResourceBundle arg1) { } @Override public void processSelectionManipulationRequest(double minX, double minY, double maxX, double maxY) { } @Override public void processEndOfSelectionManipulation() { } @Override public Pair<Integer, Integer> provideOffsets() { return null; } @Override public void processKeyPressedEvent(KeyEvent ke) { } @Override public void processKeyReleasedEvent(KeyEvent ke) { } /** * Refresh legend using the provided colours and values. * @param data */ public void refresh(ColorLegendDataset data) { this.data = data; // Reset slider to initial values. slider.setHighValue(slider.getMax()); slider.setLowValue(slider.getMin()); // Refresh color legend. this.refresh(); } /** * Update legend after refresh. */ private void updateLegend() { AnchorPane parent = (AnchorPane) rootNode; // Remove old ImageView from root, if one exists. if (legend != null && parent.getChildren().contains(legend)) { // Remove legend. parent.getChildren().remove(legend); } // Calculate percentage of legend selected with slider. double percentageSelected = (slider.getHighValue() - slider.getLowValue()) / (slider.getMax() - slider.getMin()); double legendOffsetY = (slider.getMax() - slider.getHighValue()) / (slider.getMax() - slider.getMin()) * legendHeight; // Create new legend legend = ColorScale.createColorScaleImageView( data.getMin(), data.getMax(), data.getMinColor(), data.getMaxColor(), legendWidth, (int)(legendHeight * percentageSelected), Orientation.VERTICAL); legend.setLayoutX(legendOffsetX); legend.setLayoutY(legendOffsetY); // Add to root. parent.getChildren().add(legend); } /** * Update slider after refresh. */ private void updateSlider() { if ( !((AnchorPane) rootNode).getChildren().contains(slider) ) { // Add to parent. ((AnchorPane) rootNode).getChildren().add(slider); } // Set new values. slider.setMax(data.getMax()); slider.setMin(data.getMin()); // Resize. slider.setPrefHeight(legendHeight); // Push to front. slider.toFront(); } /** * Update labels after refresh. */ private void updateLabels() { // Display extrema in lables. minLabel.setText( String.valueOf(data.getMin())); maxLabel.setText( String.valueOf(data.getMax()).substring(0, 5)); // Reposition labels. minLabel.setLayoutY(legendHeight - 15); maxLabel.setLayoutY(5); } @Override public void refresh() { if (this.data != null) { // Update legend. updateLegend(); // Update labels. updateLabels(); // Update legend border. updateLegendBorder(); // Update slider. updateSlider(); // Update histogram. updateHistogram(); } } /** * Update histogram with new data. */ private void updateHistogram() { // Set new height. histogram.setPrefHeight(legendHeight); // Add data. XYChart.Series<Number, String> series = new XYChart.Series<Number, String>(); series.getData().add(new XYChart.Data<Number, String>(5, "1")); series.getData().add(new XYChart.Data<Number, String>(10, "2")); histogram.getData().clear(); histogram.getData().add(series); } @Override public void initHoverEventListeners() { } @Override public void highlightHoveredOverDataPoints(Set<Integer> dataPointIDs, DatapointIDMode idMode) { } @Override public void removeHoverHighlighting() { } @Override public void resizeContent(double width, double height) { // Resize root node/container. ((AnchorPane)this.rootNode).setPrefSize(width, height); // Remember new height. legendHeight = height > 0 ? (int) height : legendHeight; // Redraw legend. refresh(); } private void updateLegendBorder() { if ( !((AnchorPane) rootNode).getChildren().contains(legendBorder) ) { // Add to parent. ((AnchorPane) rootNode).getChildren().add(legendBorder); } legendBorder.setLayoutX(legendOffsetX); legendBorder.setWidth(legendWidth); legendBorder.setHeight(legendHeight); } @Override protected Map<String, Integer> prepareOptionSet() { return null; } /** * Provide selected extrema. * @return */ public Pair<Double, Double> getSelectedExtrema() { return new Pair<Double, Double>(slider.getLowValue(), slider.getHighValue()); } }
package org.commcare.util.screen; import org.commcare.cases.entity.EntityUtil; import org.commcare.cases.query.QueryContext; import org.commcare.cases.query.queryset.CurrentModelQuerySet; import org.commcare.modern.session.SessionWrapper; import org.commcare.session.CommCareSession; import org.commcare.suite.model.Action; import org.commcare.suite.model.Detail; import org.commcare.suite.model.EntityDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.util.CommCarePlatform; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.trace.EvaluationTraceReporter; import org.javarosa.core.model.trace.ReducingTraceReporter; import org.javarosa.core.model.utils.InstrumentationUtils; import org.javarosa.core.util.NoLocalizedTextException; import org.javarosa.model.xform.XPathReference; import java.util.Hashtable; import java.util.Vector; /** * Compound Screen to select an entity from a list and then display the one or more details that * are associated with the entity. * * Does not currently support tile based selects * * @author ctsims */ public class EntityScreen extends CompoundScreenHost { private TreeReference mCurrentSelection; private SessionWrapper mSession; private CommCarePlatform mPlatform; private Detail mShortDetail; private EntityDatum mNeededDatum; private Action mPendingAction; private Subscreen<EntityScreen> mCurrentScreen; private boolean readyToSkip = false; private EvaluationContext evalContext; private Hashtable<String, TreeReference> referenceMap; private boolean handleCaseIndex; private boolean full = true; private Vector<TreeReference> references; private boolean initialized = false; private Action autoLaunchAction; public EntityScreen(boolean handleCaseIndex) { this.handleCaseIndex = handleCaseIndex; } /** * This constructor allows specifying whether to use the complete init or a minimal one * * @param handleCaseIndex Allow specifying entity by list index rather than unique ID * @param full If set to false, the subscreen and referenceMap, used for * selecting and rendering entity details, will not be created. * This speeds up initialization but makes further selection impossible. */ public EntityScreen(boolean handleCaseIndex, boolean full) { this.handleCaseIndex = handleCaseIndex; this.full = full; } public EntityScreen(boolean handleCaseIndex, boolean full, SessionWrapper session) throws CommCareSessionException { this.handleCaseIndex = handleCaseIndex; this.full = full; this.setSession(session); for (Action action : mShortDetail.getCustomActions(evalContext)) { if (action.isAutoLaunching()) { // Supply an empty case list so we can "select" from it later using getEntityFromID mCurrentScreen = new EntityListSubscreen(mShortDetail, new Vector<TreeReference>(), evalContext, handleCaseIndex); this.autoLaunchAction = action; } } } public void init(SessionWrapper session) throws CommCareSessionException { if (initialized) { return; } this.setSession(session); references = expandEntityReferenceSet(evalContext); //Pulled from NodeEntityFactory. We should likely replace this whole functonality with //that from nodeentityfactory QueryContext newContext = evalContext.getCurrentQueryContext() .checkForDerivativeContextAndReturn(references.size()); newContext.setHackyOriginalContextBody(new CurrentModelQuerySet(references)); evalContext.setQueryContext(newContext); if (full || references.size() == 1) { referenceMap = new Hashtable<>(); for(TreeReference reference: references) { referenceMap.put(getReturnValueFromSelection(reference, (EntityDatum) session.getNeededDatum(), evalContext), reference); } // for now override 'here()' with the coords of Sao Paulo, eventually allow dynamic setting evalContext.addFunctionHandler(new ScreenUtils.HereDummyFunc(-23.56, -46.66)); if (mNeededDatum.isAutoSelectEnabled() && references.size() == 1) { this.setHighlightedEntity(references.firstElement()); if (!this.setCurrentScreenToDetail()) { this.updateSession(session); readyToSkip = true; } } else { mCurrentScreen = new EntityListSubscreen(mShortDetail, references, evalContext, handleCaseIndex); } } initialized = true; } private void setSession(SessionWrapper session) throws CommCareSessionException { SessionDatum datum = session.getNeededDatum(); if (!(datum instanceof EntityDatum)) { throw new CommCareSessionException("Didn't find an entity select action where one is expected."); } mNeededDatum = (EntityDatum)datum; this.mSession = session; this.mPlatform = mSession.getPlatform(); String detailId = mNeededDatum.getShortDetail(); if (detailId == null) { throw new CommCareSessionException("Can't handle entity selection with blank detail definition for datum " + mNeededDatum.getDataId()); } mShortDetail = this.mPlatform.getDetail(detailId); if (mShortDetail == null) { throw new CommCareSessionException("Missing detail definition for: " + detailId); } evalContext = mSession.getEvaluationContext(); } private Vector<TreeReference> expandEntityReferenceSet(EvaluationContext context) { return evalContext.expandReference(mNeededDatum.getNodeset()); } @Override public boolean shouldBeSkipped() { return readyToSkip; } @Override public String getScreenTitle() { try { return mShortDetail.getTitle().evaluate(evalContext).getName(); } catch (NoLocalizedTextException nlte) { return "Select (error with title string)"; } } @Override public Subscreen getCurrentScreen() { return mCurrentScreen; } public static String getReturnValueFromSelection(TreeReference contextRef, EntityDatum needed, EvaluationContext context) { // grab the session's (form) element reference, and load it. TreeReference elementRef = XPathReference.getPathExpr(needed.getValue()).getReference(); AbstractTreeElement element = context.resolveReference(elementRef.contextualize(contextRef)); String value = ""; // get the case id and add it to the intent if (element != null && element.getValue() != null) { value = element.getValue().uncast().getString(); } return value; } @Override protected void updateSession(CommCareSession session) { if (mPendingAction != null) { session.executeStackOperations(mPendingAction.getStackOperations(), evalContext); return; } String selectedValue = this.getReturnValueFromSelection(this.mCurrentSelection, mNeededDatum, evalContext); session.setDatum(mNeededDatum.getDataId(), selectedValue); } public void setHighlightedEntity(TreeReference selection) { this.mCurrentSelection = selection; } public void setHighlightedEntity(String id) throws CommCareSessionException { if (referenceMap == null) { this.mCurrentSelection = mNeededDatum.getEntityFromID(evalContext, id); } else { this.mCurrentSelection = referenceMap.get(id); } if (this.mCurrentSelection == null) { throw new CommCareSessionException("EntityScreen " + this.toString() + " could not select case " + id + "." + " If this error persists please report a bug to CommCareHQ."); } } public boolean setCurrentScreenToDetail() throws CommCareSessionException { Detail[] longDetailList = getLongDetailList(mCurrentSelection); if (longDetailList == null) { return false; } setCurrentScreenToDetail(0); return true; } public void setCurrentScreenToDetail(int index) throws CommCareSessionException { EvaluationContext subContext = new EvaluationContext(evalContext, this.mCurrentSelection); Detail[] longDetailList = getLongDetailList(this.mCurrentSelection); TreeReference detailNodeset = longDetailList[index].getNodeset(); if (detailNodeset != null) { TreeReference contextualizedNodeset = detailNodeset.contextualize(this.mCurrentSelection); this.mCurrentScreen = new EntityListSubscreen(longDetailList[index], subContext.expandReference(contextualizedNodeset), subContext, handleCaseIndex); } else { this.mCurrentScreen = new EntityDetailSubscreen(index, longDetailList[index], subContext, getDetailListTitles(subContext, this.mCurrentSelection)); } } public Detail[] getLongDetailList(TreeReference ref){ Detail[] longDetailList; String longDetailId = this.mNeededDatum.getLongDetail(); if (longDetailId == null) { return null; } Detail d = mPlatform.getDetail(longDetailId); if (d == null) { return null; } EvaluationContext contextForChildDetailDisplayConditions = EntityUtil.prepareCompoundEvaluationContext(ref, d, evalContext); longDetailList = d.getDisplayableChildDetails(contextForChildDetailDisplayConditions); if (longDetailList == null || longDetailList.length == 0) { longDetailList = new Detail[]{d}; } return longDetailList; } public String[] getDetailListTitles(EvaluationContext subContext, TreeReference reference) { Detail[] mLongDetailList = getLongDetailList(reference); String[] titles = new String[mLongDetailList.length]; for (int i = 0; i < mLongDetailList.length; ++i) { titles[i] = mLongDetailList[i].getTitle().getText().evaluate(subContext); } return titles; } public void setPendingAction(Action pendingAction) { this.mPendingAction = pendingAction; } public Detail getShortDetail(){ return mShortDetail; } public SessionWrapper getSession() { return mSession; } public void printNodesetExpansionTrace(EvaluationTraceReporter reporter) { evalContext.setDebugModeOn(reporter); this.expandEntityReferenceSet(evalContext); InstrumentationUtils.printAndClearTraces(reporter, "Entity Nodeset"); } public TreeReference resolveTreeReference(String reference) { return referenceMap.get(reference); } public EvaluationContext getEvalContext() { return evalContext; } public TreeReference getCurrentSelection() { return mCurrentSelection; } public Vector<TreeReference> getReferences() { return references; } public Action getAutoLaunchAction() { return autoLaunchAction; } @Override public String toString() { return "EntityScreen [Detail=" + mShortDetail + ", selection=" + mCurrentSelection + "]"; } // Used by Formplayer @SuppressWarnings("unused") public Hashtable<String, TreeReference> getReferenceMap() { return referenceMap; } }
package com.akjava.gwt.androidhtml5.client; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.akjava.gwt.androidhtml5.client.data.ImageElementData; import com.akjava.gwt.html5.client.download.HTML5Download; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FilePredicates; import com.akjava.gwt.html5.client.file.FileUploadForm; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.html5.client.file.FileUtils.DataURLListener; import com.akjava.gwt.html5.client.file.ui.DropDockDataUrlRootPanel; import com.akjava.gwt.html5.client.input.ColorBox; import com.akjava.gwt.lib.client.CanvasPaintUtils; import com.akjava.gwt.lib.client.CanvasUtils; import com.akjava.gwt.lib.client.ImageElementListener; import com.akjava.gwt.lib.client.ImageElementLoader; import com.akjava.gwt.lib.client.ImageElementUtils; import com.akjava.gwt.lib.client.LogUtils; import com.akjava.gwt.lib.client.StorageControler; import com.akjava.gwt.lib.client.StorageException; import com.akjava.gwt.lib.client.canvas.Rect; import com.akjava.gwt.lib.client.widget.cell.ButtonColumn; import com.akjava.gwt.lib.client.widget.cell.EasyCellTableObjects; import com.akjava.gwt.lib.client.widget.cell.SimpleCellTable; import com.akjava.lib.common.io.FileType; import com.google.common.base.Ascii; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.Context2d.Composite; import com.google.gwt.canvas.dom.client.Context2d.LineJoin; import com.google.gwt.canvas.dom.client.TextMetrics; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.ErrorEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.text.shared.Renderer; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.DeckLayoutPanel; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.IntegerBox; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.ValueListBox; import com.google.gwt.user.client.ui.VerticalPanel; public class ExportImage extends Html5DemoEntryPoint { public final String KEY_BASE_NAME="exportimage_key_basename"; public final String KEY_BASE_PATH="exportimage_key_basepath"; public final String KEY_USE_MARKED="exportimage_key_usemarked"; public final String KEY_FONT="exportimage_key_font"; public final String KEY_TEXT_COLOR="exportimage_key_text_color"; public final String KEY_BG_COLOR="exportimage_key_bg_color"; public final String KEY_BG_DIAMETER="exportimage_key_bg_diameter"; public final String KEY_BG_TYPE="exportimage_key_bg_type"; public final int BG_TYPE_SQUARE=0; public final int BG_TYPE_CIRCLE=1; public final int BG_TYPE_NONE=2; //public final int BG_TYPE_TRANSPARENT_SQUARE=3; public static final int MODE_ERASE=0; public static final int MODE_COLOR=3; public static final int MODE_NUMBER=4; private int penMode=MODE_COLOR; private DockLayoutPanel dock; private HorizontalPanel topPanel; private EasyCellTableObjects<ImageElementCaptionData> easyCellTableObjects; private TextBox pathBox; private StorageControler storageControler=new StorageControler(); private int penSize=4; private ColorBox colorPicker; @Override public Panel initializeWidget() { root=new DropDockDataUrlRootPanel(Unit.PX,false){ @Override public void loadFile(String pareht, Optional<File> optional, String dataUrl) { for(File file:optional.asSet()){ ExportImage.this.loadFile(file, dataUrl); } } }; root.setFilePredicate(FilePredicates.getImageExtensionOnly()); dock = new DockLayoutPanel(Unit.PX); root.add(dock); topPanel = new HorizontalPanel(); topPanel.setWidth("100%"); topPanel.setStylePrimaryName("bg1"); topPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); topPanel.setSpacing(1); dock.addNorth(topPanel,30); topPanel.add(createTitleWidget()); topPanel.add(new Anchor(textConstants.Help(), "exportimage_help.html")); topPanel.add(createSettingAnchor()); VerticalPanel controler=new VerticalPanel(); controler.setSpacing(1); FileUploadForm upload=FileUtils.createSingleFileUploadForm(new DataURLListener() { @Override public void uploaded(File file, String value) { loadFile(file, value); } }, true,false);//base component catch everything HorizontalPanel fileUps=new HorizontalPanel(); controler.add(fileUps); fileUps.add(upload); HorizontalPanel clearAllPanel=new HorizontalPanel(); controler.add(clearAllPanel); //size choose HorizontalPanel sizes=new HorizontalPanel(); sizes.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); controler.add(sizes); Label penSizeLabel=new Label(textConstants.Pen_Size()); sizes.add(penSizeLabel); final ValueListBox<Integer> sizeListBox=new ValueListBox<Integer>(new Renderer<Integer>() { @Override public String render(Integer object) { // TODO Auto-generated method stub return ""+object; } @Override public void render(Integer object, Appendable appendable) throws IOException { // TODO Auto-generated method stub } }); List<Integer> sizeList=Lists.newArrayList(1,2,3,4,5,6,8,12,16,24,32,48,64); sizeListBox.setValue(penSize); sizeListBox.setAcceptableValues(sizeList); sizeListBox.addValueChangeHandler(new ValueChangeHandler<Integer>() { @Override public void onValueChange(ValueChangeEvent<Integer> event) { penSize=event.getValue(); } }); sizes.add(sizeListBox); HorizontalPanel pens=new HorizontalPanel(); pens.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE); sizes.add(pens); colorPicker = new ColorBox(); colorPicker.setValue("#ff0000"); pens.add(colorPicker); final RadioButton eraseR=new RadioButton("pens"); eraseR.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { penMode=MODE_ERASE; } }); pens.add(eraseR); pens.add(new Label(textConstants.Erase())); RadioButton pickR=new RadioButton("pens"); pens.add(pickR); pens.add(new Label(textConstants.Draw())); pickR.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { penMode=MODE_COLOR; } }); pickR.setValue(true); RadioButton pickNumber=new RadioButton("pens"); pens.add(pickNumber); pens.add(new Label(textConstants.Number())); pickNumber.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { penMode=MODE_NUMBER; } }); numberBox = new ListBox(); for(int i=0;i<=20;i++){ numberBox.addItem(""+i); } sizes.add(numberBox); numberBox.setSelectedIndex(1); Button clearNumber=new Button("x",new ClickHandler() { @Override public void onClick(ClickEvent event) { clearNumber(); } }); sizes.add(clearNumber); Button clearLinesBt=new Button(textConstants.Clear_Lines(),new ClickHandler() { @Override public void onClick(ClickEvent event) { if(selection==null){ return; } CanvasUtils.clear(selection.getImageCanvas()); updateCanvas(); } }); clearAllPanel.add(clearLinesBt); Button clearNumbersBt=new Button(textConstants.Clear_Numbers(),new ClickHandler() { @Override public void onClick(ClickEvent event) { if(selection==null){ return; } getCurrentNumbers().clear(); updateCanvas(); } }); clearAllPanel.add(clearNumbersBt); Button clearBt=new Button(textConstants.Clear_All(),new ClickHandler() { @Override public void onClick(ClickEvent event) { if(selection==null){ return; } CanvasUtils.clear(selection.getImageCanvas()); getCurrentNumbers().clear(); updateCanvas(); } }); clearAllPanel.add(clearBt); HorizontalPanel namePanel=new HorizontalPanel(); namePanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); namePanel.add(new Label(textConstants.BaseName())); nameBox = new TextBox(); namePanel.add(nameBox); nameBox.setValue(storageControler.getValue(KEY_BASE_NAME, "image")); Button updateBt=new Button(textConstants.update(),new ClickHandler() { @Override public void onClick(ClickEvent event) { updateList(); try { storageControler.setValue(KEY_BASE_NAME, nameBox.getValue()); } catch (StorageException e) { // TODO Auto-generated catch block e.printStackTrace(); Window.alert(e.getMessage()); } } }); namePanel.add(updateBt); controler.add(namePanel); HorizontalPanel dirPanel=new HorizontalPanel(); dirPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); dirPanel.add(new Label(textConstants.ImagePath())); pathBox = new TextBox(); dirPanel.add(pathBox); pathBox.setValue(storageControler.getValue(KEY_BASE_PATH, "/img/")); Button update3Bt=new Button(textConstants.update(),new ClickHandler() { @Override public void onClick(ClickEvent event) { updateList(); try { storageControler.setValue(KEY_BASE_PATH, pathBox.getValue()); } catch (StorageException e) { // TODO Auto-generated catch block e.printStackTrace(); Window.alert(e.getMessage()); } } }); dirPanel.add(update3Bt); markedCheck = new CheckBox(textConstants.use_marked()); markedCheck.setValue(storageControler.getValue(KEY_USE_MARKED, false)); markedCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { try { storageControler.setValue(KEY_USE_MARKED, event.getValue()); } catch (StorageException e) { // TODO Auto-generated catch block e.printStackTrace(); } updateMarkedText(); } }); dirPanel.add(markedCheck); controler.add(dirPanel); HorizontalPanel captionPanel=new HorizontalPanel(); captionPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); captionPanel.add(new Label(textConstants.Image_Caption())); markedTextArea = new TextArea(); markedTextArea.setSize("350px", "180px"); controler.add(markedTextArea); SimpleCellTable<ImageElementCaptionData> cellTable = new SimpleCellTable<ImageElementCaptionData>(999) { @Override public void addColumns(CellTable<ImageElementCaptionData> table) { ButtonColumn<ImageElementCaptionData> removeBtColumn=new ButtonColumn<ImageElementCaptionData>() { @Override public void update(int index, ImageElementCaptionData object, String value) { easyCellTableObjects.removeItem(object); } @Override public String getValue(ImageElementCaptionData object) { return "X"; } }; table.addColumn(removeBtColumn); TextColumn<ImageElementCaptionData> fileInfoColumn = new TextColumn<ImageElementCaptionData>() { public String getValue(ImageElementCaptionData value) { return Ascii.truncate(value.getCaption()+" "+value.getFileName(), 8, ".."); } }; table.addColumn(fileInfoColumn,textConstants.Name()); table.addColumn(new ActionCellGenerator<ImageElementCaptionData>(){ @Override public void executeAt(int index,ImageElementCaptionData object) { if(index==0){ easyCellTableObjects.upItem(object); }else{ easyCellTableObjects.downItem(object); } updateMarkedText(); } }.generateColumn(Lists.newArrayList(textConstants.UP(),textConstants.DOWN()))); //if use downloa here need update every mouse-up event,it's really slow /* HtmlColumn<ImageElementCaptionData> downloadColumn=new HtmlColumn<ImageElementCaptionData> (new SafeHtmlCell()){ @Override public String toHtml(ImageElementCaptionData data) { String extension=FileUtils.getExtension(data.getFileName()); FileType fileType=FileType.getFileTypeByExtension(extension); if(fileType==null){ return ""; } int index=easyCellTableObjects.getDatas().indexOf(data)+1;//start 0 Anchor anchor=HTML5Download.get().generateBase64DownloadLink(data.getDataUrl(), fileType.getMimeType(), nameBox.getValue()+index+"."+extension, "Download" , false); anchor.setStylePrimaryName("bt"); return anchor.toString(); //return data.getDownloadLink().toString(); } }; table.addColumn(downloadColumn); */ table.addColumn(new ButtonColumn<ExportImage.ImageElementCaptionData>() { @Override public void update(int index, ImageElementCaptionData data, String value) { downloadLinks.clear(); String extension=FileUtils.getExtension(data.getFileName()); FileType fileType=FileType.getFileTypeByExtension(extension); if(fileType==null){ //return ""; } int imgIndex=easyCellTableObjects.getDatas().indexOf(data)+1;//start 0 drawCanvas(data);//need redraw here.because when pushed button's row is not selected,doSelect called after update and canvas was not drawed. String name=nameBox.getValue()+imgIndex+"."+extension; Anchor anchor=HTML5Download.get().generateBase64DownloadLink(canvas.toDataUrl(), fileType.getMimeType(),name, name , true); //anchor.setStylePrimaryName("bt"); downloadLinks.add(anchor); } @Override public String getValue(ImageElementCaptionData object) { // TODO Auto-generated method stub return textConstants.updateimage(); } }); } }; imageCaptionBox = new TextBox(); imageCaptionBox.setEnabled(false); captionPanel.add(imageCaptionBox); imageCaptionBox.setWidth("200px"); Button update2Bt=new Button(textConstants.update(),new ClickHandler() { @Override public void onClick(ClickEvent event) { updateCaption(); } }); captionPanel.add(update2Bt); controler.add(captionPanel); downloadLinks = new HorizontalPanel(); controler.add(downloadLinks); eastPanel = new DockLayoutPanel(Unit.PX); eastPanel.addNorth(controler, 400); ScrollPanel cellScroll=new ScrollPanel(); cellScroll.setSize("100%", "100%"); cellTable.setWidth("100%"); cellScroll.add(cellTable); easyCellTableObjects=new EasyCellTableObjects<ImageElementCaptionData>(cellTable,false) { @Override public void onSelect(ImageElementCaptionData selection) { doSelect(selection); } }; eastPanel.add(cellScroll); dock.addEast(eastPanel, 400); mainScrollPanel = new ScrollPanel(); mainScrollPanel.setWidth("100%"); mainScrollPanel.setHeight("100%"); canvas = Canvas.createIfSupported(); mainPanel = new DeckLayoutPanel(); //mainPanel.setSize("100%", "100%"); dock.add(mainPanel); mainPanel.add(canvas); mainPanel.showWidget(0); //can i this with event-bus? moveControler = new CanvasDragMoveControler(canvas, new MoveListener() { int shiftDownX; int shiftDownY; boolean firstDraged; boolean horizontalOnly; @Override public void start(int sx, int sy) { // TODO Auto-generated method stub if(penMode==MODE_NUMBER){ if(moveControler.isShiftKeyDown()){ int selection=numberBox.getSelectedIndex(); if(selection<numberBox.getItemCount()-1){ numberBox.setSelectedIndex(selection+1); } } NumberData number=new NumberData(numberBox.getSelectedIndex()); number.setX(sx); number.setY(sy); addNumberToCurrent(number); updateCanvas(); }else if(penMode==MODE_COLOR){ shiftDownX=sx; shiftDownY=sy; firstDraged=false; } } @Override public void dragged(int startX, int startY, int endX, int endY, int vectorX, int vectorY) { if(selection==null){ return; } if(penMode==MODE_COLOR){ //one direction if(moveControler.isShiftKeyDown()){ if(!firstDraged){ if(vectorX>vectorY){ horizontalOnly=true; }else{ horizontalOnly=false; } firstDraged=true; } if(horizontalOnly){ startY=shiftDownY; endY=shiftDownY; }else{ startX=shiftDownX; endX=shiftDownX; } }else{ shiftDownX=endX; shiftDownY=endY; //for next shift down } drawLine(startX,startY,endX,endY,colorPicker.getValue()); }else if(penMode==MODE_ERASE){ erase(startX,startY,endX,endY); }else{ return; } updateCanvas(); } @Override public void end(int sx, int sy) { } }); return root; } protected void clearNumber() { removeNumberToCurrent(new NumberData(numberBox.getSelectedIndex())); updateCanvas(); } private IntegerBox makeIntegerBox(Panel parent,String name,int value){ HorizontalPanel h1=new HorizontalPanel(); //h.setWidth("100%"); parent.add(h1); Label label=new Label(name); label.setWidth("100px"); h1.add(label); IntegerBox box=new IntegerBox(); box.setWidth("40px"); box.setValue(value); h1.add(box); return box; } private TextBox makeTextBox(Panel parent,String name,String value){ HorizontalPanel h=new HorizontalPanel(); parent.add(h); Label label=new Label(name); label.setWidth("100px"); h.add(label); TextBox box=new TextBox(); box.setValue(value); h.add(box); return box; } private ColorBox makeColorBox(Panel parent,String name,String value){ HorizontalPanel h=new HorizontalPanel(); parent.add(h); Label label=new Label(name); label.setWidth("100px"); h.add(label); ColorBox box=new ColorBox(); box.setValue(value); h.add(box); return box; } private class BGType{ private int type; public BGType(int type, String label) { super(); this.type = type; this.label = label; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } private String label; } @Override public Panel createMainSettingPage(){ VerticalPanel panel=new VerticalPanel(); HTML html=new HTML("<h3>"+textConstants.Number()+"</h3>"); panel.add(html); fontBox = makeTextBox(panel,textConstants.font(),storageControler.getValue(KEY_FONT,"16px Audiowide")); textColorBox = makeColorBox(panel,textConstants.textcolor(),storageControler.getValue(KEY_TEXT_COLOR, "#000000")); bgColorBox = makeColorBox(panel,textConstants.bgcolor(),storageControler.getValue(KEY_BG_COLOR, "#ff0000")); digimeterBox = makeIntegerBox(panel, textConstants.digimeter(), storageControler.getValue(KEY_BG_DIAMETER, 24)); final List<BGType> types=Lists.newArrayList(new BGType(BG_TYPE_SQUARE, textConstants.square()), new BGType(BG_TYPE_CIRCLE, textConstants.circle()), new BGType(BG_TYPE_NONE, textConstants.none()) ); int selection=storageControler.getValue(KEY_BG_TYPE, 0); BGType bgtype=null; for(BGType type:types){ if(type.getType()==selection){ bgtype=type; break; } } if(bgtype==null){ bgtype=types.get(0); } bgTypeBox = new ValueListBox<ExportImage.BGType>(new Renderer<BGType>() { @Override public String render(BGType object) { return object.getLabel(); } @Override public void render(BGType object, Appendable appendable) throws IOException { // TODO Auto-generated method stub } }); bgTypeBox.setValue(bgtype); bgTypeBox.setAcceptableValues(types); HorizontalPanel h1=new HorizontalPanel(); panel.add(h1); Label label=new Label(textConstants.bgtype()); label.setWidth("100px"); h1.add(label); h1.add(bgTypeBox); Button resetBt=new Button(textConstants.reset(),new ClickHandler() { @Override public void onClick(ClickEvent event) { fontBox.setValue("16px Audiowide"); textColorBox.setValue("#000000"); bgColorBox.setValue("#ff0000"); digimeterBox.setValue(24); bgTypeBox.setValue(types.get(0)); } }); panel.add(resetBt); //TODO create list box //valuelistbox return panel; } private void addNumberToCurrent(NumberData data){ if(selection==null){ return; } List<NumberData> numbers=selection.getNumbers(); int index=numbers.indexOf(data); if(index!=-1){ numbers.get(index).setX(data.getX()); numbers.get(index).setY(data.getY()); }else{ numbers.add(data); } } private void removeNumberToCurrent(NumberData data){ if(selection==null){ return; } List<NumberData> numbers=selection.getNumbers(); numbers.remove(data); } private List<NumberData> getCurrentNumbers(){ if(selection==null){ return null; } List<NumberData> numbers=selection.getNumbers(); return numbers; } private class NumberData{ int x; int y; int number; public NumberData(int number) { super(); this.number = number; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getNumber() { return number; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + number; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberData other = (NumberData) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (number != other.number) return false; return true; } private ExportImage getOuterType() { return ExportImage.this; } } private void erase(int x1,int y1,int x2,int y2){ Canvas imageCanvas=selection.getImageCanvas(); imageCanvas.getContext2d().save(); imageCanvas.getContext2d().setLineWidth(penSize*2); imageCanvas.getContext2d().setLineJoin(LineJoin.ROUND); imageCanvas.getContext2d().setStrokeStyle("#000"); imageCanvas.getContext2d().setGlobalCompositeOperation("destination-out"); imageCanvas.getContext2d().beginPath(); imageCanvas.getContext2d().moveTo(x1,y1); imageCanvas.getContext2d().lineTo(x2,y2); imageCanvas.getContext2d().closePath(); imageCanvas.getContext2d().stroke(); imageCanvas.getContext2d().restore(); } private void drawLine(int x1,int y1,int x2,int y2,String color){ //LogUtils.log("drawLine-before:"+canvas.getContext2d().getGlobalCompositeOperation()); Canvas ImageCanvas=selection.getImageCanvas(); ImageCanvas.getContext2d().save(); ImageCanvas.getContext2d().setLineWidth(penSize); ImageCanvas.getContext2d().setLineJoin(LineJoin.ROUND); ImageCanvas.getContext2d().setStrokeStyle(color); ImageCanvas.getContext2d().setGlobalCompositeOperation(Composite.SOURCE_OVER); ImageCanvas.getContext2d().beginPath(); ImageCanvas.getContext2d().moveTo(x1,y1); ImageCanvas.getContext2d().lineTo(x2,y2); ImageCanvas.getContext2d().closePath(); ImageCanvas.getContext2d().stroke(); ImageCanvas.getContext2d().restore(); //LogUtils.log("drawLine-after:"+canvas.getContext2d().getGlobalCompositeOperation()); } private String toImageFileName(ImageElementCaptionData data){ String extension=FileUtils.getExtension(data.getFileName()); FileType fileType=FileType.getFileTypeByExtension(extension); if(fileType==null){ return ""; } int index=easyCellTableObjects.getDatas().indexOf(data)+1;//start 0 return nameBox.getText()+index+"."+extension; } protected void updateCaption() { if(selection!=null){ selection.setCaption(imageCaptionBox.getText()); int index=easyCellTableObjects.getDatas().indexOf(selection); easyCellTableObjects.getSimpleCellTable().getCellTable().redrawRow(index); } updateMarkedText(); } private void updateMarkedText() { String result=""; for(ImageElementCaptionData data:easyCellTableObjects.getDatas()){ String image=toImageFileName(data); result+=data.getCaption()+"\n"; result+="\n"; if(markedCheck.getValue()){ result+="![]("+pathBox.getValue()+image+")\n"; }else{ result+=""+pathBox.getValue()+image+"\n"; } result+="\n"; result+="\n"; } markedTextArea.setText(result); } public class ImageElementCaptionData extends ImageElementData{ private String caption; private Canvas imageCanvas; private List<NumberData> numbers=new ArrayList<ExportImage.NumberData>(); public List<NumberData> getNumbers() { return numbers; } public Canvas getImageCanvas() { return imageCanvas; } public void setImageCanvas(Canvas imageCanvas) { this.imageCanvas = imageCanvas; } public String getCaption() { if(caption==null){ return ""; } return caption; } public void setCaption(String caption) { this.caption = caption; } public ImageElementCaptionData(String fileName, ImageElement imageElement, String dataUrl) { super(fileName, imageElement, dataUrl); imageCanvas=CanvasUtils.createCanvas(imageElement.getWidth(), imageElement.getHeight()); } } protected void updateList() { easyCellTableObjects.update(); updateMarkedText(); } protected void loadFile(final File file,final String asStringText) { try{ //TODO create method //ImageElement element=ImageElementUtils.create(asStringText); new ImageElementLoader().load(asStringText, new ImageElementListener() { @Override public void onLoad(ImageElement element) { final ImageElementCaptionData data=new ImageElementCaptionData(file.getFileName(),element,asStringText); easyCellTableObjects.addItem(data); //updateList(); //stack on mobile,maybe because of called async method Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { easyCellTableObjects.setSelected(data, true); updateMarkedText(); } }); } @Override public void onError(String url, ErrorEvent event) { Window.alert(event.toDebugString()); } }); //doSelecct(data);//only way to update on Android Chrome }catch (Exception e) { e.printStackTrace(); LogUtils.log(e.getMessage()); } } ImageElementCaptionData selection; private ScrollPanel mainScrollPanel; private DockLayoutPanel eastPanel; private DropDockDataUrlRootPanel root; private DeckLayoutPanel mainPanel; public void doSelect(ImageElementCaptionData selection) { this.selection=selection; if(selection==null){ imageCaptionBox.setEnabled(false); imageCaptionBox.setValue(""); }else{ imageCaptionBox.setEnabled(true); imageCaptionBox.setValue(selection.getCaption()); } updateCanvas(); updateMarkedText(); } private void updateCanvas(){ if(selection==null){ CanvasUtils.clear(canvas); }else{ drawCanvas(selection); } } /* * must draw based on ImageElementCaptionData data */ private void drawCanvas(ImageElementCaptionData data){ ImageElementUtils.copytoCanvas(data.getImageElement(), canvas); canvas.getContext2d().drawImage(data.getImageCanvas().getCanvasElement(), 0, 0); if(data.getNumbers()!=null){ for(NumberData number:data.getNumbers()){ double r=(double)digimeterBox.getValue()/2; double dx=(double)number.getX()-r; double dy=(double)number.getY()-r; double w=r*2; double h=r*2; Rect rect=new Rect((int)dx, (int)dy, (int)w, (int)h); if(bgTypeBox.getValue().getType()==BG_TYPE_SQUARE){ canvas.getContext2d().setFillStyle(bgColorBox.getValue()); canvas.getContext2d().fillRect(dx, dy, w, h); }else if(bgTypeBox.getValue().getType()==BG_TYPE_CIRCLE){ canvas.getContext2d().setFillStyle(bgColorBox.getValue()); CanvasPaintUtils.drawCircleInRect(canvas, (int)dx, (int)dy,(int) w,(int) h, true, true); }else{//none } //set font? canvas.getContext2d().setFont(fontBox.getText()); canvas.getContext2d().setFillStyle(textColorBox.getValue());//TODO text-picker drawCenterInRect(canvas, ""+number.getNumber(), rect); } } } //TODO replace common public static void drawCenterInRect(Canvas canvas,String text,Rect rect){ canvas.getContext2d().save(); TextMetrics metrix=canvas.getContext2d().measureText(text); int dx=(int) ((rect.getWidth()-metrix.getWidth())/2); int dy=rect.getHeight()/2; //int size=parseFontSize(canvas.getContext2d().getFont()); //double descentOffset=(double)size/4; offset no need anymore canvas.getContext2d().setTextBaseline("middle"); canvas.getContext2d().fillText(text, rect.getX()+dx, rect.getY()+dy); canvas.getContext2d().restore(); } @Override public void onCloseSettingPanel(){ try { //number settings storageControler.setValue(KEY_FONT, fontBox.getValue()); storageControler.setValue(KEY_TEXT_COLOR, textColorBox.getValue()); storageControler.setValue(KEY_BG_COLOR, bgColorBox.getValue()); storageControler.setValue(KEY_BG_DIAMETER, digimeterBox.getValue()); storageControler.setValue(KEY_BG_TYPE, bgTypeBox.getValue().getType()); } catch (StorageException e) { LogUtils.log(e.getMessage()); //TODO } updateCanvas();//possible number-settings changed. } private ListBox sizeBox; private TextBox nameBox; private TextBox imageCaptionBox; private TextArea markedTextArea; private Canvas canvas; private HorizontalPanel downloadLinks; private CheckBox markedCheck; private CanvasDragMoveControler moveControler; private ListBox numberBox; private ValueListBox<BGType> bgTypeBox; private IntegerBox digimeterBox; private ColorBox bgColorBox; private ColorBox textColorBox; private TextBox fontBox; @Override public String getAppName() { return textConstants.ExportImage(); } @Override public String getAppVersion() { return "1.0"; } @Override public Panel getLinkContainer() { return topPanel; } @Override public String getAppUrl() { return "http://android.akjava.com/html5apps/index.html#exportimage"; } }
package com.arcusweather.forecastio; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ForecastIOResponse { private ForecastIOCurrently mOutputCurrently; private ForecastIOMinutely mOutputMinutely; private ForecastIOHourly mOutputHourly; private ForecastIODaily mOutputDaily; private ForecastIOAlerts mOutputAlerts; private ForecastIOFlags mOutputFlags; private String latitude; private String longitude; private String timezone; private String offset; public ForecastIOResponse(String responseString) { JSONObject forecastJsonObject = null; try { forecastJsonObject = new JSONObject(responseString); } catch (JSONException e) { return; } try { latitude = forecastJsonObject.getString("latitude"); } catch (JSONException e) { } try { longitude = forecastJsonObject.getString("longitude"); } catch (JSONException e) { } try { timezone = forecastJsonObject.getString("timezone"); } catch (JSONException e) { } try { offset = forecastJsonObject.getString("offset"); } catch (JSONException e) { } try { JSONObject currentlyJSONObject = forecastJsonObject.getJSONObject("currently"); mOutputCurrently = buildForecastIOCurrently(currentlyJSONObject); } catch (JSONException e) { } try { JSONObject minutelyJSONObject = forecastJsonObject.getJSONObject("minutely"); mOutputMinutely = buildForecastIOMinutely(minutelyJSONObject); } catch (JSONException e) { } try { JSONObject hourlyJSONObject = forecastJsonObject.getJSONObject("hourly"); mOutputHourly = buildForecastIOHourly(hourlyJSONObject); } catch (JSONException e) { } try { JSONObject dailyJSONObject = forecastJsonObject.getJSONObject("daily"); mOutputDaily = buildForecastIODaily(dailyJSONObject); } catch (JSONException e) { } try { JSONArray alertsJSONArray = forecastJsonObject.getJSONArray("alerts"); mOutputAlerts = buildForecastIOAlerts(alertsJSONArray); } catch (JSONException e) { } try { JSONObject flagsJSONObject = forecastJsonObject.getJSONObject("flags"); mOutputFlags = buildForecastIOFlags(flagsJSONObject); } catch (JSONException e) { } } public String getValue(String keyString) { String[] fields = keyString.split("-"); String level = fields[0]; String value = null; try { if(level.equals(new String("latitude"))) { value = latitude; } else if(level.equals(new String("longitude"))) { value = longitude; } else if(level.equals(new String("timezone"))) { value = timezone; } else if(level.equals(new String("offset"))) { value = offset; } else if(level.equals(new String("currently"))) { value = getCurrently().getValue(fields[1]); } else if(level.equals(new String("minutely"))) { try { int listIndex = Integer.parseInt(fields[1]); value = getMinutely().getData()[listIndex].getValue(fields[2]); } catch(NumberFormatException e) { value = getMinutely().getValue(fields[1]); } } else if(level.equals(new String("hourly"))) { try { int listIndex = Integer.parseInt(fields[1]); value = getHourly().getData()[listIndex].getValue(fields[2]); } catch(NumberFormatException e) { value = getHourly().getValue(fields[1]); } } else if(level.equals(new String("daily"))) { try { int listIndex = Integer.parseInt(fields[1]); value = getDaily().getData()[listIndex].getValue(fields[2]); } catch(NumberFormatException e) { value = getDaily().getValue(fields[1]); } } else if(level.equals(new String("alerts"))) { try { int listIndex = Integer.parseInt(fields[1]); value = getAlerts().getData()[listIndex].getValue(fields[2]); } catch(NumberFormatException e) { value = getAlerts().getData()[0].getValue(fields[1]); } } else if(level.equals(new String("flags"))) { value = getFlags().getValue(fields[1]); } } catch(NullPointerException e) { return null; } return value; } public ForecastIODataPoint[] getDataPoints(String keyString) { ForecastIODataPoint[] value = null; try { if(keyString == "minutely") { value = getMinutely().getData(); } else if(keyString == "hourly") { value = getHourly().getData(); } else if(keyString == "daily") { value = getDaily().getData(); } } catch(NullPointerException e) { return null; } return value; } public ForecastIOCurrently getCurrently() { return mOutputCurrently; } public ForecastIOCurrently buildForecastIOCurrently(JSONObject forecastJsonObject) { return new ForecastIOCurrently(forecastJsonObject); } public ForecastIOMinutely getMinutely() { return mOutputMinutely; } public ForecastIOMinutely buildForecastIOMinutely(JSONObject forecastJsonObject) { return new ForecastIOMinutely(forecastJsonObject); } public ForecastIOHourly getHourly() { return mOutputHourly; } public ForecastIOHourly buildForecastIOHourly(JSONObject forecastJsonObject) { return new ForecastIOHourly(forecastJsonObject); } public ForecastIODaily getDaily() { return mOutputDaily; } public ForecastIODaily buildForecastIODaily(JSONObject forecastJsonObject) { return new ForecastIODaily(forecastJsonObject); } public ForecastIOAlerts getAlerts() { return mOutputAlerts; } public ForecastIOAlerts buildForecastIOAlerts(JSONArray forecastJsonArray) { return new ForecastIOAlerts(forecastJsonArray); } public ForecastIOFlags getFlags() { return mOutputFlags; } public ForecastIOFlags buildForecastIOFlags(JSONObject forecastJsonObject) { return new ForecastIOFlags(forecastJsonObject); } }
package com.ecyrd.jspwiki.filters; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import org.apache.xmlrpc.*; import java.net.URL; import java.net.MalformedURLException; import java.util.Vector; import java.util.Hashtable; import org.apache.log4j.Category; /** * A very dumb class that pings weblogs.com on each save. INTERNAL USE ONLY SO FAR! * Look, but don't use as-is. */ // FIXME: Needs to figure out when only weblogs have been saved. // FIXME: rpc endpoint must be configurable // FIXME: Should really be settable per-page. // FIXME: Weblog name has been set to stone public class PingWeblogsComFilter extends BasicPageFilter { static Category log = Category.getInstance( PingWeblogsComFilter.class ); public void postSave( WikiContext context, String pagecontent ) { String blogName = context.getPage().getName(); WikiEngine engine = context.getEngine(); int blogentryTxt = blogName.indexOf("_blogentry_"); if( blogentryTxt == -1 ) { return; // This is not a weblog entry. } blogName = blogName.substring( blogentryTxt ); if( blogName.equals( engine.getFrontPage() ) ) { blogName = null; } try { XmlRpcClient xmlrpc = new XmlRpcClient("http://rpc.weblogs.com/RPC2"); Vector params = new Vector(); params.addElement( "The Butt Ugly Weblog" ); params.addElement( engine.getViewURL(blogName) ); log.debug("Pinging weblogs.com with URL: "+engine.getViewURL(blogName)); xmlrpc.executeAsync("weblogUpdates.ping", params, new AsyncCallback() { public void handleError( Exception ex, URL url, String method ) { log.error("Unable to execute weblogs.com ping to URL: "+url.toString(),ex); } public void handleResult( Object result, URL url, String method ) { Hashtable res = (Hashtable) result; Boolean flerror = (Boolean)res.get("flerror"); String msg = (String)res.get("message"); if( flerror == Boolean.TRUE ) { log.error("Failed to ping: "+msg); } log.info("Weblogs.com has been pinged."); } } ); } catch( MalformedURLException e ) { log.error("Malformed URL",e); } } }
package cn.cerc.ui.core; public interface IOriginOwner { void setOrigin(Object origin); Object getOrigin(); }
package com.ggstudios.lolcraft; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Color; import android.util.Log; import android.util.SparseIntArray; import com.ggstudios.lolcraft.ChampionInfo.Skill; import com.ggstudios.utils.DebugLog; import com.google.gson.Gson; /** * Class that holds information about a build, such as build order, stats and cost. */ public class Build { private static final String TAG = "Build"; public static final int RUNE_TYPE_RED = 0; public static final int RUNE_TYPE_BLUE = 1; public static final int RUNE_TYPE_YELLOW = 2; public static final int RUNE_TYPE_BLACK = 3; public static final double MAX_ATTACK_SPEED = 2.5; public static final double MAX_CDR = 0.4; private static final int[] RUNE_COUNT_MAX = new int[] { 9, 9, 9, 3 }; private static final int[] GROUP_COLOR = new int[] { 0xff2ecc71, // emerald //0xffe74c3c, // alizarin 0xff3498db, // peter river 0xff9b59b6, // amethyst 0xffe67e22, // carrot 0xff34495e, // wet asphalt 0xff1abc9c, // turquoise 0xfff1c40f, // sun flower }; private static final int FLAG_SCALING = 0x80000000; public static final String SN_NULL = "null"; public static final int STAT_NULL = 0; public static final int STAT_HP = 1; public static final int STAT_HPR = 2; public static final int STAT_MP = 3; public static final int STAT_MPR = 4; public static final int STAT_AD = 5; //public static final int STAT_BASE_AS = asdf; public static final int STAT_ASP = 6; public static final int STAT_AR = 7; public static final int STAT_MR = 8; public static final int STAT_MS = 9; public static final int STAT_RANGE = 10; public static final int STAT_CRIT = 11; public static final int STAT_AP = 12; public static final int STAT_LS = 13; public static final int STAT_MSP = 14; public static final int STAT_CDR = 15; public static final int STAT_ARPEN = 16; public static final int STAT_NRG = 17; public static final int STAT_NRGR = 18; public static final int STAT_GP10 = 19; public static final int STAT_MRP = 20; public static final int STAT_CD = 21; public static final int STAT_DT = 22; public static final int STAT_APP = 23; public static final int STAT_SV = 24; public static final int STAT_MPENP = 25; public static final int STAT_APENP = 26; public static final int STAT_DMG_REDUCTION = 27; public static final int STAT_CC_RED = 28; public static final int STAT_AA_TRUE_DAMAGE = 29; public static final int STAT_AA_MAGIC_DAMAGE = 30; public static final int STAT_MAGIC_DMG_REDUCTION = 31; public static final int STAT_MAGIC_HP = 32; public static final int STAT_INVULNERABILITY = 33; public static final int STAT_SPELL_BLOCK = 34; public static final int STAT_CC_IMMUNE = 35; public static final int STAT_INVULNERABILITY_ALL_BUT_ONE = 36; public static final int STAT_AOE_DPS_MAGIC = 37; public static final int STAT_PERCENT_HP_MISSING = 38; public static final int STAT_UNDYING = 39; public static final int STAT_TOTAL_AR = 40; public static final int STAT_TOTAL_AD = 41; public static final int STAT_TOTAL_HP = 42; public static final int STAT_CD_MOD = 43; public static final int STAT_TOTAL_AP = 44; public static final int STAT_TOTAL_MS = 45; public static final int STAT_TOTAL_MR = 46; public static final int STAT_AS = 47; public static final int STAT_LEVEL = 48; public static final int STAT_TOTAL_RANGE = 49; public static final int STAT_TOTAL_MP = 50; public static final int STAT_BONUS_AD = 60; public static final int STAT_BONUS_HP = 61; public static final int STAT_BONUS_MS = 62; public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp public static final int STAT_BONUS_AR = 63; public static final int STAT_BONUS_MR = 64; public static final int STAT_LEVEL_MINUS_ONE = 65; public static final int STAT_CRIT_DMG = 66; public static final int STAT_AA_DPS = 70; public static final int STAT_NAUTILUS_Q_CD = 80; public static final int STAT_RENGAR_Q_BASE_DAMAGE = 81; public static final int STAT_VI_W = 82; public static final int STAT_STACKS = 83; // generic stat... could be used for Ashe/Nasus, etc public static final int STAT_SOULS = 84; public static final int STAT_ENEMY_MISSING_HP = 100; public static final int STAT_ENEMY_CURRENT_HP = 101; public static final int STAT_ENEMY_MAX_HP = 102; public static final int STAT_ONE = 120; public static final int STAT_TYPE_DEFAULT = 0; public static final int STAT_TYPE_PERCENT = 1; private static final int MAX_STATS = 121; private static final int MAX_ACTIVE_ITEMS = 6; public static final String JSON_KEY_RUNES = "runes"; public static final String JSON_KEY_ITEMS = "items"; public static final String JSON_KEY_BUILD_NAME = "build_name"; public static final String JSON_KEY_COLOR = "color"; private static final Map<String, Integer> statKeyToIndex = new HashMap<String, Integer>(); private static final SparseIntArray statIdToStringId = new SparseIntArray(); private static final SparseIntArray statIdToSkillStatDescStringId = new SparseIntArray(); private static final int COLOR_AP = 0xFF59BD1A; private static final int COLOR_AD = 0xFFFAA316; private static final int COLOR_TANK = 0xFF1092E8; private static final float STAT_VALUE_HP = 2.66f; private static final float STAT_VALUE_AR = 20f; private static final float STAT_VALUE_MR = 20f; private static final float STAT_VALUE_AD = 36f; private static final float STAT_VALUE_AP = 21.75f; private static final float STAT_VALUE_CRIT = 50f; private static final float STAT_VALUE_ASP = 30f; private static ItemLibrary itemLibrary; private static RuneLibrary runeLibrary; private static final double[] RENGAR_Q_BASE = new double[] { 30, 45, 60, 75, 90, 105, 120, 135, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240 }; static { statKeyToIndex.put("FlatArmorMod", STAT_AR); statKeyToIndex.put("FlatAttackSpeedMod", STAT_NULL); statKeyToIndex.put("FlatBlockMod", STAT_NULL); statKeyToIndex.put("FlatCritChanceMod", STAT_CRIT); statKeyToIndex.put("FlatCritDamageMod", STAT_NULL); statKeyToIndex.put("FlatEXPBonus", STAT_NULL); statKeyToIndex.put("FlatEnergyPoolMod", STAT_NULL); statKeyToIndex.put("FlatEnergyRegenMod", STAT_NULL); statKeyToIndex.put("FlatHPPoolMod", STAT_HP); statKeyToIndex.put("FlatHPRegenMod", STAT_HPR); statKeyToIndex.put("FlatMPPoolMod", STAT_MP); statKeyToIndex.put("FlatMPRegenMod", STAT_MPR); statKeyToIndex.put("FlatMagicDamageMod", STAT_AP); statKeyToIndex.put("FlatMovementSpeedMod", STAT_MS); statKeyToIndex.put("FlatPhysicalDamageMod", STAT_AD); statKeyToIndex.put("FlatSpellBlockMod", STAT_MR); statKeyToIndex.put("FlatCoolDownRedMod", STAT_CDR); statKeyToIndex.put("PercentArmorMod", STAT_NULL); statKeyToIndex.put("PercentAttackSpeedMod", STAT_ASP); statKeyToIndex.put("PercentBlockMod", STAT_NULL); statKeyToIndex.put("PercentCritChanceMod", STAT_NULL); statKeyToIndex.put("PercentCritDamageMod", STAT_NULL); statKeyToIndex.put("PercentDodgeMod", STAT_NULL); statKeyToIndex.put("PercentEXPBonus", STAT_NULL); statKeyToIndex.put("PercentHPPoolMod", STAT_NULL); statKeyToIndex.put("PercentHPRegenMod", STAT_NULL); statKeyToIndex.put("PercentLifeStealMod", STAT_LS); statKeyToIndex.put("PercentMPPoolMod", STAT_NULL); statKeyToIndex.put("PercentMPRegenMod", STAT_NULL); statKeyToIndex.put("PercentMagicDamageMod", STAT_APP); statKeyToIndex.put("PercentMovementSpeedMod", STAT_MSP); statKeyToIndex.put("PercentPhysicalDamageMod", STAT_NULL); statKeyToIndex.put("PercentSpellBlockMod", STAT_NULL); statKeyToIndex.put("PercentSpellVampMod", STAT_SV); statKeyToIndex.put("CCRed", STAT_CC_RED); statKeyToIndex.put("FlatAaTrueDamageMod", STAT_AA_TRUE_DAMAGE); statKeyToIndex.put("FlatAaMagicDamageMod", STAT_AA_MAGIC_DAMAGE); statKeyToIndex.put("magic_aoe_dps", STAT_AOE_DPS_MAGIC); statKeyToIndex.put("perpercenthpmissing", STAT_PERCENT_HP_MISSING); statKeyToIndex.put("rFlatArmorModPerLevel", STAT_AR | FLAG_SCALING); statKeyToIndex.put("rFlatArmorPenetrationMod", STAT_ARPEN); statKeyToIndex.put("rFlatArmorPenetrationModPerLevel", STAT_ARPEN | FLAG_SCALING); statKeyToIndex.put("rFlatEnergyModPerLevel", STAT_NRG | FLAG_SCALING); statKeyToIndex.put("rFlatEnergyRegenModPerLevel", STAT_NRGR | FLAG_SCALING); statKeyToIndex.put("rFlatGoldPer10Mod", STAT_GP10); statKeyToIndex.put("rFlatHPModPerLevel", STAT_HP | FLAG_SCALING); statKeyToIndex.put("rFlatHPRegenModPerLevel", STAT_HPR | FLAG_SCALING); statKeyToIndex.put("rFlatMPModPerLevel", STAT_MP | FLAG_SCALING); statKeyToIndex.put("rFlatMPRegenModPerLevel", STAT_MPR | FLAG_SCALING); statKeyToIndex.put("rFlatMagicDamageModPerLevel", STAT_AP | FLAG_SCALING); statKeyToIndex.put("rFlatMagicPenetrationMod", STAT_MRP); statKeyToIndex.put("rFlatMagicPenetrationModPerLevel", STAT_MRP | FLAG_SCALING); statKeyToIndex.put("rFlatPhysicalDamageModPerLevel", STAT_AD | FLAG_SCALING); statKeyToIndex.put("rFlatSpellBlockModPerLevel", STAT_MR | FLAG_SCALING); statKeyToIndex.put("rPercentCooldownMod", STAT_CD); // negative val... statKeyToIndex.put("rPercentCooldownModPerLevel", STAT_CD | FLAG_SCALING); statKeyToIndex.put("rPercentTimeDeadMod", STAT_DT); statKeyToIndex.put("rPercentTimeDeadModPerLevel", STAT_DT | FLAG_SCALING); statKeyToIndex.put("rPercentMagicPenetrationMod", STAT_MPENP); statKeyToIndex.put("rPercentArmorPenetrationMod", STAT_APENP); statKeyToIndex.put("damagereduction", STAT_DMG_REDUCTION); statKeyToIndex.put("magicaldamagereduction", STAT_MAGIC_DMG_REDUCTION); statKeyToIndex.put("FlatMagicHp", STAT_MAGIC_HP); statKeyToIndex.put("Invulnerability", STAT_INVULNERABILITY); statKeyToIndex.put("SpellBlock", STAT_SPELL_BLOCK); statKeyToIndex.put("CcImmune", STAT_CC_IMMUNE); statKeyToIndex.put("InvulnerabilityButOne", STAT_INVULNERABILITY_ALL_BUT_ONE); statKeyToIndex.put("Undying", STAT_UNDYING); // keys used for skills... statKeyToIndex.put("spelldamage", STAT_TOTAL_AP); statKeyToIndex.put("attackdamage", STAT_TOTAL_AD); statKeyToIndex.put("bonushealth", STAT_BONUS_HP); statKeyToIndex.put("armor", STAT_TOTAL_AR); statKeyToIndex.put("bonusattackdamage", STAT_BONUS_AD); statKeyToIndex.put("health", STAT_TOTAL_HP); statKeyToIndex.put("bonusarmor", STAT_BONUS_AR); statKeyToIndex.put("bonusspellblock", STAT_BONUS_MR); statKeyToIndex.put("levelMinusOne", STAT_LEVEL_MINUS_ONE); statKeyToIndex.put("level", STAT_LEVEL); statKeyToIndex.put("RangeMod", STAT_RANGE); statKeyToIndex.put("mana", STAT_TOTAL_MP); statKeyToIndex.put("critdamage", STAT_CRIT_DMG); statKeyToIndex.put("enemymissinghealth", STAT_ENEMY_MISSING_HP); statKeyToIndex.put("enemycurrenthealth", STAT_ENEMY_CURRENT_HP); statKeyToIndex.put("enemymaxhealth", STAT_ENEMY_MAX_HP); statKeyToIndex.put("movementspeed", STAT_TOTAL_MS); // special keys... statKeyToIndex.put("@special.BraumWArmor", STAT_NULL); statKeyToIndex.put("@special.BraumWMR", STAT_NULL); statKeyToIndex.put("@special.jaycew", STAT_NULL); statKeyToIndex.put("@cooldownchampion", STAT_CD_MOD); statKeyToIndex.put("@stacks", STAT_STACKS); statKeyToIndex.put("@souls", STAT_SOULS); // heim statKeyToIndex.put("@dynamic.abilitypower", STAT_AP); // rengar statKeyToIndex.put("@dynamic.attackdamage", STAT_RENGAR_Q_BASE_DAMAGE); statKeyToIndex.put("@special.nautilusq", STAT_NAUTILUS_Q_CD); statKeyToIndex.put("@special.viw", STAT_VI_W); // darius statKeyToIndex.put("@special.dariusr3", STAT_ONE); statKeyToIndex.put("null", STAT_NULL); SparseIntArray a = statIdToStringId; a.put(STAT_NULL, R.string.stat_desc_null); a.put(STAT_HP, R.string.stat_desc_hp); a.put(STAT_HPR, R.string.stat_desc_hpr); a.put(STAT_MP, R.string.stat_desc_mp); a.put(STAT_MPR, R.string.stat_desc_mpr); a.put(STAT_AD, R.string.stat_desc_ad); a.put(STAT_ASP, R.string.stat_desc_asp); a.put(STAT_AR, R.string.stat_desc_ar); a.put(STAT_MR, R.string.stat_desc_mr); a.put(STAT_LEVEL_MINUS_ONE, R.string.stat_desc_level_minus_one); a.put(STAT_MS, R.string.stat_desc_ms); a.put(STAT_RANGE, R.string.stat_desc_range); a.put(STAT_ENEMY_MAX_HP, R.string.stat_desc_enemy_max_hp); a.put(STAT_TOTAL_MP, R.string.stat_desc_total_mp); // public static final int STAT_CRIT = 11; // public static final int STAT_AP = 12; // public static final int STAT_LS = 13; // public static final int STAT_MSP = 14; // public static final int STAT_CDR = 15; // public static final int STAT_ARPEN = 16; // public static final int STAT_NRG = 17; // public static final int STAT_NRGR = 18; // public static final int STAT_GP10 = 19; // public static final int STAT_MRP = 20; // public static final int STAT_CD = 21; // public static final int STAT_DT = 22; // public static final int STAT_APP = 23; // public static final int STAT_SV = 24; // public static final int STAT_MPENP = 25; // public static final int STAT_APENP = 26; a.put(STAT_DMG_REDUCTION, R.string.stat_desc_damage_reduction); // public static final int STAT_TOTAL_AR = 40; // public static final int STAT_TOTAL_AD = 41; // public static final int STAT_TOTAL_HP = 42; // public static final int STAT_CD_MOD = 43; // public static final int STAT_TOTAL_AP = 44; // public static final int STAT_TOTAL_MS = 45; // public static final int STAT_TOTAL_MR = 46; // public static final int STAT_AS = 47; // public static final int STAT_LEVEL = 48; // public static final int STAT_BONUS_AD = 50; // public static final int STAT_BONUS_HP = 51; // public static final int STAT_BONUS_MS = 52; // public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp // public static final int STAT_BONUS_AR = 53; // public static final int STAT_BONUS_MR = 54; // public static final int STAT_AA_DPS = 60; SparseIntArray b = statIdToSkillStatDescStringId; b.put(STAT_NULL, R.string.skill_stat_null); b.put(STAT_TOTAL_AP, R.string.skill_stat_ap); b.put(STAT_LEVEL_MINUS_ONE, R.string.skill_stat_level_minus_one); b.put(STAT_TOTAL_AD, R.string.skill_stat_ad); b.put(STAT_BONUS_AD, R.string.skill_stat_bonus_ad); b.put(STAT_CD_MOD, R.string.skill_stat_cd_mod); b.put(STAT_STACKS, R.string.skill_stat_stacks); b.put(STAT_ONE, R.string.skill_stat_one); b.put(STAT_BONUS_HP, R.string.skill_stat_bonus_hp); b.put(STAT_TOTAL_AR, R.string.skill_stat_total_ar); b.put(STAT_TOTAL_MP, R.string.skill_stat_total_mp); // public static final int STAT_TOTAL_AR = 40; // public static final int STAT_TOTAL_AD = 41; // public static final int STAT_TOTAL_HP = 42; // public static final int STAT_CD_MOD = 43; // public static final int STAT_TOTAL_MS = 45; // public static final int STAT_TOTAL_MR = 46; // public static final int STAT_AS = 47; // public static final int STAT_LEVEL = 48; // public static final int STAT_TOTAL_RANGE = 49; // public static final int STAT_TOTAL_MP = 50; // public static final int STAT_BONUS_HP = 61; // public static final int STAT_BONUS_MS = 62; // public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp // public static final int STAT_BONUS_AR = 63; // public static final int STAT_BONUS_MR = 64; // public static final int STAT_LEVEL_MINUS_ONE = 65; // public static final int STAT_CRIT_DMG = 66; } private String buildName; private List<BuildSkill> activeSkills; private List<BuildRune> runeBuild; private List<BuildItem> itemBuild; private ChampionInfo champ; private int champLevel; private List<BuildObserver> observers = new ArrayList<BuildObserver>(); private int enabledBuildStart = 0; private int enabledBuildEnd = 0; private int currentGroupCounter = 0; private int[] runeCount = new int[4]; private double[] stats = new double[MAX_STATS]; private double[] statsWithActives = new double[MAX_STATS]; private boolean itemBuildDirty = false; private Gson gson; private OnRuneCountChangedListener onRuneCountChangedListener = new OnRuneCountChangedListener() { @Override public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) { Build.this.onRuneCountChanged(rune, oldCount, newCount); } }; public Build() { itemBuild = new ArrayList<BuildItem>(); runeBuild = new ArrayList<BuildRune>(); activeSkills = new ArrayList<BuildSkill>(); gson = StateManager.getInstance().getGson(); if (itemLibrary == null) { itemLibrary = LibraryManager.getInstance().getItemLibrary(); } if (runeLibrary == null) { runeLibrary = LibraryManager.getInstance().getRuneLibrary(); } champLevel = 1; } public void setBuildName(String name) { buildName = name; } public String getBuildName() { return buildName; } private void clearGroups() { for (BuildItem item : itemBuild) { item.group = -1; item.to = null; item.depth = 0; item.from.clear(); } currentGroupCounter = 0; } private void recalculateAllGroups() { clearGroups(); for (int i = 0; i < itemBuild.size(); i++) { labelAllIngredients(itemBuild.get(i), i); } } private BuildItem getFreeItemWithId(int id, int index) { for (int i = index - 1; i >= 0; i if (itemBuild.get(i).getId() == id && itemBuild.get(i).to == null) { return itemBuild.get(i); } } return null; } private void labelAllIngredients(BuildItem item, int index) { int curGroup = currentGroupCounter; boolean grouped = false; Stack<Integer> from = new Stack<Integer>(); from.addAll(item.info.from); while (!from.empty()) { int i = from.pop(); BuildItem ingredient = getFreeItemWithId(i, index); if (ingredient != null && ingredient.to == null) { if (ingredient.group != -1) { curGroup = ingredient.group; } ingredient.to = item; item.from.add(ingredient); grouped = true; calculateItemCost(item); } else { from.addAll(itemLibrary.getItemInfo(i).from); } } if (grouped) { increaseIngredientDepth(item); for (BuildItem i : item.from) { i.group = curGroup; } item.group = curGroup; if (curGroup == currentGroupCounter) { currentGroupCounter++; } } } private void calculateItemCost(BuildItem item) { int p = item.info.totalGold; for (BuildItem i : item.from) { p -= i.info.totalGold; } item.costPer = p; } private void recalculateItemCosts() { for (BuildItem item : itemBuild) { calculateItemCost(item); } } private void increaseIngredientDepth(BuildItem item) { for (BuildItem i : item.from) { i.depth++; increaseIngredientDepth(i); } } public void addItem(ItemInfo item) { addItem(item, 1, true); } public void addItem(ItemInfo item, int count, boolean isAll) { BuildItem buildItem = null; BuildItem last = getLastItem(); if (last != null && item == last.info) { if (item.stacks > last.count) { last.count += count; buildItem = last; } } if (isAll == false) { itemBuildDirty = true; } boolean itemNull = buildItem == null; if (itemNull) { buildItem = new BuildItem(item); buildItem.count = Math.min(item.stacks, count); // check if ingredients of this item is already part of the build... labelAllIngredients(buildItem, itemBuild.size()); if (itemBuild.size() == enabledBuildEnd) { enabledBuildEnd++; } itemBuild.add(buildItem); calculateItemCost(buildItem); } if (isAll) { recalculateStats(); if (itemBuildDirty) { itemBuildDirty = false; buildItem = null; } notifyItemAdded(buildItem, itemNull); } } public void clearItems() { itemBuild.clear(); normalizeValues(); recalculateItemCosts(); recalculateAllGroups(); recalculateStats(); notifyBuildChanged(); } public void removeItemAt(int position) { BuildItem item = itemBuild.get(position); itemBuild.remove(position); normalizeValues(); recalculateItemCosts(); recalculateAllGroups(); recalculateStats(); notifyBuildChanged(); } public int getItemCount() { return itemBuild.size(); } private void clearStats(double[] stats) { for (int i = 0; i < stats.length; i++) { stats[i] = 0; } } private void recalculateStats() { calculateStats(stats, enabledBuildStart, enabledBuildEnd, false, champLevel); } private void calculateStats(double[] stats, int startItemBuild, int endItemBuild, boolean onlyDoRawCalculation, int champLevel) { clearStats(stats); int active = 0; for (BuildRune r : runeBuild) { appendStat(stats, r); } if (!onlyDoRawCalculation) { for (BuildItem item : itemBuild) { item.active = false; } } HashSet<Integer> alreadyAdded = new HashSet<Integer>(); for (int i = endItemBuild - 1; i >= startItemBuild; i BuildItem item = itemBuild.get(i); if (item.to == null || itemBuild.indexOf(item.to) >= enabledBuildEnd) { if (!onlyDoRawCalculation) { item.active = true; } ItemInfo info = item.info; appendStat(stats, info.stats); int id = info.id; if (info.uniquePassiveStat != null && !alreadyAdded.contains(id)) { alreadyAdded.add(info.id); appendStat(stats, info.uniquePassiveStat); } active++; if (active == MAX_ACTIVE_ITEMS) break; } } calculateTotalStats(stats, champLevel); if (!onlyDoRawCalculation) { notifyBuildStatsChanged(); } } private void appendStat(double[] stats, JSONObject jsonStats) { Iterator<?> iter = jsonStats.keys(); while (iter.hasNext()) { String key = (String) iter.next(); try { stats[getStatIndex(key)] += jsonStats.getDouble(key); } catch (JSONException e) { DebugLog.e(TAG, e); } } } private void appendStat(double[] stats, BuildRune rune) { RuneInfo info = rune.info; Iterator<?> iter = info.stats.keys(); while (iter.hasNext()) { String key = (String) iter.next(); try { int f = getStatIndex(key); if ((f & FLAG_SCALING) != 0) { stats[f & ~FLAG_SCALING] += info.stats.getDouble(key) * champLevel * rune.count; } else { stats[f] += info.stats.getDouble(key) * rune.count; } } catch (JSONException e) { DebugLog.e(TAG, e); } } } private void calculateTotalStats() { calculateTotalStats(stats, champLevel); } private void calculateTotalStats(double[] stats, int champLevel) { // do some stat normalization... stats[STAT_CDR] = Math.min(MAX_CDR, stats[STAT_CDR] - stats[STAT_CD]); int levMinusOne = champLevel - 1; stats[STAT_TOTAL_AR] = stats[STAT_AR] + champ.ar + champ.arG * levMinusOne; stats[STAT_TOTAL_AD] = stats[STAT_AD] + champ.ad + champ.adG * levMinusOne; stats[STAT_TOTAL_HP] = stats[STAT_HP] + champ.hp + champ.hpG * levMinusOne; stats[STAT_CD_MOD] = 1.0 - stats[STAT_CDR]; stats[STAT_TOTAL_MS] = (stats[STAT_MS] + champ.ms) * stats[STAT_MSP] + stats[STAT_MS] + champ.ms; stats[STAT_TOTAL_AP] = stats[STAT_AP] * (stats[STAT_APP] + 1); stats[STAT_TOTAL_MR] = stats[STAT_MR] + champ.mr + champ.mrG * levMinusOne; stats[STAT_AS] = Math.min(champ.as * (1 + levMinusOne * champ.asG + stats[STAT_ASP]), MAX_ATTACK_SPEED); stats[STAT_LEVEL] = champLevel; stats[STAT_TOTAL_RANGE] = stats[STAT_RANGE] + champ.range; stats[STAT_TOTAL_MP] = stats[STAT_MP] + champ.mp + champ.mpG * levMinusOne; stats[STAT_BONUS_AD] = stats[STAT_TOTAL_AD] - champ.ad; stats[STAT_BONUS_HP] = stats[STAT_TOTAL_HP] - champ.hp; stats[STAT_BONUS_MS] = stats[STAT_TOTAL_MS] - champ.ms; stats[STAT_BONUS_AR] = stats[STAT_TOTAL_AR] - champ.ar; stats[STAT_BONUS_MR] = stats[STAT_TOTAL_MR] - champ.mr; stats[STAT_LEVEL_MINUS_ONE] = stats[STAT_LEVEL] - 1; stats[STAT_CRIT_DMG] = stats[STAT_TOTAL_AD] * 2.0; // pure stats... stats[STAT_AA_DPS] = stats[STAT_TOTAL_AD] * stats[STAT_AS]; // static values... stats[STAT_NAUTILUS_Q_CD] = 0.5; stats[STAT_ONE] = 1; } private static int addColor(int base, int value) { double result = 1 - (1 - base / 256.0) * (1 - value / 256.0); return (int) (result * 256); } public int generateColorBasedOnBuild() { int r = 0, g = 0, b = 0; int hp = 0; int mr = 0; int ar = 0; int ad = 0; int ap = 0; int crit = 0; int as = 0; calculateTotalStats(stats, 1); hp = (int) (stats[STAT_BONUS_HP] * STAT_VALUE_HP); mr = (int) (stats[STAT_BONUS_MR] * STAT_VALUE_MR); ar = (int) (stats[STAT_BONUS_AR] * STAT_VALUE_AR); ad = (int) (stats[STAT_BONUS_AD] * STAT_VALUE_AD); ap = (int) (stats[STAT_BONUS_AP] * STAT_VALUE_AP); crit = (int) (stats[STAT_CRIT] * 100 * STAT_VALUE_CRIT); as = (int) (stats[STAT_ASP] * 100 * STAT_VALUE_ASP); int tank = hp + mr + ar; int dps = ad + as + crit; int burst = ap; double total = tank + dps + burst; double tankness = tank / total; double adness = dps / total; double apness = burst / total; r = addColor((int) (Color.red(COLOR_AD) * adness), r); r = addColor((int) (Color.red(COLOR_AP) * apness), r); r = addColor((int) (Color.red(COLOR_TANK) * tankness), r); g = addColor((int) (Color.green(COLOR_AD) * adness), g); g = addColor((int) (Color.green(COLOR_AP) * apness), g); g = addColor((int) (Color.green(COLOR_TANK) * tankness), g); b = addColor((int) (Color.blue(COLOR_AD) * adness), b); b = addColor((int) (Color.blue(COLOR_AP) * apness), b); b = addColor((int) (Color.blue(COLOR_TANK) * tankness), b); Log.d(TAG, String.format("Tankiness: %f Apness: %f Adness: %f", tankness, apness, adness)); return Color.rgb(r, g, b); } public BuildRune addRune(RuneInfo rune) { return addRune(rune, 1, true); } public BuildRune addRune(RuneInfo rune, int count, boolean isAll) { // Check if this rune is already in the build... BuildRune r = null; for (BuildRune br : runeBuild) { if (br.id == rune.id) { r = br; break; } } if (r == null) { r = new BuildRune(rune, rune.id); runeBuild.add(r); r.listener = onRuneCountChangedListener; notifyRuneAdded(r); } r.addRune(count); recalculateStats(); return r; } public void clearRunes() { for (BuildRune r : runeBuild) { r.listener = null; notifyRuneRemoved(r); } runeBuild.clear(); recalculateStats(); } public boolean canAdd(RuneInfo rune) { return runeCount[rune.runeType] + 1 <= RUNE_COUNT_MAX[rune.runeType]; } public void removeRune(BuildRune rune) { rune.listener = null; runeBuild.remove(rune); recalculateStats(); notifyRuneRemoved(rune); } private void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) { int runeType = rune.info.runeType; if (runeCount[runeType] + (newCount - oldCount) > RUNE_COUNT_MAX[runeType]) { rune.count = oldCount; return; } runeCount[runeType] += (newCount - oldCount); if (rune.getCount() == 0) { removeRune(rune); } else { recalculateStats(); } } public BuildSkill addActiveSkill(Skill skill, double base, double scaling, String scaleType, String bonusType) { BuildSkill sk = new BuildSkill(); sk.skill = skill; sk.base = base; sk.scaleTypeId = getStatIndex(scaleType); sk.bonusTypeId = getStatIndex(bonusType); sk.scaling = scaling; activeSkills.add(sk); DebugLog.d(TAG, "Skill " + skill.name + " bonus: " + base + "; "); return sk; } public double[] calculateStatWithActives(int gold, int champLevel) { double[] s = new double[stats.length]; int itemEndIndex = itemBuild.size(); int buildCost = 0; for (int i = 0; i < itemBuild.size(); i++) { BuildItem item = itemBuild.get(i); int itemCost = item.costPer * item.count; if (buildCost + itemCost > gold) { itemEndIndex = i; break; } else { buildCost += itemCost; } } calculateStats(s, 0, itemEndIndex, true, champLevel); for (BuildSkill sk : activeSkills) { sk.totalBonus = s[sk.scaleTypeId] * sk.scaling + sk.base; s[sk.bonusTypeId] += sk.totalBonus; } calculateTotalStats(s, champLevel); return s; } public List<BuildSkill> getActives() { return activeSkills; } public void clearActiveSkills() { activeSkills.clear(); } public void setChampion(ChampionInfo champ) { this.champ = champ; recalculateStats(); } public void setChampionLevel(int level) { champLevel = level; recalculateStats(); } public void registerObserver(BuildObserver observer) { observers.add(observer); } public void unregisterObserver(BuildObserver observer) { observers.remove(observer); } private void notifyBuildChanged() { for (BuildObserver o : observers) { o.onBuildChanged(this); } } private void notifyItemAdded(BuildItem item, boolean isNewItem) { for (BuildObserver o : observers) { o.onItemAdded(this, item, isNewItem); } } private void notifyRuneAdded(BuildRune rune) { for (BuildObserver o : observers) { o.onRuneAdded(this, rune); } } private void notifyRuneRemoved(BuildRune rune) { for (BuildObserver o : observers) { o.onRuneRemoved(this, rune); } } private void notifyBuildStatsChanged() { for (BuildObserver o : observers) { o.onBuildStatsChanged(); } } private void normalizeValues() { if (enabledBuildStart < 0) { enabledBuildStart = 0; } if (enabledBuildEnd > itemBuild.size()) { enabledBuildEnd = itemBuild.size(); } } public BuildItem getItem(int index) { return itemBuild.get(index); } public int getBuildSize() { return itemBuild.size(); } public BuildRune getRune(int index) { return runeBuild.get(index); } public int getRuneCount() { return runeBuild.size(); } public BuildItem getLastItem() { if (itemBuild.size() == 0) return null; return itemBuild.get(itemBuild.size() - 1); } public double getBonusHp() { return stats[STAT_HP]; } public double getBonusHpRegen() { return stats[STAT_HPR]; } public double getBonusMp() { if (champ.partype == ChampionInfo.TYPE_MANA) { return stats[STAT_MP]; } else { return 0; } } public double getBonusMpRegen() { if (champ.partype == ChampionInfo.TYPE_MANA) { return stats[STAT_MPR]; } else { return 0; } } public double getBonusAd() { return stats[STAT_AD]; } public double getBonusAs() { return stats[STAT_ASP]; } public double getBonusAr() { return stats[STAT_AR]; } public double getBonusMr() { return stats[STAT_MR]; } public double getBonusMs() { return stats[STAT_BONUS_MS]; } public double getBonusRange() { return stats[STAT_RANGE]; } public double getBonusAp() { return stats[STAT_BONUS_AP]; } public double getBonusEnergy() { return stats[STAT_NRG]; } public double getBonusEnergyRegen() { return stats[STAT_NRGR]; } public double[] getRawStats() { return stats; } public double getStat(String key) { int statId = getStatIndex(key); if (statId == STAT_NULL) return 0.0; if (statId == STAT_RENGAR_Q_BASE_DAMAGE) { // refresh rengar q base damage since it looks like we are going to be using it... stats[STAT_RENGAR_Q_BASE_DAMAGE] = RENGAR_Q_BASE[champLevel - 1]; } if (statId == STAT_VI_W) { stats[STAT_VI_W] = 0.00081632653 * stats[STAT_BONUS_AD]; } return stats[statId]; } public double getStat(int statId) { if (statId == STAT_NULL) return 0.0; return stats[statId]; } public void reorder(int itemOldPosition, int itemNewPosition) { BuildItem item = itemBuild.get(itemOldPosition); itemBuild.remove(itemOldPosition); itemBuild.add(itemNewPosition, item); recalculateAllGroups(); recalculateStats(); notifyBuildStatsChanged(); } public int getEnabledBuildStart() { return enabledBuildStart; } public int getEnabledBuildEnd() { return enabledBuildEnd; } public void setEnabledBuildStart(int start) { enabledBuildStart = start; recalculateStats(); notifyBuildStatsChanged(); } public void setEnabledBuildEnd(int end) { enabledBuildEnd = end; recalculateStats(); notifyBuildStatsChanged(); } public BuildSaveObject toSaveObject() { BuildSaveObject o = new BuildSaveObject(); for (BuildRune r : runeBuild) { o.runes.add(r.info.id); o.runes.add(r.count); } for (BuildItem i : itemBuild) { o.items.add(i.info.id); o.items.add(i.count); } o.buildName = buildName; o.buildColor = generateColorBasedOnBuild(); return o; } public void fromSaveObject(BuildSaveObject o) { clearItems(); clearRunes(); int count = o.runes.size(); for (int i = 0; i < count; i += 2) { addRune(runeLibrary.getRuneInfo(o.runes.get(i)), o.runes.get(i + 1), i + 2 >= count); } count = o.items.size(); for (int i = 0; i < count; i += 2) { int itemId = o.items.get(i); int c = o.items.get(i + 1); addItem(itemLibrary.getItemInfo(itemId), c, i == count - 2); } buildName = o.buildName; } public static int getSuggestedColorForGroup(int groupId) { return GROUP_COLOR[groupId % GROUP_COLOR.length]; } public static interface BuildObserver { public void onBuildChanged(Build build); public void onItemAdded(Build build, BuildItem item, boolean isNewItem); public void onRuneAdded(Build build, BuildRune rune); public void onRuneRemoved(Build build, BuildRune rune); public void onBuildStatsChanged(); } public static class BuildItem { ItemInfo info; int group = -1; boolean active = true; int count = 1; int costPer = 0; int depth = 0; List<BuildItem> from; BuildItem to; private BuildItem(ItemInfo info) { this.info = info; from = new ArrayList<BuildItem>(); } public int getId() { return info.id; } } public static class BuildRune { RuneInfo info; Object tag; int id; private int count; private OnRuneCountChangedListener listener; private OnRuneCountChangedListener onRuneCountChangedListener; private BuildRune(RuneInfo info, int id) { this.info = info; count = 0; this.id = id; } public void addRune() { addRune(1); } public void addRune(int n) { count += n; int c = count; listener.onRuneCountChanged(this, count - n, count); if (c == count && onRuneCountChangedListener != null) { onRuneCountChangedListener.onRuneCountChanged(this, count - n, count); } } public void removeRune() { if (count == 0) return; count int c = count; listener.onRuneCountChanged(this, count + 1, count); if (c == count && onRuneCountChangedListener != null) { onRuneCountChangedListener.onRuneCountChanged(this, count + 1, count); } } public int getCount() { return count; } public void setOnRuneCountChangedListener(OnRuneCountChangedListener listener) { onRuneCountChangedListener = listener; } } public static class BuildSkill { public double totalBonus; Skill skill; double base; double scaling; int scaleTypeId; int bonusTypeId; } public static interface OnRuneCountChangedListener { public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount); } public static int getStatIndex(String statName) { Integer i; i = statKeyToIndex.get(statName); if (i == null) { throw new RuntimeException("Stat name not found: " + statName); } return i; } public static int getStatName(int statId) { int i; i = statIdToStringId.get(statId); if (i == 0) { throw new RuntimeException("Stat id does not have string resource: " + statId); } return i; } public static int getSkillStatDesc(int statId) { int i; i = statIdToSkillStatDescStringId.get(statId); if (i == 0) { throw new RuntimeException("Stat id does not have a skill stat description: " + statId); } return i; } public static int getStatType(int statId) { switch (statId) { case STAT_DMG_REDUCTION: case STAT_ENEMY_MAX_HP: case STAT_ENEMY_CURRENT_HP: case STAT_ENEMY_MISSING_HP: return STAT_TYPE_PERCENT; default: return STAT_TYPE_DEFAULT; } } public static int getScalingType(int statId) { switch (statId) { case STAT_CD_MOD: case STAT_STACKS: case STAT_ONE: return STAT_TYPE_DEFAULT; default: return STAT_TYPE_PERCENT; } } }
package com.zsx.app; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import com.zsx.itf.Lib_OnLifecycleListener; import com.zsx.manager.Lib_SystemExitManager; import java.util.HashSet; import java.util.Set; public class Lib_BaseActivity extends Activity { public static final String _EXTRA_Serializable = "extra_Serializable"; public static final String _EXTRA_String = "xtra_String"; public static final String _EXTRA_Integer = "extra_Integer"; public static final String _EXTRA_Boolean = "extra_boolean"; /** * Activity Toast */ private Toast toast; private long exitTime; private boolean isDoubleBack = false; /** * EditText */ private boolean isClickNoEditTextCloseInput = false; /** * Activity */ private Set<Lib_OnLifecycleListener> listeners = new HashSet<Lib_OnLifecycleListener>(); public void _showToast(String message) { if (TextUtils.isEmpty(message)) { return; } if (toast == null) { toast = Toast.makeText(this, message, Toast.LENGTH_SHORT); } toast.setText(message); toast.show(); } public void _setClickNoEditTextCloseInput(boolean isClickNoEditTextCloseInput) { this.isClickNoEditTextCloseInput = isClickNoEditTextCloseInput; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!isClickNoEditTextCloseInput) { return super.dispatchTouchEvent(ev); } if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (isShouldHideInput(v, ev)) { if (v.getWindowToken() != null) { InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } } return super.dispatchTouchEvent(ev); } private boolean isShouldHideInput(View v, MotionEvent event) { if (v != null && (v instanceof EditText)) { int[] l = {0, 0}; v.getLocationInWindow(l); int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth(); if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) { return false; } else { return true; } } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Lib_SystemExitManager.addActivity(this); } public void _addOnLifeCycleListener(Lib_OnLifecycleListener listener) { listeners.add(listener); } public void _removeOnLifeCycleListener(Lib_OnLifecycleListener listener) { listeners.remove(listener); } @Override protected void onResume() { super.onResume(); for (Lib_OnLifecycleListener l : listeners) { l.onActivityResume(); } } @Override protected void onPause() { super.onPause(); for (Lib_OnLifecycleListener l : listeners) { l.onActivityPause(); } } @Override protected void onDestroy() { super.onDestroy(); for (Lib_OnLifecycleListener l : listeners) { l.onActivityDestroy(); } listeners.clear(); Lib_SystemExitManager.removeActivity(this); } @Override public void finish() { super.finish(); for (Lib_OnLifecycleListener l : listeners) { l.onActivityDestroy(); } listeners.clear(); Lib_SystemExitManager.removeActivity(this); } public void _exitSystem() { Lib_SystemExitManager.exitSystem(); } private String mToastMessage = ""; /** * * * @param isDoubleBack */ public final void _setDoubleBackExit(boolean isDoubleBack) { this.isDoubleBack = isDoubleBack; } public final void _setDoubleBackExit(boolean isDoubleBack, String toastMessage) { this.isDoubleBack = isDoubleBack; this.mToastMessage = toastMessage; } public int _getFullScreenWidth() { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); return displayMetrics.widthPixels; } @Override public void onBackPressed() { if (!isDoubleBack) { super.onBackPressed(); return; } if ((System.currentTimeMillis() - exitTime) > 2000) { _showToast(mToastMessage); exitTime = System.currentTimeMillis(); } else { _exitSystem(); } } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (!isDoubleBack) { // return super.onKeyDown(keyCode, event); // if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // if ((System.currentTimeMillis() - exitTime) > 2000) { // _showToast(mToastMessage); // exitTime = System.currentTimeMillis(); // } else { // _exitSystem(); // return true; // return super.onKeyDown(keyCode, event); }
package org.wikipedia.page; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.language.AppLanguageLookUpTable; import org.wikipedia.settings.SiteInfoClient; import org.wikipedia.util.StringUtil; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Locale; import static org.wikipedia.util.UriUtil.decodeURL; /** * Represents certain vital information about a page, including the title, namespace, * and fragment (section anchor target). It can also contain a thumbnail URL for the * page, and a short description retrieved from Wikidata. * * WARNING: This class is not immutable! Specifically, the thumbnail URL and the Wikidata * description can be altered after construction. Therefore do NOT rely on all the fields * of a PageTitle to remain constant for the lifetime of the object. */ public class PageTitle implements Parcelable { public static final Parcelable.Creator<PageTitle> CREATOR = new Parcelable.Creator<PageTitle>() { @Override public PageTitle createFromParcel(Parcel in) { return new PageTitle(in); } @Override public PageTitle[] newArray(int size) { return new PageTitle[size]; } }; /** * The localised namespace of the page as a string, or null if the page is in mainspace. * * This field contains the prefix of the page's title, as opposed to the namespace ID used by * MediaWiki. Therefore, mainspace pages always have a null namespace, as they have no prefix, * and the namespace of a page will depend on the language of the wiki the user is currently * looking at. * * Examples: * * [[Manchester]] on enwiki will have a namespace of null * * [[Deutschland]] on dewiki will have a namespace of null * * [[User:Deskana]] on enwiki will have a namespace of "User" * * [[Utilisateur:Deskana]] on frwiki will have a namespace of "Utilisateur", even if you got * to the page by going to [[User:Deskana]] and having MediaWiki automatically redirect you. */ // TODO: remove. This legacy code is the localized namespace name (File, Special, Talk, etc) but // are broken. @Nullable private final String namespace; @NonNull private String text; @Nullable private final String fragment; @Nullable private String thumbUrl; @SerializedName("site") @NonNull private final WikiSite wiki; @Nullable private String description; @Nullable private final PageProperties properties; // TODO: remove after the restbase endpoint supports ZH variants. @Nullable private String displayText; /** * Creates a new PageTitle object. * Use this if you want to pass in a fragment portion separately from the title. * * @param prefixedText title of the page with optional namespace prefix * @param fragment optional fragment portion * @param wiki the wiki site the page belongs to * @return a new PageTitle object matching the given input parameters */ public static PageTitle withSeparateFragment(@NonNull String prefixedText, @Nullable String fragment, @NonNull WikiSite wiki) { if (TextUtils.isEmpty(fragment)) { return new PageTitle(prefixedText, wiki, null, (PageProperties) null); } else { // TODO: this class needs some refactoring to allow passing in a fragment // without having to do string manipulations. return new PageTitle(prefixedText + "#" + fragment, wiki, null, (PageProperties) null); } } public PageTitle(@Nullable final String namespace, @NonNull String text, @Nullable String fragment, @Nullable String thumbUrl, @NonNull WikiSite wiki) { this.namespace = namespace; this.text = text; this.fragment = fragment; this.wiki = wiki; this.thumbUrl = thumbUrl; properties = null; } public PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable String description, @Nullable PageProperties properties) { this(text, wiki, thumbUrl, properties); this.description = description; } public PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable String description, @Nullable String displayText) { this(text, wiki, thumbUrl, description); this.displayText = displayText; } public PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable String description) { this(text, wiki, thumbUrl); this.description = description; } public PageTitle(@Nullable String namespace, @NonNull String text, @NonNull WikiSite wiki) { this(namespace, text, null, null, wiki); } public PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl) { this(text, wiki, thumbUrl, (PageProperties) null); } public PageTitle(@Nullable String text, @NonNull WikiSite wiki) { this(text, wiki, null); } private PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable PageProperties properties) { // FIXME: Does not handle mainspace articles with a colon in the title well at all if (TextUtils.isEmpty(text)) { // If empty, this refers to the main page. text = SiteInfoClient.getMainPageForLang(wiki.languageCode()); } String[] fragParts = text.split(" text = fragParts[0]; if (fragParts.length > 1) { this.fragment = decodeURL(fragParts[1]).replace(" ", "_"); } else { this.fragment = null; } String[] parts = text.split(":", -1); if (parts.length > 1) { String namespaceOrLanguage = parts[0]; if (Arrays.asList(Locale.getISOLanguages()).contains(namespaceOrLanguage)) { this.namespace = null; this.wiki = new WikiSite(wiki.authority(), namespaceOrLanguage); } else { this.wiki = wiki; this.namespace = namespaceOrLanguage; } this.text = TextUtils.join(":", Arrays.copyOfRange(parts, 1, parts.length)); } else { this.wiki = wiki; this.namespace = null; this.text = parts[0]; } this.thumbUrl = thumbUrl; this.properties = properties; } @Nullable public String getNamespace() { return namespace; } @NonNull public Namespace namespace() { if (properties != null) { return properties.getNamespace(); } // Properties has the accurate namespace but it doesn't exist. Guess based on title. return Namespace.fromLegacyString(wiki, namespace); } @NonNull public WikiSite getWikiSite() { return wiki; } @NonNull public String getText() { return text.replace(" ", "_"); } @Nullable public String getFragment() { return fragment; } @Nullable public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(@Nullable String thumbUrl) { this.thumbUrl = thumbUrl; } @Nullable public String getDescription() { return description; } public void setDescription(@Nullable String description) { this.description = description; } // This update the text to the API text. public void setText(@NonNull String convertedFromText) { this.text = convertedFromText; } @NonNull public String getDisplayText() { return displayText == null ? getPrefixedText().replace("_", " ") : displayText; } public void setDisplayText(@Nullable String displayText) { this.displayText = displayText; } @Nullable public PageProperties getProperties() { return properties; } public boolean isMainPage() { if (properties != null) { return properties.isMainPage(); } String mainPageTitle = SiteInfoClient.getMainPageForLang(getWikiSite().languageCode()); return mainPageTitle.equals(getDisplayText()); } public String getUri() { return getUriForDomain(getWikiSite().authority()); } public String getUriForAction(String action) { try { return String.format( "%1$s://%2$s/w/index.php?title=%3$s&action=%4$s", getWikiSite().scheme(), getWikiSite().authority(), URLEncoder.encode(getPrefixedText(), "utf-8"), action ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public String getPrefixedText() { // TODO: find a better way to check if the namespace is a ISO Alpha2 Code (two digits country code) return namespace == null ? getText() : StringUtil.addUnderscores(namespace) + ":" + getText(); } /** * Check if the Title represents a File: * * @return true if it is a File page, false if not */ public boolean isFilePage() { return namespace().file(); } /** * Check if the Title represents a special page * * @return true if it is a special page, false if not */ public boolean isSpecial() { return namespace().special(); } /** * Check if the Title represents a talk page * * @return true if it is a talk page, false if not */ public boolean isTalkPage() { return namespace().talk(); } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(wiki, flags); parcel.writeParcelable(properties, flags); parcel.writeString(thumbUrl); parcel.writeString(description); parcel.writeString(displayText); } @Override public boolean equals(Object o) { if (!(o instanceof PageTitle)) { return false; } PageTitle other = (PageTitle)o; // Not using namespace directly since that can be null return StringUtil.normalizedEquals(other.getPrefixedText(), getPrefixedText()) && other.wiki.equals(wiki); } @Override public int hashCode() { int result = getPrefixedText().hashCode(); result = 31 * result + wiki.hashCode(); return result; } @Override public String toString() { return getPrefixedText(); } @Override public int describeContents() { return 0; } private String getUriForDomain(String domain) { try { return String.format( "%1$s://%2$s/%3$s/%4$s%5$s", getWikiSite().scheme(), domain, domain.startsWith(AppLanguageLookUpTable.CHINESE_LANGUAGE_CODE) ? getWikiSite().languageCode() : "wiki", URLEncoder.encode(getPrefixedText(), "utf-8"), (this.fragment != null && this.fragment.length() > 0) ? ("#" + this.fragment) : "" ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private PageTitle(Parcel in) { namespace = in.readString(); text = in.readString(); fragment = in.readString(); wiki = in.readParcelable(WikiSite.class.getClassLoader()); properties = in.readParcelable(PageProperties.class.getClassLoader()); thumbUrl = in.readString(); description = in.readString(); displayText = in.readString(); } }
package com.iskrembilen.quasseldroid.io; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.util.Pair; import com.iskrembilen.quasseldroid.*; import com.iskrembilen.quasseldroid.Network.ConnectionState; import com.iskrembilen.quasseldroid.exceptions.UnsupportedProtocolException; import com.iskrembilen.quasseldroid.io.CustomTrustManager.NewCertificateException; import com.iskrembilen.quasseldroid.qtcomm.*; import com.iskrembilen.quasseldroid.service.CoreConnService; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.cert.CertificateException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class CoreConnection { private static final String TAG = CoreConnection.class.getSimpleName(); private Socket socket; private QDataOutputStream outStream; private QDataInputStream inStream; private Map<Integer, Buffer> buffers; private CoreInfo coreInfo; private Map<Integer, Network> networks; private String address; private int port; private String username; private String password; private boolean ssl; CoreConnService service; private Timer heartbeatTimer; private ReadThread readThread; private boolean initComplete; private int initBacklogBuffers; private int networkInitsLeft; private boolean networkInitComplete; private LinkedList<List<QVariant<?>>> packageQueue; //Used to create the ID of new channels we join private int maxBufferId = 0; private ExecutorService outputExecutor; public CoreConnection(String address, int port, String username, String password, Boolean ssl, CoreConnService parent) { this.address = address; this.port = port; this.username = username; this.password = password; this.ssl = ssl; this.service = parent; outputExecutor = Executors.newSingleThreadExecutor(); readThread = new ReadThread(); readThread.start(); } /** * Checks whether the core is available. */ public boolean isConnected() { return (socket != null && !socket.isClosed() && readThread.running); } /** * requests the core to set a given buffer as read * @param buffer the buffer id to set as read */ public void requestMarkBufferAsRead(int buffer) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestMarkBufferAsRead", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestRemoveBuffer(int buffer) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBuffer", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestTempHideBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBuffer", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requestRemoveBuffer", e); onDisconnected("Lost connection"); } } public void requestPermHideBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBufferPermanently", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requestRemoveBufferPermanently", e); onDisconnected("Lost connection"); } } public void requestDisconnectNetwork(int networkId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("Network", QVariantType.String)); retFunc.add(new QVariant<String>(Integer.toString(networkId), QVariantType.String)); retFunc.add(new QVariant<String>("requestDisconnect", QVariantType.ByteArray)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestConnectNetwork(int networkId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("Network", QVariantType.String)); retFunc.add(new QVariant<String>(Integer.toString(networkId), QVariantType.String)); retFunc.add(new QVariant<String>("requestConnect", QVariantType.ByteArray)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestSetLastMsgRead(int buffer, int msgid) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestSetLastSeenMsg", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(msgid, "MsgId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestSetMarkerLine(int buffer, int msgid) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestSetMarkerLine", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(msgid, "MsgId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } /** * Requests to unhide a temporarily hidden buffer */ public void requestUnhideTempHiddenBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestAddBuffer", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); retFunc.add(new QVariant<Integer>(networks.get(buffers.get(bufferId).getInfo().networkId).getBufferCount(), QVariantType.Int)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requesting backlog", e); onDisconnected("Lost connection"); } } /** * Requests the unread backlog for a given buffer. */ public void requestUnreadBacklog(int buffer) { requestBacklog(buffer, buffers.get(buffer).getLastSeenMessage()); } /** * Requests moar backlog for a give buffer * @param buffer Buffer id to request moar for */ public void requestMoreBacklog(int buffer, int amount) { if (buffers.get(buffer).getUnfilteredSize()==0) { requestBacklog(buffer, -1, -1, amount); }else { // Log.e(TAG, "GETTING: "+buffers.get(buffer).getUnfilteredBacklogEntry(0).messageId); requestBacklog(buffer, -1, buffers.get(buffer).getUnfilteredBacklogEntry(0).messageId, amount); } } /** * Requests all backlog from a given message ID until the current. */ private void requestBacklog(int buffer, int firstMsgId) { requestBacklog(buffer, firstMsgId, -1); } /** * Requests backlog between two given message IDs. */ private void requestBacklog(int buffer, int firstMsgId, int lastMsgId) { requestBacklog(buffer, firstMsgId, lastMsgId, 10); //TODO: get the number from the shared preferences } private void requestBacklog(int buffer, int firstMsgId, int lastMsgId, int maxAmount) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BacklogManager", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestBacklog", QVariantType.String)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(firstMsgId, "MsgId")); retFunc.add(new QVariant<Integer>(lastMsgId, "MsgId")); retFunc.add(new QVariant<Integer>(maxAmount, QVariantType.Int)); retFunc.add(new QVariant<Integer>(0, QVariantType.Int)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requesting backlog", e); onDisconnected("Lost connection"); } } /** * Sends an IRC message to a given buffer * @param buffer buffer to send to * @param message content of message */ public void sendMessage(int buffer, String message) { if (message.charAt(0) == '/') { String t[] = message.split(" "); message = t[0].toUpperCase(); if (t.length > 1){ StringBuilder tmpMsg = new StringBuilder(message); for (int i=1; i<t.length; i++) { tmpMsg.append(' '); tmpMsg.append(t[i]); } message = tmpMsg.toString(); } } else { message = "/SAY " + message; } List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.RpcCall.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("2sendInput(BufferInfo,QString)", QVariantType.String)); retFunc.add(new QVariant<BufferInfo>(buffers.get(buffer).getInfo(), "BufferInfo")); retFunc.add(new QVariant<String>(message, QVariantType.String)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while sending message", e); onDisconnected("Lost connection"); } } /** * Initiates a connection. * @throws EmptyQVariantException * @throws UnsupportedProtocolException */ public void connect() throws UnknownHostException, IOException, GeneralSecurityException, CertificateException, NewCertificateException, EmptyQVariantException, UnsupportedProtocolException { // START CREATE SOCKETS SocketFactory factory = (SocketFactory)SocketFactory.getDefault(); socket = (Socket)factory.createSocket(address, port); socket.setKeepAlive(true); outStream = new QDataOutputStream(socket.getOutputStream()); // END CREATE SOCKETS // START CLIENT INFO updateInitProgress("Sending client info..."); Map<String, QVariant<?>> initial = new HashMap<String, QVariant<?>>(); DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy HH:mm:ss"); Date date = new Date(); initial.put("ClientDate", new QVariant<String>(dateFormat.format(date), QVariantType.String)); initial.put("UseSsl", new QVariant<Boolean>(ssl, QVariantType.Bool)); initial.put("ClientVersion", new QVariant<String>("v0.6.1 (dist-<a href='http://git.quassel-irc.org/?p=quassel.git;a=commit;h=611ebccdb6a2a4a89cf1f565bee7e72bcad13ffb'>611ebcc</a>)", QVariantType.String)); initial.put("UseCompression", new QVariant<Boolean>(false, QVariantType.Bool)); initial.put("MsgType", new QVariant<String>("ClientInit", QVariantType.String)); initial.put("ProtocolVersion", new QVariant<Integer>(10, QVariantType.Int)); sendQVariantMap(initial); // END CLIENT INFO // START CORE INFO updateInitProgress("Getting core info..."); inStream = new QDataInputStream(socket.getInputStream()); Map<String, QVariant<?>> reply = readQVariantMap(); coreInfo = new CoreInfo(); coreInfo.setCoreFeatures((Integer)reply.get("CoreFeatures").getData()); coreInfo.setCoreInfo((String)reply.get("CoreInfo").getData()); coreInfo.setSupportSsl((Boolean)reply.get("SupportSsl").getData()); coreInfo.setCoreDate(new Date((String)reply.get("CoreDate").getData())); coreInfo.setCoreStartTime((GregorianCalendar)reply.get("CoreStartTime").getData()); String coreVersion = (String)reply.get("CoreVersion").getData(); coreVersion = coreVersion.substring(coreVersion.indexOf("v")+1, coreVersion.indexOf(" ")); coreInfo.setCoreVersion(coreVersion); coreInfo.setConfigured((Boolean)reply.get("Configured").getData()); coreInfo.setLoginEnabled((Boolean)reply.get("LoginEnabled").getData()); coreInfo.setMsgType((String)reply.get("MsgType").getData()); coreInfo.setProtocolVersion(((Long)reply.get("ProtocolVersion").getData()).intValue()); coreInfo.setSupportsCompression((Boolean)reply.get("SupportsCompression").getData()); Matcher matcher = Pattern.compile("(\\d+)\\W(\\d+)\\W", Pattern.CASE_INSENSITIVE).matcher(coreInfo.getCoreVersion()); Log.i(TAG, "Core version: " + coreInfo.getCoreVersion()); int version, release; if (matcher.find()) { version = Integer.parseInt(matcher.group(1)); release = Integer.parseInt(matcher.group(2)); } else { throw new UnsupportedProtocolException("Can't match core version: " + coreInfo.getCoreVersion()); } //Check that the protocol version is atleast 10 and the version is above 0.6.0 if(coreInfo.getProtocolVersion()<10 || !(version>0 || (version==0 && release>=6))) throw new UnsupportedProtocolException("Protocol version is old: "+coreInfo.getProtocolVersion()); /*for (String key : reply.keySet()) { System.out.println("\t" + key + " : " + reply.get(key)); }*/ // END CORE INFO // START SSL CONNECTION if (ssl) { Log.d(TAG, "Using ssl"); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager [] { new CustomTrustManager(this) }; sslContext.init(null, trustManagers, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address, port, true); sslSocket.setEnabledProtocols(new String[] {"SSLv3"}); sslSocket.setUseClientMode(true); updateInitProgress("Starting ssl handshake"); sslSocket.startHandshake(); Log.d(TAG, "Ssl handshake complete"); inStream = new QDataInputStream(sslSocket.getInputStream()); outStream = new QDataOutputStream(sslSocket.getOutputStream()); socket = sslSocket; } else { Log.w(TAG, "SSL DISABLED!"); } // FINISHED SSL CONNECTION // START LOGIN updateInitProgress("Logging in..."); Map<String, QVariant<?>> login = new HashMap<String, QVariant<?>>(); login.put("MsgType", new QVariant<String>("ClientLogin", QVariantType.String)); login.put("User", new QVariant<String>(username, QVariantType.String)); login.put("Password", new QVariant<String>(password, QVariantType.String)); sendQVariantMap(login); // FINISH LOGIN // START LOGIN ACK reply = readQVariantMap(); if (!reply.get("MsgType").toString().equals("ClientLoginAck")) throw new GeneralSecurityException("Invalid password?"); // END LOGIN ACK // START SESSION INIT updateInitProgress("Receiving session state..."); reply = readQVariantMap(); /*System.out.println("SESSION INIT: "); for (String key : reply.keySet()) { System.out.println("\t" + key + " : " + reply.get(key)); }*/ Map<String, QVariant<?>> sessionState = (Map<String, QVariant<?>>) reply.get("SessionState").getData(); List<QVariant<?>> networkIds = (List<QVariant<?>>) sessionState.get("NetworkIds").getData(); networks = new HashMap<Integer, Network>(networkIds.size()); for (QVariant<?> networkId: networkIds) { Integer id = (Integer) networkId.getData(); networks.put(id, new Network(id)); } List<QVariant<?>> bufferInfos = (List<QVariant<?>>) sessionState.get("BufferInfos").getData(); buffers = new HashMap<Integer, Buffer>(bufferInfos.size()); QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); ArrayList<Integer> bufferIds = new ArrayList<Integer>(); for (QVariant<?> bufferInfoQV: bufferInfos) { BufferInfo bufferInfo = (BufferInfo)bufferInfoQV.getData(); Buffer buffer = new Buffer(bufferInfo, dbHelper); buffers.put(bufferInfo.id, buffer); if(bufferInfo.type==BufferInfo.Type.StatusBuffer){ networks.get(bufferInfo.networkId).setStatusBuffer(buffer); }else{ networks.get(bufferInfo.networkId).addBuffer(buffer); } bufferIds.add(bufferInfo.id); } dbHelper.open(); dbHelper.cleanupEvents(bufferIds.toArray(new Integer[bufferIds.size()])); dbHelper.close(); // END SESSION INIT // Now the fun part starts, where we play signal proxy // START SIGNAL PROXY INIT updateInitProgress("Requesting network and buffer information..."); // We must do this here, to get network names early enough networkInitsLeft = 0; networkInitComplete = false; for(Network network: networks.values()) { networkInitsLeft += 1; sendInitRequest("Network", Integer.toString(network.getId())); } sendInitRequest("BufferSyncer", ""); //sendInitRequest("BufferViewManager", ""); this is about where this should be, but don't know what it does sendInitRequest("BufferViewConfig", "0"); int backlogAmout = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(service).getString(service.getString(R.string.preference_initial_backlog_limit), "1")); initBacklogBuffers = 0; for (Buffer buffer:buffers.values()) { initBacklogBuffers += 1; requestMoreBacklog(buffer.getInfo().id, backlogAmout); } TimerTask sendPingAction = new TimerTask() { public void run() { List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>(); packedFunc.add(new QVariant<Integer>(RequestType.HeartBeat.getValue(), QVariantType.Int)); packedFunc.add(new QVariant<Calendar>(Calendar.getInstance(), QVariantType.Time)); try { sendQVariantList(packedFunc); } catch (IOException e) { Log.e(TAG, "IOException while sending ping", e); onDisconnected("Lost connection"); } } }; heartbeatTimer = new Timer(); heartbeatTimer.schedule(sendPingAction, 30000, 30000); // Send heartbeats every 30 seconds // END SIGNAL PROXY updateInitProgress("Connection established..."); // Notify the UI we have an open socket Message msg = service.getHandler().obtainMessage(R.id.CONNECTING); msg.sendToTarget(); initComplete = false; } public void closeConnection() { readThread.running = false; //tell the while loop to quit } /** * Disconnect from the core, as best as we can. * */ public synchronized void onDisconnected(String informationMessage) { Log.d(TAG, "Disconnected so closing connection"); if(readThread.running) { service.getHandler().obtainMessage(R.id.LOST_CONNECTION, informationMessage).sendToTarget(); } closeConnection(); } /** * Type of a given request (should be pretty self-explanatory). */ private enum RequestType { Invalid(0), Sync(1), RpcCall(2), InitRequest(3), InitData(4), HeartBeat(5), HeartBeatReply(6); // Below this line; java sucks. Hard. int value; RequestType(int value){ this.value = value; } public int getValue(){ return value; } public static RequestType getForVal(int val) { for (RequestType type: values()) { if (type.value == val) return type; } return Invalid; } } /** * Convenience function to send a given QVariant. * @param data QVariant to send. */ private synchronized void sendQVariant(QVariant<?> data) throws IOException { outputExecutor.execute(new OutputRunnable(data)); } private class OutputRunnable implements Runnable { private QVariant<?> data; public OutputRunnable(QVariant<?> data) { this.data = data; } @Override public void run() { try { // See how much data we're going to send //TODO sandsmark: there must be a better way to to this then create new streams each time.... ByteArrayOutputStream baos = new ByteArrayOutputStream(); QDataOutputStream bos = new QDataOutputStream(baos); QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, bos, data); // Tell the other end how much data to expect outStream.writeUInt(bos.size(), 32); // Sanity check, check that we can decode our own stuff before sending it off //QDataInputStream bis = new QDataInputStream(new ByteArrayInputStream(baos.toByteArray())); //QMetaTypeRegistry.instance().getTypeForId(QMetaType.Type.QVariant.getValue()).getSerializer().unserialize(bis, DataStreamVersion.Qt_4_2); // Send data QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, outStream, data); bos.close(); baos.close(); } catch (IOException e) { onDisconnected("Lost connection while sending information"); } } } /** * Convenience function to send a given QVariantMap. * @param data the given QVariantMap to send. */ private void sendQVariantMap(Map<String, QVariant<?>> data) throws IOException { QVariant<Map<String, QVariant<?>>> bufstruct = new QVariant<Map<String, QVariant<?>>>(data, QVariantType.Map); sendQVariant(bufstruct); } /** * A convenience function to send a given QVariantList. * @param data The QVariantList to send. */ private void sendQVariantList(List<QVariant<?>> data) throws IOException { QVariant<List<QVariant<?>>> bufstruct = new QVariant<List<QVariant<?>>>(data, QVariantType.List); sendQVariant(bufstruct); } /** * A convenience function to read a QVariantMap. * @throws EmptyQVariantException */ private Map<String, QVariant<?>> readQVariantMap() throws IOException, EmptyQVariantException { // Length of this packet (why do they send this? noone knows!). inStream.readUInt(32); QVariant <Map<String, QVariant<?>>> v = (QVariant <Map<String, QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream); Map<String, QVariant<?>>ret = (Map<String, QVariant<?>>)v.getData(); // System.out.println(ret.toString()); return ret; } /** * A convenience function to read a QVariantList. * @throws EmptyQVariantException */ private List<QVariant<?>> readQVariantList() throws IOException, EmptyQVariantException { inStream.readUInt(32); // Length QVariant <List<QVariant<?>>> v = (QVariant <List<QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream); List<QVariant<?>>ret = (List<QVariant<?>>)v.getData(); // System.out.println(ret.toString()); return ret; } /** * Convenience function to request an init of a given object. * @param className The class name of the object we want. * @param objectName The name of the object we want. */ private void sendInitRequest(String className, String objectName) throws IOException { List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>(); packedFunc.add(new QVariant<Integer>(RequestType.InitRequest.getValue(), QVariantType.Int)); packedFunc.add(new QVariant<String>(className, QVariantType.String)); packedFunc.add(new QVariant<String>(objectName, QVariantType.String)); sendQVariantList(packedFunc); } private void updateInitProgress(String message) { Log.i(TAG, message); service.getHandler().obtainMessage(R.id.INIT_PROGRESS, message).sendToTarget(); } private void updateInitDone() { initComplete = true; service.getHandler().obtainMessage(R.id.INIT_DONE).sendToTarget(); } private class ReadThread extends Thread { boolean running = false; CountDownTimer checkAlive = new CountDownTimer(180000, 180000) { @Override public void onTick(long millisUntilFinished) { //Do nothing, no use } @Override public void onFinish() { Log.i(TAG, "Timer finished, disconnection from core"); CoreConnection.this.onDisconnected("Timed out"); } }; public void run() { String errorMessage = null; try { errorMessage = doRun(); if(errorMessage != null) onDisconnected(errorMessage); } catch (EmptyQVariantException e) { Log.e(TAG, "Protocol error", e); onDisconnected("Protocol error!"); } } public String doRun() throws EmptyQVariantException { this.running = true; packageQueue = new LinkedList<List<QVariant<?>>>(); try { connect(); } catch (UnknownHostException e) { return "Unknown host!"; } catch (UnsupportedProtocolException e) { service.getHandler().obtainMessage(R.id.UNSUPPORTED_PROTOCOL).sendToTarget(); Log.w(TAG, e); closeConnection(); return null; } catch (IOException e) { if(e.getCause() instanceof NewCertificateException) { service.getHandler().obtainMessage(R.id.INVALID_CERTIFICATE, ((NewCertificateException)e.getCause()).hashedCert()).sendToTarget(); closeConnection(); }else{ e.printStackTrace(); return "IO error while connecting! " + e.getMessage(); } return null; } catch (CertificateException e) { service.getHandler().obtainMessage(R.id.INVALID_CERTIFICATE, "Invalid SSL certificate from core!").sendToTarget(); closeConnection(); return null; } catch (GeneralSecurityException e) { Log.w(TAG, "Invalid username/password combination"); return "Invalid username/password combination."; } catch (EmptyQVariantException e) { return "IO error while connecting!"; } List<QVariant<?>> packedFunc; final long startWait = System.currentTimeMillis(); while (running) { try { if(networkInitComplete && packageQueue.size() > 0) { Log.e(TAG, "Queue not empty, retrive element"); packedFunc = packageQueue.poll(); } else { packedFunc = readQVariantList(); } //Log.i(TAG, "Slow core is slow: " + (System.currentTimeMillis() - startWait) + "ms"); //We received a package, aka we are not disconnected, restart timer //Log.i(TAG, "Package reviced, reseting countdown"); checkAlive.cancel(); checkAlive.start(); //if network init is not complete and we receive anything but a network init object, queue it if(!networkInitComplete) { if(RequestType.getForVal((Integer)packedFunc.get(0).getData()) != RequestType.InitData && !((String)packedFunc.get(1).getData()).equals("Network")) { Log.e(TAG, "Package not network, queueing it"); packageQueue.add(packedFunc); continue; //Read next packageFunc } } long start = System.currentTimeMillis(); RequestType type = RequestType.getForVal((Integer)packedFunc.remove(0).getData()); String className = "", objectName; /* * Here we handle different calls from the core. */ switch (type) { /* * A heartbeat is a simple request sent with fixed intervals, * to make sure that both ends are still connected (apparently, TCP isn't good enough). * TODO: We should use this, and disconnect automatically when the core has gone away. */ case HeartBeat: Log.d(TAG, "Got heartbeat"); List<QVariant<?>> packet = new LinkedList<QVariant<?>>(); packet.add(new QVariant<Integer>(RequestType.HeartBeatReply.getValue(), QVariantType.Int)); packet.add(new QVariant<Calendar>(Calendar.getInstance(), QVariantType.Time)); try { sendQVariantList(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case HeartBeatReply: Log.d(TAG, "Got heartbeat reply"); if (packedFunc.size() != 0) { Calendar calendarNow = Calendar.getInstance(); Calendar calendarSent = (Calendar) packedFunc.remove(0).getData(); int latency = (int)(calendarNow.getTimeInMillis() - calendarSent.getTimeInMillis()) / 2; Log.d(TAG, "Latency: " + latency); service.getHandler().obtainMessage(R.id.SET_CORE_LATENCY, latency, 0, null).sendToTarget(); } break; /* * This is when the core send us a new object to create. * Since we don't actually create objects, we parse out the fields * in the objects manually. */ case InitData: // The class name and name of the object we are about to create className = (String) packedFunc.remove(0).getData(); objectName = (String) packedFunc.remove(0).getData(); /* * An object representing an IRC network, containing users and channels ("buffers"). */ if (className.equals("Network")) { Log.d(TAG, "InitData: Network"); int networkId = Integer.parseInt(objectName); Network network = networks.get(networkId); Map<String, QVariant<?>> initMap = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); // Store the network name and associated nick for "our" user network.setNick((String) initMap.get("myNick").getData()); network.setName((String) initMap.get("networkName").getData()); network.setLatency((Integer) initMap.get("latency").getData()); network.setServer((String) initMap.get("currentServer").getData()); boolean isConnected = (Boolean)initMap.get("isConnected").getData(); if(isConnected) network.setConnected(true); else network.setConnectionState(ConnectionState.Disconnected); if(network.getStatusBuffer() != null) network.getStatusBuffer().setActive(isConnected); //we got enough info to tell service we are parsing network Log.i(TAG, "Started parsing network " + network.getName()); updateInitProgress("Receiving network: " +network.getName()); // Horribly nested maps Map<String, QVariant<?>> usersAndChans = (Map<String, QVariant<?>>) initMap.get("IrcUsersAndChannels").getData(); Map<String, QVariant<?>> channels = (Map<String, QVariant<?>>) usersAndChans.get("channels").getData(); //Parse out user objects for network Map<String, QVariant<?>> userObjs = (Map<String, QVariant<?>>) usersAndChans.get("users").getData(); ArrayList<IrcUser> ircUsers = new ArrayList<IrcUser>(); HashMap<String, IrcUser> userTempMap = new HashMap<String, IrcUser>(); for (Map.Entry<String, QVariant<?>> element: userObjs.entrySet()) { IrcUser user = new IrcUser(); user.name = element.getKey(); Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) element.getValue().getData(); user.away = (Boolean) map.get("away").getData(); user.awayMessage = (String) map.get("awayMessage").getData(); user.ircOperator = (String) map.get("ircOperator").getData(); user.nick = (String) map.get("nick").getData(); user.channels = (List<String>) map.get("channels").getData(); ircUsers.add(user); userTempMap.put(user.nick, user); } network.setUserList(ircUsers); // Parse out the topics for (QVariant<?> channel: channels.values()) { Map<String, QVariant<?>> chan = (Map<String, QVariant<?>>) channel.getData(); String chanName = (String)chan.get("name").getData(); Map<String, QVariant<?>> userModes = (Map<String, QVariant<?>>) chan.get("UserModes").getData(); String topic = (String)chan.get("topic").getData(); boolean foundChannel = false; for (Buffer buffer: network.getBuffers().getRawBufferList()) { if (buffer.getInfo().name.equalsIgnoreCase(chanName)) { buffer.setTopic(topic); buffer.setActive(true); ArrayList<Pair<IrcUser, String>> usersToAdd = new ArrayList<Pair<IrcUser, String>>(); for(Entry<String, QVariant<?>> nick : userModes.entrySet()) { IrcUser user = userTempMap.get(nick.getKey()); if(user == null) { Log.e(TAG, "Channel has nick that is does not match any user on the network: " + nick); //TODO: WHY THE FUCK IS A USER NULL HERE? HAPPENS ON MY OWN CORE, BUT NOT ON DEBUG CORE CONNECTED TO SAME CHANNEL. QUASSEL BUG? WHAT TO DO ABOUT IT //this sync request did not seem to do anything // sendInitRequest("IrcUser", network.getId()+"/" +nick.getKey()); continue; } usersToAdd.add(new Pair<IrcUser, String>(user, (String)nick.getValue().getData())); } buffer.getUsers().addUsers(usersToAdd); foundChannel = true; break; } } if(!foundChannel) throw new RuntimeException("A channel in a network has no coresponding buffer object " + chanName); } Log.i(TAG, "Sending network " + network.getName() + " to service"); service.getHandler().obtainMessage(R.id.ADD_NETWORK, network).sendToTarget(); //sendInitRequest("BufferSyncer", ""); /*sendInitRequest("BufferViewManager", ""); sendInitRequest("AliasManager", ""); sendInitRequest("NetworkConfig", "GlobalNetworkConfig"); sendInitRequest("IgnoreListManager", "");*/ List<QVariant<?>> reqPackedFunc = new LinkedList<QVariant<?>>(); reqPackedFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); reqPackedFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); reqPackedFunc.add(new QVariant<String>("", QVariantType.String)); reqPackedFunc.add(new QVariant<String>("requestPurgeBufferIds", QVariantType.String)); sendQVariantList(reqPackedFunc); if(!initComplete) { networkInitsLeft -= 1; if(networkInitsLeft <= 0) networkInitComplete = true; } long endWait = System.currentTimeMillis(); Log.w(TAG, "Network parsed, took: "+(endWait-startWait)); /* * An object that is used to synchronize metadata about buffers, * like the last seen message, marker lines, etc. */ } else if (className.equals("BufferSyncer")) { Log.d(TAG, "InitData: BufferSyncer"); // Parse out the last seen messages updateInitProgress("Receiving last seen and marker lines"); List<QVariant<?>> lastSeen = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("LastSeenMsg").getData(); for (int i=0; i<lastSeen.size(); i+=2) { int bufferId = (Integer)lastSeen.get(i).getData(); int msgId = (Integer)lastSeen.get(i+1).getData(); if (buffers.containsKey(bufferId)){ // We only care for buffers we have open Message msg = service.getHandler().obtainMessage(R.id.SET_LAST_SEEN_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); }else{ Log.e(TAG, "Getting last seen message for buffer we dont have " +bufferId); } } // Parse out the marker lines for buffers if the core supports them QVariant<?> rawMarkerLines = ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("MarkerLines"); if(rawMarkerLines != null) { List<QVariant<?>> markerLines = (List<QVariant<?>>) rawMarkerLines.getData(); for (int i=0; i<markerLines.size(); i+=2) { int bufferId = (Integer)markerLines.get(i).getData(); int msgId = (Integer)markerLines.get(i+1).getData(); if (buffers.containsKey(bufferId)){ Message msg = service.getHandler().obtainMessage(R.id.SET_MARKERLINE_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); }else{ Log.e(TAG, "Getting markerlinemessage for buffer we dont have " +bufferId); } } }else{ Log.e(TAG, "Marker lines are null in BufferSyncer, should not happen"); } /* * A class representing another user on a given IRC network. */ } else if (className.equals("IrcUser")) { Log.d(TAG, "InitData: IrcUser"); Map<String, QVariant<?>> userMap = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("awayMessage", (String)userMap.get("awayMessage").getData()); bundle.putSerializable("channels", (ArrayList<String>) userMap.get("channels").getData()); bundle.putBoolean("away", (Boolean)userMap.get("away").getData()); bundle.putString("ircOperator", (String) userMap.get("ircOperator").getData()); bundle.putString("nick", (String) userMap.get("nick").getData()); Message msg = service.getHandler().obtainMessage(R.id.NEW_USER_INFO); int networkId = Integer.parseInt(objectName.split("/", 2)[0]); msg.obj = bundle; msg.arg1 = networkId; msg.sendToTarget(); } else if (className.equals("IrcChannel")) { Log.d(TAG, "InitData: IrcChannel"); // System.out.println(packedFunc.toString() + " Object: "+objectName); // topic, UserModes, password, ChanModes, name //For now only topic seems useful here, rest is added other places Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); String bufferName = (String)map.get("name").getData(); String topic = (String)map.get("topic").getData(); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); for(Buffer buffer : networks.get(networkId).getBuffers().getRawBufferList()) { if(buffer.getInfo().name.equalsIgnoreCase(bufferName)) { Message msg = service.getHandler().obtainMessage(R.id.CHANNEL_TOPIC_CHANGED, networkId, buffer.getInfo().id, topic); msg.sendToTarget(); msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ACTIVE,buffer.getInfo().id, 0, true); msg.sendToTarget(); break; } } } else if (className.equals("BufferViewConfig")) { Log.d(TAG, "InitData: BufferViewConfig"); Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); List<QVariant<?>> tempList = (List<QVariant<?>>) map.get("TemporarilyRemovedBuffers").getData(); List<QVariant<?>> permList = (List<QVariant<?>>) map.get("RemovedBuffers").getData(); List<QVariant<?>> orderList = (List<QVariant<?>>) map.get("BufferList").getData(); updateInitProgress("Receiving buffer list information"); BufferCollection.orderAlphabetical = (Boolean) map.get("sortAlphabetically").getData(); //TODO: mabye send this in a bulk to the service so it wont sort and shit every time for (QVariant bufferId: tempList) { if (!buffers.containsKey(bufferId.getData())) { Log.e(TAG, "TempList, dont't have buffer: " +bufferId.getData()); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId.getData()); msg.obj = true; msg.sendToTarget(); } for (QVariant bufferId: permList) { if (!buffers.containsKey(bufferId.getData())) { Log.e(TAG, "TempList, dont't have buffer: " +bufferId.getData()); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId.getData()); msg.obj = true; msg.sendToTarget(); } int order = 0; for (QVariant bufferId: orderList) { int id = (Integer)bufferId.getData(); if(id > maxBufferId) { maxBufferId = id; } if (!buffers.containsKey(id)) { System.err.println("got buffer info for non-existant buffer id: " + id); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ORDER); msg.arg1 = id; msg.arg2 = order; //FIXME: DEBUG PISS REMOVE ArrayList<Integer> keysString = new ArrayList<Integer>(); ArrayList<Integer> buffersString = new ArrayList<Integer>(); for(Entry<Integer, Buffer> b : buffers.entrySet()) { keysString.add(b.getKey()); buffersString.add(b.getValue().getInfo().id); } Bundle bundle = new Bundle(); bundle.putIntegerArrayList("keys", keysString); bundle.putIntegerArrayList("buffers", buffersString); msg.obj = bundle; msg.sendToTarget(); order++; } updateInitProgress("Receiving backlog"); } /* * There are several objects that we don't care about (at the moment). */ else { Log.i(TAG, "Unparsed InitData: " + className + "(" + objectName + ")."); } break; /* * Sync requests are sent by the core whenever an object needs to be updated. * Again, we just parse out whatever we need manually */ case Sync: /* See above; parse out information about object, * and additionally a sync function name. */ Object foo = packedFunc.remove(0).getData(); //System.out.println("FUCK" + foo.toString() + " balle " + foo.getClass().getName()); /*if (foo.getClass().getName().equals("java.nio.ReadWriteHeapByteBuffer")) { try { System.out.println("faen i helvete: " + new String(((ByteBuffer)foo).array(), "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ className = (String)foo; // This is either a byte buffer or a string objectName = (String) packedFunc.remove(0).getData(); String function = packedFunc.remove(0).toString(); /* * The BacklogManager object is responsible for synchronizing backlog * between the core and the client. * * The receiveBacklog function is called in the client with a given (requested) * amount of messages. */ if (className.equals("BacklogManager") && function.equals("receiveBacklog")) { Log.d(TAG, "Sync: BacklogManager -> receiveBacklog"); /* Here we first just dump some unused data; * the buffer id is embedded in the message itself (in a bufferinfo object), * the rest of the arguments aren't used at all, apparently. */ packedFunc.remove(0); // Buffer ID (Integer) packedFunc.remove(0); // first message packedFunc.remove(0); // last message packedFunc.remove(0); // limit to how many messages to fetch packedFunc.remove(0); // additional messages to fetch List<QVariant<?>> data = (List<QVariant<?>>)(packedFunc.remove(0).getData()); Collections.reverse(data); // Apparently, we receive them in the wrong order // Send our the backlog messages to our listeners for (QVariant<?> message: data) { Message msg = service.getHandler().obtainMessage(R.id.NEW_BACKLOGITEM_TO_SERVICE); msg.obj = message.getData(); msg.sendToTarget(); } if(!initComplete) { //We are still initializing backlog for the first time initBacklogBuffers -= 1; if(initBacklogBuffers<=0) { updateInitDone(); } } /* * The addIrcUser function in the Network class is called whenever a new * IRC user appears on a given network. */ } else if (className.equals("Network") && function.equals("addIrcUser")) { Log.d(TAG, "Sync: Network -> addIrcUser"); String nick = (String) packedFunc.remove(0).getData(); IrcUser user = new IrcUser(); user.nick = nick.split("!")[0]; //If not done then we can add it right here, if we try to send it we might crash because service don't have the network yet if(!initComplete) { networks.get(Integer.parseInt(objectName)).onUserJoined(user); } else { service.getHandler().obtainMessage(R.id.NEW_USER_ADDED, Integer.parseInt(objectName), 0, user).sendToTarget(); } sendInitRequest("IrcUser", objectName+"/" + nick.split("!")[0]); } else if (className.equals("Network") && function.equals("setConnectionState")) { Log.d(TAG, "Sync: Network -> setConnectionState"); int networkId = Integer.parseInt(objectName); Network.ConnectionState state = ConnectionState.getForValue((Integer)packedFunc.remove(0).getData()); //If network has no status buffer it is the first time we are connecting to it if(state == ConnectionState.Connecting && networks.get(networkId).getStatusBuffer() == null) { //Create the new buffer object for status buffer QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); BufferInfo info = new BufferInfo(); maxBufferId += 1; info.id = maxBufferId; info.networkId = networkId; info.type = BufferInfo.Type.StatusBuffer; Buffer buffer = new Buffer(info, dbHelper); buffers.put(info.id, buffer); service.getHandler().obtainMessage(R.id.SET_STATUS_BUFFER, networkId, 0, buffer).sendToTarget(); } service.getHandler().obtainMessage(R.id.SET_CONNECTION_STATE, networkId, 0, state).sendToTarget(); } else if (className.equals("Network") && function.equals("addIrcChannel")) { Log.d(TAG, "Sync: Network -> addIrcChannel"); int networkId = Integer.parseInt(objectName); String bufferName = (String) packedFunc.remove(0).getData(); System.out.println(bufferName); boolean hasBuffer = false; for(Buffer buffer : networks.get(networkId).getBuffers().getRawBufferList()) { if(buffer.getInfo().name.equalsIgnoreCase(bufferName)) { hasBuffer = true; } } if(!hasBuffer) { //Create the new buffer object QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); BufferInfo info = new BufferInfo(); info.name = bufferName; maxBufferId += 1; info.id = maxBufferId; info.networkId = networkId; info.type = BufferInfo.Type.ChannelBuffer; Buffer buffer = new Buffer(info, dbHelper); buffers.put(info.id, buffer); Message msg = service.getHandler().obtainMessage(R.id.NEW_BUFFER_TO_SERVICE, buffer); msg.sendToTarget(); } sendInitRequest("IrcChannel", objectName+"/" + bufferName); } else if (className.equals("Network") && function.equals("setConnected")) { Log.d(TAG, "Sync: Network -> setConnected"); boolean connected = (Boolean) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_CONNECTED, networkId, 0, connected).sendToTarget(); } else if (className.equals("Network") && function.equals("setMyNick")) { Log.d(TAG, "Sync: Network -> setMyNick"); String nick = (String) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_MY_NICK, networkId, 0, nick).sendToTarget(); } else if (className.equals("Network") && function.equals("setLatency")) { Log.d(TAG, "Sync: Network -> setLatency"); int networkLatency = (Integer) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_NETWORK_LATENCY, networkId, networkLatency, null).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("partChannel")) { Log.d(TAG, "Sync: IrcUser -> partChannel"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String userName = tmp[1]; Bundle bundle = new Bundle(); bundle.putString("nick", userName); bundle.putString("buffer", (String)packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.USER_PARTED, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("quit")) { Log.d(TAG, "Sync: IrcUser -> quit"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String userName = tmp[1]; service.getHandler().obtainMessage(R.id.USER_QUIT, networkId, 0, userName).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setNick")) { Log.d(TAG, "Sync: IrcUser -> setNick"); /* * Does nothing, Why would we need a sync call, when we got a RPC call about renaming the user object */ } else if (className.equals("IrcUser") && function.equals("setServer")) { Log.d(TAG, "Sync: IrcUser -> setServer"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putString("server", (String) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_SERVER, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setAway")) { Log.d(TAG, "Sync: IrcUser -> setAway"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putBoolean("away", (Boolean) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_AWAY, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setRealName")) { Log.d(TAG, "Sync: IrcUser -> setRealName"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putString("realname", (String) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_REALNAME, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcChannel") && function.equals("joinIrcUsers")) { Log.d(TAG, "Sync: IrcChannel -> joinIrcUsers"); List<String> nicks = (List<String>)packedFunc.remove(0).getData(); List<String> modes = (List<String>)packedFunc.remove(0).getData(); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String bufferName = tmp[1]; for(int i=0; i<nicks.size();i++) { Bundle bundle = new Bundle(); bundle.putString("nick", nicks.get(i)); bundle.putString("mode", modes.get(i)); bundle.putString("buffername", bufferName); service.getHandler().obtainMessage(R.id.USER_JOINED, networkId, 0, bundle).sendToTarget(); } } else if (className.equals("IrcChannel") && function.equals("addUserMode")) { Log.d(TAG, "Sync: IrcChannel -> addUserMode"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String channel = tmp[1]; String nick = (String) packedFunc.remove(0).getData(); String changedMode = (String) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("nick", nick); bundle.putString("mode", changedMode); bundle.putString("channel", channel); service.getHandler().obtainMessage(R.id.USER_ADD_MODE, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcChannel") && function.equals("removeUserMode")) { Log.d(TAG, "Sync: IrcChannel -> removeUserMode"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String channel = tmp[1]; String nick = (String) packedFunc.remove(0).getData(); String changedMode = (String) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("nick", nick); bundle.putString("mode", changedMode); bundle.putString("channel", channel); service.getHandler().obtainMessage(R.id.USER_REMOVE_MODE, networkId, 0, bundle).sendToTarget(); } else if (className.equals("BufferSyncer") && function.equals("setLastSeenMsg")) { Log.d(TAG, "Sync: BufferSyncer -> setLastSeenMsg"); int bufferId = (Integer) packedFunc.remove(0).getData(); int msgId = (Integer) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.SET_LAST_SEEN_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); } else if (className.equals("BufferSyncer") && function.equals("setMarkerLine")) { Log.d(TAG, "Sync: BufferSyncer -> setMarkerLine"); int bufferId = (Integer) packedFunc.remove(0).getData(); int msgId = (Integer) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.SET_MARKERLINE_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); /* * markBufferAsRead is called whenever a given buffer is set as read by the core. */ } else if (className.equals("BufferSyncer") && function.equals("markBufferAsRead")) { Log.d(TAG, "Sync: BufferSyncer -> markBufferAsRead"); //TODO: this basicly does shit. So find out if it effects anything and what it should do //int buffer = (Integer) packedFunc.remove(0).getData(); //buffers.get(buffer).setRead(); } else if (className.equals("BufferSyncer") && function.equals("removeBuffer")) { Log.d(TAG, "Sync: BufferSyncer -> removeBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if(buffers.containsKey(bufferId)) { int networkId = buffers.get(bufferId).getInfo().networkId; buffers.remove(bufferId); service.getHandler().obtainMessage(R.id.REMOVE_BUFFER, networkId, bufferId).sendToTarget(); } } else if (className.equals("BufferSyncer") && function.equals("renameBuffer")) { Log.d(TAG, "Sync: BufferSyncer -> renameBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); String newName = (String) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.RENAME_BUFFER); msg.arg1 = bufferId; msg.arg2 = 0; msg.obj = newName; msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("addBuffer")) { Log.d(TAG, "Sync: BufferViewConfig -> addBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { // System.err.println("got buffer info for non-existant buffer id: " + bufferId); continue; } if(bufferId > maxBufferId) { maxBufferId = bufferId; } if (buffers.get(bufferId).isTemporarilyHidden()) { Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = false; msg.sendToTarget(); } if (buffers.get(bufferId).isPermanentlyHidden()) { Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = false; msg.sendToTarget(); } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ORDER); msg.arg1 = bufferId; msg.arg2 = networks.get(buffers.get(bufferId).getInfo().networkId).getBufferCount(); msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("removeBuffer")) { Log.d(TAG, "Sync: BufferViewConfig -> removeBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { Log.e(TAG, "Dont't have buffer: " + bufferId); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = true; msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("removeBufferPermanently")) { Log.d(TAG, "Sync: BufferViewConfig -> removeBufferPermanently"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { Log.e(TAG, "Dont't have buffer: " + bufferId); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = true; msg.sendToTarget(); } else { Log.i(TAG, "Unparsed Sync request: " + className + "::" + function); } break; /* * Remote procedure calls are direct calls that are not associated with any objects. */ case RpcCall: // Contains a normalized function signature; see QMetaObject::normalizedSignature, I guess. String functionName = packedFunc.remove(0).toString(); /* * This is called by the core when a new message should be displayed. */ if (functionName.equals("2displayMsg(Message)")) { //Log.d(TAG, "RpcCall: " + "2displayMsg(Message)"); IrcMessage message = (IrcMessage) packedFunc.remove(0).getData(); if (!networks.get(message.bufferInfo.networkId).containsBuffer(message.bufferInfo.id) && message.bufferInfo.type == BufferInfo.Type.QueryBuffer) { // TODO: persist the db connections Buffer buffer = new Buffer(message.bufferInfo, new QuasselDbHelper(service.getApplicationContext())); buffers.put(message.bufferInfo.id, buffer); Message msg = service.getHandler().obtainMessage(R.id.NEW_BUFFER_TO_SERVICE); msg.obj = buffer; msg.sendToTarget(); } Message msg = service.getHandler().obtainMessage(R.id.NEW_MESSAGE_TO_SERVICE); msg.obj = message; msg.sendToTarget(); //11-12 21:48:02.514: I/CoreConnection(277): Unhandled RpcCall: __objectRenamed__ ([IrcUser, 1/Kenji, 1/Kenj1]). } else if(functionName.equals("__objectRenamed__") && ((String)packedFunc.get(0).getData()).equals("IrcUser")) { packedFunc.remove(0); //Drop the "ircUser" String[] tmp = ((String)packedFunc.remove(0).getData()).split("/", 2); int networkId = Integer.parseInt(tmp[0]); String newNick = tmp[1]; tmp = ((String)packedFunc.remove(0).getData()).split("/", 2); String oldNick = tmp[1]; Bundle bundle = new Bundle(); bundle.putString("oldNick", oldNick); bundle.putString("newNick", newNick); service.getHandler().obtainMessage(R.id.USER_CHANGEDNICK, networkId, -1, bundle).sendToTarget(); } else if(functionName.equals("2networkCreated(NetworkId)")) { Log.d(TAG, "RpcCall: " + "2networkCreated(NetworkId)"); int networkId = ((Integer)packedFunc.remove(0).getData()); Network network = new Network(networkId); networks.put(networkId, network); sendInitRequest("Network", Integer.toString(networkId)); } else if(functionName.equals("2networkRemoved(NetworkId)")) { Log.d(TAG, "RpcCall: " + "2networkRemoved(NetworkId)"); int networkId = ((Integer)packedFunc.remove(0).getData()); networks.remove(networkId); service.getHandler().obtainMessage(R.id.NETWORK_REMOVED, networkId, 0).sendToTarget(); } else { Log.i(TAG, "Unhandled RpcCall: " + functionName + " (" + packedFunc + ")."); } break; default: Log.i(TAG, "Unhandled request type: " + type.name()); } long end = System.currentTimeMillis(); if (end-start > 500) { System.err.println("Slow parsing (" + (end-start) + "ms)!: Request type: " + type.name() + " Class name:" + className); } } catch (IOException e) { CoreConnection.this.onDisconnected("Lost connection"); Log.w(TAG, "IO error, lost connection?", e); } } if (heartbeatTimer!=null) { heartbeatTimer.cancel(); // Has this stopped executing now? Nobody knows. } //Close streams and socket try { if (outStream != null) { outStream.flush(); outStream.close(); } } catch (IOException e) { Log.w(TAG, "IOException while closing outStream", e); } try { if(inStream != null) inStream.close(); } catch (IOException e) { Log.w(TAG, "IOException while closing inStream", e); } try { if (socket != null) socket.close(); } catch (IOException e) { Log.w(TAG, "IOException while closing socket", e); } return null; } } public boolean isInitComplete() { return initComplete; } }
package com.jayantkrish.jklol.cvsm; import java.util.Arrays; import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.jayantkrish.jklol.tensor.SparseTensor; import com.jayantkrish.jklol.tensor.Tensor; public class TensorLowRankTensor extends AbstractLowRankTensor { private static final long serialVersionUID = 1L; private final Tensor tensor; public TensorLowRankTensor(Tensor tensor) { super(tensor.getDimensionNumbers(), tensor.getDimensionSizes()); this.tensor = tensor; } public static TensorLowRankTensor zero(int[] dimensionNumbers, int[] dimensionSizes) { return new TensorLowRankTensor(SparseTensor.empty(dimensionNumbers, dimensionSizes)); } @Override public Tensor getTensor() { return tensor; } @Override public LowRankTensor relabelDimensions(BiMap<Integer, Integer> relabeling) { return new TensorLowRankTensor(tensor.relabelDimensions(relabeling)); } @Override public LowRankTensor innerProduct(LowRankTensor other) { Preconditions.checkArgument(other.getDimensionNumbers().length < this.getDimensionNumbers().length, "Cannot inner product %s and %s", Arrays.toString(this.getDimensionNumbers()), Arrays.toString(other.getDimensionNumbers())); return new TensorLowRankTensor(tensor.innerProduct(other.getTensor())); } @Override public LowRankTensor elementwiseProduct(double value) { return new TensorLowRankTensor(tensor.elementwiseProduct(value)); } }
package com.jme.input.thirdperson; import java.util.HashMap; import com.jme.input.ChaseCamera; import com.jme.input.InputHandler; import com.jme.input.MouseInput; import com.jme.input.RelativeMouse; import com.jme.input.action.InputActionEvent; import com.jme.input.action.MouseInputAction; import com.jme.math.FastMath; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.scene.Spatial; public class ThirdPersonMouseLook extends MouseInputAction { public static final String PROP_MAXASCENT = "maxAscent"; public static final String PROP_MINASCENT = "minAscent"; public static final String PROP_MAXROLLOUT = "maxRollOut"; public static final String PROP_MINROLLOUT = "minRollOut"; public static final String PROP_MOUSEXMULT = "mouseXMult"; public static final String PROP_MOUSEYMULT = "mouseYMult"; public static final String PROP_MOUSEROLLMULT = "mouseRollMult"; public static final String PROP_INVERTEDY = "invertedY"; public static final String PROP_LOCKASCENT = "lockAscent"; public static final String PROP_ROTATETARGET = "rotateTarget"; public static final String PROP_ENABLED = "lookEnabled"; public static final String PROP_TARGETTURNSPEED = "targetTurnSpeed"; public static final String PROP_MOUSEBUTTON_FOR_LOOKING = "lookButton"; public static final float DEFAULT_MOUSEXMULT = 2; public static final float DEFAULT_MOUSEYMULT = 30; public static final float DEFAULT_MOUSEROLLMULT = 50; public static final float DEFAULT_MAXASCENT = 45 * FastMath.DEG_TO_RAD; public static final float DEFAULT_MINASCENT = -15 * FastMath.DEG_TO_RAD; public static final float DEFAULT_MAXROLLOUT = 240; public static final float DEFAULT_MINROLLOUT = 20; public static final float DEFAULT_TARGETTURNSPEED = FastMath.TWO_PI; public static final boolean DEFAULT_INVERTEDY = false; public static final boolean DEFAULT_LOCKASCENT = false; public static final boolean DEFAULT_ENABLED = true; public static final boolean DEFAULT_ROTATETARGET = false; public static final int DEFAULT_MOUSEBUTTON_FOR_LOOKING = -1; protected float maxAscent = DEFAULT_MAXASCENT; protected float minAscent = DEFAULT_MINASCENT; protected float maxRollOut = DEFAULT_MAXROLLOUT; protected float minRollOut = DEFAULT_MINROLLOUT; protected float mouseXMultiplier = DEFAULT_MOUSEXMULT; protected float mouseYMultiplier = DEFAULT_MOUSEYMULT; protected float mouseRollMultiplier = DEFAULT_MOUSEROLLMULT; protected float mouseXSpeed = DEFAULT_MOUSEXMULT; protected float mouseYSpeed = DEFAULT_MOUSEYMULT; protected float rollInSpeed = DEFAULT_MOUSEROLLMULT; protected float targetTurnSpeed = DEFAULT_TARGETTURNSPEED; protected ChaseCamera camera; protected Spatial target; protected boolean updated = false; protected boolean invertedY = DEFAULT_INVERTEDY; protected boolean lockAscent = DEFAULT_LOCKASCENT; protected boolean enabled = DEFAULT_ENABLED; protected boolean rotateTarget = DEFAULT_ROTATETARGET; protected int lookMouse = DEFAULT_MOUSEBUTTON_FOR_LOOKING; protected Vector3f difTemp = new Vector3f(); protected Vector3f sphereTemp = new Vector3f(); protected Vector3f rightTemp = new Vector3f(); protected Quaternion rotTemp = new Quaternion(); /** * Constructor creates a new <code>MouseLook</code> object. It takes the * mouse, camera and speed of the looking. * * @param mouse * the mouse to calculate view changes. * @param camera * the camera to move. */ public ThirdPersonMouseLook(RelativeMouse mouse, ChaseCamera camera, Spatial target) { this.mouse = mouse; this.camera = camera; this.target = target; // force update of the 3 speeds. setSpeed(1); } /** * * <code>updateProperties</code> * @param props */ public void updateProperties(HashMap props) { maxAscent = InputHandler.getFloatProp(props, PROP_MAXASCENT, DEFAULT_MAXASCENT); minAscent = InputHandler.getFloatProp(props, PROP_MINASCENT, DEFAULT_MINASCENT); maxRollOut = InputHandler.getFloatProp(props, PROP_MAXROLLOUT, DEFAULT_MAXROLLOUT); minRollOut = InputHandler.getFloatProp(props, PROP_MINROLLOUT, DEFAULT_MINROLLOUT); targetTurnSpeed = InputHandler.getFloatProp(props, PROP_TARGETTURNSPEED, DEFAULT_TARGETTURNSPEED); setMouseXMultiplier(InputHandler.getFloatProp(props, PROP_MOUSEXMULT, DEFAULT_MOUSEXMULT)); setMouseYMultiplier(InputHandler.getFloatProp(props, PROP_MOUSEYMULT, DEFAULT_MOUSEYMULT)); setMouseRollMultiplier(InputHandler.getFloatProp(props, PROP_MOUSEROLLMULT, DEFAULT_MOUSEROLLMULT)); invertedY = InputHandler.getBooleanProp(props, PROP_INVERTEDY, DEFAULT_INVERTEDY); lockAscent = InputHandler.getBooleanProp(props, PROP_LOCKASCENT, DEFAULT_LOCKASCENT); rotateTarget = InputHandler.getBooleanProp(props, PROP_ROTATETARGET, DEFAULT_ROTATETARGET); enabled = InputHandler.getBooleanProp(props, PROP_ENABLED, DEFAULT_ENABLED); lookMouse = InputHandler.getIntProp(props, PROP_MOUSEBUTTON_FOR_LOOKING, DEFAULT_MOUSEBUTTON_FOR_LOOKING); } /** * * <code>setSpeed</code> sets the speed of the mouse look. * * @param speed * the speed of the mouse look. */ public void setSpeed(float speed) { super.setSpeed( speed ); mouseXSpeed = mouseXMultiplier * speed; mouseYSpeed = mouseYMultiplier * speed; rollInSpeed = mouseRollMultiplier * speed; } /** * <code>performAction</code> checks for any movement of the mouse, and * calls the appropriate method to alter the camera's orientation when * applicable. * * @see com.jme.input.action.MouseInputAction#performAction */ public void performAction(InputActionEvent event) { if (!enabled) return; float time = event.getTime(); if (lookMouse == -1 || MouseInput.get().isButtonDown(lookMouse)) { if (mouse.getLocalTranslation().x != 0) { float amount = time * mouse.getLocalTranslation().x; rotateRight(amount, time); updated = true; } else if (rotateTarget) rotateRight(0, time); if (!lockAscent && mouse.getLocalTranslation().y != 0) { float amount = time * mouse.getLocalTranslation().y; rotateUp(amount); updated = true; } } int wdelta = MouseInput.get().getWheelDelta(); if (wdelta != 0) { float amount = time * -wdelta; rollIn(amount); updated = true; } if (updated) camera.getCamera().onFrameChange(); } /** * <code>rotateRight</code> updates the azimuth value of the camera's * spherical coordinates. * * @param amount */ private void rotateRight(float amount, float time) { Vector3f camPos = camera.getCamera().getLocation(); Vector3f targetPos = target.getWorldTranslation(); float azimuthAccel = (amount * mouseXSpeed); difTemp.set(camPos).subtractLocal(targetPos); FastMath.cartesianToSpherical(difTemp, sphereTemp); sphereTemp.y = FastMath.normalize(sphereTemp.y + (azimuthAccel), -FastMath.TWO_PI, FastMath.TWO_PI); FastMath.sphericalToCartesian(sphereTemp, rightTemp); rightTemp.addLocal(targetPos); camPos.set(rightTemp); if (rotateTarget) { //First figure out the current facing vector. target.getLocalRotation().getRotationColumn(0, rightTemp); // get angle between vectors rightTemp.normalizeLocal(); difTemp.y = 0; difTemp.negateLocal().normalizeLocal(); float angle = rightTemp.angleBetween(difTemp); // calc how much angle we'll do float maxAngle = targetTurnSpeed * time; if (angle < 0 && -maxAngle > angle) { angle = -maxAngle; } else if (angle > 0 && maxAngle < angle) { angle = maxAngle; } //figure out rotation axis by taking cross product Vector3f rotAxis = rightTemp.crossLocal(difTemp); // Build a rotation quat and apply current local rotation. Quaternion q = rotTemp; q.fromAngleAxis(angle, rotAxis); q.mult(target.getLocalRotation(), target.getLocalRotation()); } } /** * <code>rotateRight</code> updates the altitude/polar value of the * camera's spherical coordinates. * * @param amount */ private void rotateUp(float amount) { if (invertedY) amount *= -1; Vector3f camPos = camera.getCamera().getLocation(); Vector3f targetPos = target.getWorldTranslation(); float thetaAccel = (amount * mouseYSpeed); difTemp.set(camPos).subtractLocal(targetPos).subtractLocal( camera.getTargetOffset()); FastMath.cartesianToSpherical(difTemp, sphereTemp); camera.getIdealSphereCoords().z = clampUpAngle(sphereTemp.z + (thetaAccel)); } /** * <code>rollIn</code> updates the radius value of the camera's spherical * coordinates. * * @param amount */ private void rollIn(float amount) { camera.getIdealSphereCoords().x = clampRollIn(camera .getIdealSphereCoords().x + (amount * rollInSpeed)); } /** * clampUpAngle * * @param r * float * @return float */ private float clampUpAngle(float r) { if (Float.isInfinite(r) || Float.isNaN(r)) return r; if (r > maxAscent) r = maxAscent; else if (r < minAscent) r = minAscent; return r; } /** * clampRollIn * * @param r * float * @return float */ private float clampRollIn(float r) { if (Float.isInfinite(r) || Float.isNaN(r)) return 100f; if (r > maxRollOut) r = maxRollOut; else if (r < minRollOut) r = minRollOut; return r; } /** * * @param invertY * true if mouse control should be inverted vertically */ public void setInvertedY(boolean invertY) { this.invertedY = invertY; } /** * Returns whether vertical control is inverted (ie pulling down on the * mouse causes the camera to look up) * * @return true if vertical control is inverted (aircraft style) */ public boolean isInvertedY() { return invertedY; } /** * @return Returns the maxAscent. */ public float getMaxAscent() { return maxAscent; } /** * @param maxAscent * The maxAscent to set. */ public void setMaxAscent(float maxAscent) { this.maxAscent = maxAscent; rotateUp(0); } /** * @return Returns the minAscent. */ public float getMinAscent() { return minAscent; } /** * @param minAscent * The minAscent to set. */ public void setMinAscent(float minAscent) { this.minAscent = minAscent; rotateUp(0); } /** * @return Returns the maxRollOut. */ public float getMaxRollOut() { return maxRollOut; } /** * @param maxRollOut * The maxRollOut to set. */ public void setMaxRollOut(float maxRollOut) { this.maxRollOut = maxRollOut; rollIn(0); } /** * @return Returns the minRollOut. */ public float getMinRollOut() { return minRollOut; } /** * @param minRollOut * The minRollOut to set. */ public void setMinRollOut(float minRollOut) { this.minRollOut = minRollOut; rollIn(0); } /** * @return how quickly to turn the target in radians per second - only * applicable if rotateTarget is true. */ public float getTargetTurnSpeed() { return targetTurnSpeed; } /** * @param speed * how quickly to turn the target in radians per second - only * applicable if rotateTarget is true. */ public void setTargetTurnSpeed(float speed) { this.targetTurnSpeed = speed; } /** * @return Returns the mouseXMultiplier. */ public float getMouseXMultiplier() { return mouseXMultiplier; } /** * @param mouseXMultiplier * The mouseXMultiplier to set. Updates mouseXSpeed as well. */ public void setMouseXMultiplier(float mouseXMultiplier) { this.mouseXMultiplier = mouseXMultiplier; mouseXSpeed = speed * mouseXMultiplier; } /** * @return Returns the mouseYMultiplier. */ public float getMouseYMultiplier() { return mouseYMultiplier; } /** * @param mouseYMultiplier * The mouseYMultiplier to set. Updates mouseYSpeed as well. */ public void setMouseYMultiplier(float mouseYMultiplier) { this.mouseYMultiplier = mouseYMultiplier; mouseYSpeed = speed * mouseYMultiplier; } /** * @return Returns the mouseRollMultiplier. */ public float getMouseRollMultiplier() { return mouseRollMultiplier; } /** * @param mouseRollMultiplier * The mouseRollMultiplier to set. Updates rollInSpeed as well. */ public void setMouseRollMultiplier(float mouseRollMultiplier) { this.mouseRollMultiplier = mouseRollMultiplier; rollInSpeed = speed * mouseRollMultiplier; } /** * @param lock * true if camera's polar angle / ascent value should never * change. */ public void setLockAscent(boolean lock) { lockAscent = lock; } /** * @return true if camera's polar angle / ascent value should never change. */ public boolean isLockAscent() { return lockAscent; } /** * @return true if mouselook is enabled. */ public boolean isEnabled() { return enabled; } /** * @param enabled * true to allow mouselook to affect camera. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * @return true if turning mouse should cause the target to turn as well. */ public boolean isRotateTarget() { return rotateTarget; } /** * @param rotateTarget * true if turning mouse should cause the target to turn as well. */ public void setRotateTarget(boolean rotateTarget) { this.rotateTarget = rotateTarget; } /** * @return the index of the button that must be pressed to activate looking * or -1 if no button is needed */ public int getLookMouseButton() { return lookMouse; } /** * Sets the button to use for look actions. For example, if set to 0, the * left button must be held down to move the camera around. * * @param button * index of required button or -1 (default) if none */ public void setLookMouseButton(int button) { this.lookMouse = button; } }
package com.markupartist.sthlmtraveling; import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.text.format.Time; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; public class SearchActivity extends Activity { private static final String TAG = "Search"; private static final int DIALOG_START_POINT = 0; private static final int DIALOG_END_POINT = 1; private static final int DIALOG_NO_ROUTES_FOUND = 2; private static final int DIALOG_ABOUT = 3; private static final int DIALOG_PROGRESS = 4; private AutoCompleteTextView mFromAutoComplete; private AutoCompleteTextView mToAutoComplete; private final Handler mHandler = new Handler(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); Planner planner = Planner.getInstance(); mFromAutoComplete = (AutoCompleteTextView) findViewById(R.id.from); AutoCompleteStopAdapter stopAdapter = new AutoCompleteStopAdapter(this, android.R.layout.simple_dropdown_item_1line, planner); mFromAutoComplete.setAdapter(stopAdapter); mToAutoComplete = (AutoCompleteTextView) findViewById(R.id.to); AutoCompleteStopAdapter toAdapter = new AutoCompleteStopAdapter(this, android.R.layout.simple_dropdown_item_1line, planner); mToAutoComplete.setAdapter(toAdapter); final Button search = (Button) findViewById(R.id.search_route); search.setOnClickListener(mGetSearchListener); final ImageButton fromDialog = (ImageButton) findViewById(R.id.from_menu); fromDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_START_POINT); } }); final ImageButton toDialog = (ImageButton) findViewById(R.id.to_menu); toDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_END_POINT); } }); } View.OnClickListener mGetSearchListener = new View.OnClickListener() { @Override public void onClick(View v) { if (mFromAutoComplete.getText().length() <= 0) { mFromAutoComplete.setError(getText(R.string.empty_value)); } else if (mToAutoComplete.getText().length() <= 0) { mToAutoComplete.setError(getText(R.string.empty_value)); } else { Time time = new Time(); time.setToNow(); searchRoutes(mFromAutoComplete.getText().toString(), mToAutoComplete.getText().toString(), time); } } }; /** * Fires off a thread to do the query. Will call onSearchResult when done. * @param startPoint the start point * @param endPoint the end point */ private void searchRoutes(final String startPoint, final String endPoint, final Time time) { showDialog(DIALOG_PROGRESS); new Thread() { public void run() { try { Planner.getInstance().findRoutes(startPoint, endPoint, time); mHandler.post(new Runnable() { @Override public void run() { onSearchRoutesResult(); } }); dismissDialog(DIALOG_PROGRESS); } catch (Exception e) { dismissDialog(DIALOG_PROGRESS); } } }.start(); } /** * Called when we have a search result for routes. */ private void onSearchRoutesResult() { if (Planner.getInstance().lastFoundRoutes() != null && !Planner.getInstance().lastFoundRoutes().isEmpty()) { Intent i = new Intent(SearchActivity.this, RoutesActivity.class); i.putExtra("com.markupartist.sthlmtraveling.startPoint", mFromAutoComplete.getText().toString()); i.putExtra("com.markupartist.sthlmtraveling.endPoint", mToAutoComplete.getText().toString()); startActivity(i); } else { // TODO: This works for now, but we need to see if there are any // alternative stops available in later on. showDialog(DIALOG_NO_ROUTES_FOUND); } } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_START_POINT: AlertDialog.Builder startPointDialogBuilder = new AlertDialog.Builder(this); startPointDialogBuilder.setTitle("Choose start point"); startPointDialogBuilder.setItems(getMyLocationItems(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { mFromAutoComplete.setText(getAddressFromCurrentPosition()); } }); dialog = startPointDialogBuilder.create(); break; case DIALOG_END_POINT: AlertDialog.Builder endPointDialogBuilder = new AlertDialog.Builder(this); endPointDialogBuilder.setTitle("Choose end point"); endPointDialogBuilder.setItems(getMyLocationItems(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { mToAutoComplete.setText(getAddressFromCurrentPosition()); } }); dialog = endPointDialogBuilder.create(); break; case DIALOG_NO_ROUTES_FOUND: AlertDialog.Builder builder = new AlertDialog.Builder(this); dialog = builder.setTitle("Unfortunately no routes was found") .setMessage("If searhing for an address try adding a house number.") .setCancelable(true) .setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); break; case DIALOG_ABOUT: PackageManager pm = getPackageManager(); String version = ""; try { PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0); version = pi.versionName; } catch (NameNotFoundException e) { Log.e(TAG, "Could not get the package info."); } dialog = new Dialog(this); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(R.layout.about_dialog); dialog.setTitle(getText(R.string.app_name) + " " + version); break; case DIALOG_PROGRESS: ProgressDialog progress = new ProgressDialog(this); progress.setMessage(getText(R.string.loading)); dialog = progress; break; } return dialog; } private CharSequence[] getMyLocationItems() { CharSequence[] items = {"My Location"}; return items; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu_search, menu); return true; } private String getAddressFromCurrentPosition() { final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Location gpsLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc == null && gpsLoc != null) { loc = gpsLoc; } else if (gpsLoc != null && gpsLoc.getTime() > loc.getTime()) { // If we the gps location is more recent than the network // location use it. loc = gpsLoc; } Double lat = loc.getLatitude(); Double lng = loc.getLongitude(); Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); String addressString = null; try { //Log.d(TAG, "Getting address from position " + lat + "," + lng); List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); if (!addresses.isEmpty()) { // Address address = addresses.get(0); for (Address address : addresses) { //Log.d("Search", address.getLocality()); // City //Log.d("Search", address.getAddressLine(0)); // Full Street //Log.d("Search", address.getThoroughfare()); // Street name //Log.d("Search", address.getFeatureName()); // House number or interval*/ //Log.d(TAG, address.toString()); addressString = address.getLocality() + ", " + address.getThoroughfare(); if (address.getFeatureName().contains("-")) { // getFeatureName returns all house numbers on the // position like 14-16 get the first number and append // that to the address. addressString += " " + address.getFeatureName().split("-")[0]; } else if (address.getFeatureName().length() < 4) { // Sometime the feature name also is the same as the // postal code, this is a bit ugly but we just assume that // we do not have any house numbers that is bigger longer // than four, if so append it to the address. addressString += " " + address.getFeatureName(); } } } } catch (IOException e) { // TODO: Change to dialog Toast.makeText(this, "Could not determine your position", 10); Log.e(TAG, e.getMessage()); } return addressString; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: showDialog(DIALOG_ABOUT); return true; } return super.onOptionsItemSelected(item); } }
package com.thaiopensource.validate.picl; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.util.Localizer; import com.thaiopensource.util.PropertyMap; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.ContentHandler; import org.xml.sax.Attributes; import org.xml.sax.DTDHandler; import org.xml.sax.SAXException; import org.xml.sax.Locator; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; import java.util.Stack; class ValidatorImpl extends DefaultHandler implements Validator, Path, PatternManager, ErrorContext { private final Constraint constraint; private final Stack openElements = new Stack(); private final Stack valueHandlers = new Stack(); private final Stack activePatterns = new Stack(); private final AttributePath attributePath = new AttributePath(); private Locator locator; private final ErrorHandler eh; private final Localizer localizer = new Localizer(ValidatorImpl.class); private static class WrappedSAXException extends RuntimeException { final SAXException exception; WrappedSAXException(SAXException exception) { this.exception = exception; } } static class ActivePattern { final int rootDepth; final Pattern pattern; final SelectionHandler handler; ActivePattern(int rootDepth, Pattern pattern, SelectionHandler handler) { this.rootDepth = rootDepth; this.pattern = pattern; this.handler = handler; } } static class OpenElement { final String namespaceUri; final String localName; int nActivePatterns; int nValueHandlers; OpenElement(String namespaceUri, String localName) { this.namespaceUri = namespaceUri; this.localName = localName; } } class AttributePath implements Path { private Attributes atts; private int attIndex; void set(Attributes atts, int attIndex) { this.atts = atts; this.attIndex = attIndex; } public boolean isAttribute() { return true; } public int length() { return ValidatorImpl.this.length() + 1; } public String getLocalName(int i) { if (i == openElements.size()) return atts.getLocalName(attIndex); return ValidatorImpl.this.getLocalName(i); } public String getNamespaceUri(int i) { if (i == openElements.size()) return atts.getURI(attIndex); return ValidatorImpl.this.getNamespaceUri(i); } } ValidatorImpl(Constraint constraint, PropertyMap properties) { this.constraint = constraint; this.eh = ValidateProperty.ERROR_HANDLER.get(properties); } public ContentHandler getContentHandler() { return this; } public DTDHandler getDTDHandler() { return null; } public void reset() { openElements.setSize(0); valueHandlers.setSize(0); activePatterns.setSize(0); locator = null; } public int length() { return openElements.size(); } public String getLocalName(int i) { return ((OpenElement)openElements.elementAt(i)).localName; } public String getNamespaceUri(int i) { return ((OpenElement)openElements.elementAt(i)).namespaceUri; } public boolean isAttribute() { return false; } public void registerPattern(Pattern pattern, SelectionHandler handler) { // XXX what about case where it matches dot? activePatterns.push(new ActivePattern(openElements.size(), pattern, handler)); ((OpenElement)openElements.peek()).nActivePatterns += 1; } public void registerValueHandler(ValueHandler handler) { valueHandlers.push(handler); ((OpenElement)openElements.peek()).nValueHandlers += 1; } public void setDocumentLocator(Locator locator) { this.locator = locator; } public void startDocument() throws SAXException { if (locator == null) { LocatorImpl tem = new LocatorImpl(); tem.setLineNumber(-1); tem.setColumnNumber(-1); locator = tem; } openElements.push(new OpenElement("", "#root")); try { constraint.activate(this); } catch (WrappedSAXException e) { throw e.exception; } } public void endDocument() throws SAXException { try { popOpenElement(); } catch (WrappedSAXException e) { throw e.exception; } } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { openElements.push(new OpenElement(uri, localName)); for (int i = 0, len = valueHandlers.size(); i < len; i++) ((ValueHandler)valueHandlers.elementAt(i)).tag(this); for (int i = 0, len = activePatterns.size(); i < len; i++) { ActivePattern ap = (ActivePattern)activePatterns.elementAt(i); if (ap.pattern.matches(this, ap.rootDepth)) ap.handler.selectElement(this, this, this); } int nActivePatterns = activePatterns.size(); for (int i = 0, len = attributes.getLength(); i < len; i++) { attributePath.set(attributes, i); for (int j = 0; j < nActivePatterns; j++) { ActivePattern ap = (ActivePattern)activePatterns.elementAt(j); if (ap.pattern.matches(attributePath, ap.rootDepth)) ap.handler.selectAttribute(this, attributePath, attributes.getValue(i)); } } } catch (WrappedSAXException e) { throw e.exception; } } public void endElement(String uri, String localName, String qName) throws SAXException { try { popOpenElement(); } catch (WrappedSAXException e) { throw e.exception; } } public void characters(char ch[], int start, int length) throws SAXException { try { for (int i = 0, len = valueHandlers.size(); i < len; i++) ((ValueHandler)valueHandlers.elementAt(i)).characters(this, ch, start, length); } catch (WrappedSAXException e) { throw e.exception; } } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { characters(ch, start, length); } private void popOpenElement() { OpenElement top = (OpenElement)openElements.pop(); for (int i = 0; i < top.nValueHandlers; i++) { ValueHandler h = (ValueHandler)valueHandlers.pop(); h.valueComplete(this); } for (int i = 0; i < top.nActivePatterns; i++) { ActivePattern ap = (ActivePattern)activePatterns.pop(); ap.handler.selectComplete(this); } } public void error(String key) { error(key, locator); } public void error(String key, String arg) { error(key, arg, locator); } public void error(String key, Locator locator) { try { eh.error(new SAXParseException(localizer.message(key), locator)); } catch (SAXException e) { throw new WrappedSAXException(e); } } public void error(String key, String arg, Locator locator) { try { eh.error(new SAXParseException(localizer.message(key, arg), locator)); } catch (SAXException e) { throw new WrappedSAXException(e); } } public Locator saveLocator() { return new LocatorImpl(locator); } }
package com.valkryst.generator; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public final class ConsonantVowelGenerator extends NameGenerator { /** The consonants. */ private final String[] consonants; /** The vowels. */ private final String[] vowels; public ConsonantVowelGenerator(final List<String> consonants, final List<String> vowels) { // Ensure lists aren't empty: if (consonants.size() == 0) { throw new IllegalArgumentException("The list of consonants is empty or null."); } if (vowels.size() == 0) { throw new IllegalArgumentException("The list of vowels is empty or null."); } this.consonants = consonants.toArray(new String[0]); this.vowels = vowels.toArray(new String[0]); } @Override public String generateName(int length) { if (length < 2) { length = 2; } final StringBuilder sb = new StringBuilder(); final ThreadLocalRandom rand = ThreadLocalRandom.current(); while (sb.length() < length) { if (length % 2 == 0) { sb.append(vowels[rand.nextInt(vowels.length)]); } else { sb.append(consonants[rand.nextInt(consonants.length)]); } } if (sb.length() > length) { sb.deleteCharAt(sb.length() - (sb.length() - length)); } return super.capitalizeFirstCharacter(sb.toString()); } }
package me.nallar.tickthreading.patcher; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javassist.CannotCompileException; import javassist.ClassMap; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.BadBytecode; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.mappings.MethodDescription; @SuppressWarnings ("MethodMayBeStatic") public class Patches { private final ClassRegistry classRegistry; public Patches(ClassRegistry classRegistry) { this.classRegistry = classRegistry; } @Patch public void markDirty(CtClass ctClass) { // A NOOP patch to make sure META-INF is removed } @Patch ( name = "volatile" ) public void volatile_(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getType().isPrimitive()) { ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } } else { CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } @Patch ( requiredAttributes = "class" ) public CtClass replace(CtClass clazz, Map<String, String> attributes) throws NotFoundException, CannotCompileException { Log.info("Replacing " + clazz.getName() + " with " + attributes.get("class")); String oldName = clazz.getName(); clazz.setName(oldName + "_old"); CtClass newClass = classRegistry.getClass(attributes.get("class")); newClass.getClassFile2().setSuperclass(null); newClass.setName(oldName); return newClass; } @Patch public void replaceMethod(CtMethod method, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); String code = attributes.get("code"); if (fromClass != null) { String fromMethod = attributes.get("fromMethod"); CtMethod replacingMethod = fromMethod == null ? classRegistry.getClass(fromClass).getDeclaredMethod(method.getName(), method.getParameterTypes()) : MethodDescription.fromString(fromClass, fromMethod).inClass(classRegistry.getClass(fromClass)); replaceMethod(method, replacingMethod); } else if (code != null) { Log.info("Replacing " + new MethodDescription(method).getMCPName() + " with " + code); method.setBody(code); } else { Log.severe("Missing required attributes for replaceMethod"); } } private void replaceMethod(CtMethod oldMethod, CtMethod newMethod) throws CannotCompileException, BadBytecode { Log.info("Replacing " + new MethodDescription(oldMethod).getMCPName() + " with " + new MethodDescription(newMethod).getMCPName()); ClassMap classMap = new ClassMap(); classMap.put(newMethod.getClass().getName(), oldMethod.getDeclaringClass().getName()); oldMethod.setBody(newMethod, classMap); oldMethod.getMethodInfo().rebuildStackMap(classRegistry.classes); oldMethod.getMethodInfo().rebuildStackMapForME(classRegistry.classes); } @Patch ( requiredAttributes = "field" ) public void replaceFieldUsage(CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String readCode = attributes.get("readCode"); final String writeCode = attributes.get("writeCode"); if (readCode == null && writeCode == null) { throw new IllegalArgumentException("readCode or writeCode must be set"); } ctBehavior.instrument(new ExprEditor() { @Override public void edit(FieldAccess fieldAccess) throws CannotCompileException { if (fieldAccess.getFieldName().equals(field)) { if (fieldAccess.isWriter() && writeCode != null) { fieldAccess.replace(writeCode); } else if (fieldAccess.isReader() && readCode != null) { fieldAccess.replace(readCode); } } } }); } @Patch ( requiredAttributes = "fromClass" ) public void addAll(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); CtClass from = classRegistry.getClass(fromClass); ClassMap classMap = new ClassMap(); classMap.put(fromClass, ctClass.getName()); for (CtField ctField : from.getDeclaredFields()) { Log.info("Added " + ctField); ctClass.addField(new CtField(ctField, ctClass)); } for (CtMethod newMethod : from.getDeclaredMethods()) { Log.info("Replaced " + newMethod.getName()); try { CtMethod oldMethod = ctClass.getDeclaredMethod(newMethod.getName(), newMethod.getParameterTypes()); replaceMethod(oldMethod, newMethod); } catch (NotFoundException ignored) { ctClass.addMethod(CtNewMethod.copy(newMethod, ctClass, classMap)); } } } @Patch ( requiredAttributes = "field,threadLocalField,type" ) public void threadLocal(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String threadLocalField = attributes.get("threadLocalField"); final String type = attributes.get("type"); String setExpression_ = attributes.get("setExpression"); final String setExpression = setExpression_ == null ? '(' + type + ") $1" : setExpression_; Log.info(field + " -> " + threadLocalField); ctClass.instrument(new ExprEditor() { @Override public void edit(FieldAccess e) throws CannotCompileException { if (e.getFieldName().equals(field)) { if (e.isReader()) { e.replace("{ $_ = (" + type + ") " + threadLocalField + ".get(); }"); } else if (e.isWriter()) { e.replace("{ " + threadLocalField + ".set(" + setExpression + "); }"); } } } }); } @Patch ( name = "public" ) public void makePublic(CtMethod ctMethod) { ctMethod.setModifiers(Modifier.setPublic(ctMethod.getModifiers())); } @Patch ( requiredAttributes = "field" ) public void newInitializer(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); initialise = "{ " + field + " = " + (initialise == null ? ("new " + clazz + "()") : initialise) + "; }"; // Return value ignored - just used to cause a NotFoundException if the field doesn't exist. ctClass.getDeclaredField(field); for (CtConstructor ctConstructor : ctClass.getConstructors()) { ctConstructor.insertAfter(initialise); } if (clazz != null) { classRegistry.add(ctClass, clazz); } } @Patch ( requiredAttributes = "field,class" ) public void newField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); if (initialise == null) { initialise = "new " + clazz + "();"; } CtClass newType = classRegistry.getClass(clazz); CtField ctField = new CtField(newType, field, ctClass); if (attributes.get("static") != null) { ctField.setModifiers(ctField.getModifiers() | Modifier.STATIC | Modifier.PUBLIC); } CtField.Initializer initializer = CtField.Initializer.byExpr(initialise); ctClass.addField(ctField, initializer); classRegistry.add(ctClass, clazz); } @Patch ( requiredAttributes = "code" ) public void insertBefore(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertBefore(code); } @Patch ( requiredAttributes = "code" ) public void insertAfter(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertAfter(code); } @Patch ( requiredAttributes = "field" ) public void lock(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); ctMethod.setName(ctMethod.getName() + "_nolock"); replacement.setBody("{ this." + field + ".lock(); try { return " + (attributes.get("methodcall") == null ? "$proceed" : ctMethod.getName()) + "($$); } finally { this." + field + ".unlock(); } }", "this", ctMethod.getName()); ctClass.addMethod(replacement); } @Patch ( emptyConstructor = false ) public void synchronize(Object o, Map<String, String> attributes) throws CannotCompileException { if (o instanceof CtMethod) { synchronize((CtMethod) o, attributes.get("field")); } else { for (CtMethod ctMethod : ((CtClass) o).getDeclaredMethods()) { synchronize(ctMethod, attributes.get("field")); } } } private void synchronize(CtMethod ctMethod, String field) throws CannotCompileException { if (field == null) { int currentModifiers = ctMethod.getModifiers(); if (Modifier.isSynchronized(currentModifiers)) { Log.warning("Method: " + ctMethod.getLongName() + " is already synchronized"); } else { ctMethod.setModifiers(currentModifiers | Modifier.SYNCHRONIZED); } } else { CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); ctMethod.setName(ctMethod.getName() + "_nosynchronize"); replacement.setBody("synchronized(this." + field + ") { return $proceed($$); }", "this", ctMethod.getName()); ctClass.addMethod(replacement); } } @Patch public void ignoreExceptions(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException { String returnCode = attributes.get("code"); if (returnCode == null) { returnCode = "return;"; } ctMethod.addCatch("{ " + returnCode + '}', classRegistry.getClass("java.lang.Exception")); } @Patch public void replaceInstantiations(CtBehavior object, Map<String, String> attributes) { // TODO: Implement this, change some newInitializer patches to use this } public void replaceInstantiationsImplementation(CtBehavior ctBehavior, final Map<String, List<String>> replacementClasses) throws CannotCompileException { // TODO: Learn to use ASM, javassist isn't nice for some things. :( final Map<Integer, String> newExprType = new HashMap<Integer, String>(); ctBehavior.instrument(new ExprEditor() { NewExpr lastNewExpr; int newPos = 0; @Override public void edit(NewExpr e) { lastNewExpr = null; newPos++; if (replacementClasses.containsKey(e.getClassName())) { lastNewExpr = e; } } @Override public void edit(FieldAccess e) { NewExpr myLastNewExpr = lastNewExpr; lastNewExpr = null; if (myLastNewExpr != null) { Log.fine('(' + myLastNewExpr.getSignature() + ") " + myLastNewExpr.getClassName() + " at " + myLastNewExpr.getFileName() + ':' + myLastNewExpr.getLineNumber() + ':' + newPos); newExprType.put(newPos, classSignatureToName(e.getSignature())); } } @Override public void edit(MethodCall e) { lastNewExpr = null; } @Override public void edit(NewArray e) { lastNewExpr = null; } @Override public void edit(Cast e) { lastNewExpr = null; } @Override public void edit(Instanceof e) { lastNewExpr = null; } @Override public void edit(Handler e) { lastNewExpr = null; } @Override public void edit(ConstructorCall e) { lastNewExpr = null; } }); ctBehavior.instrument(new ExprEditor() { int newPos = 0; @Override public void edit(NewExpr e) throws CannotCompileException { newPos++; try { Log.fine(e.getFileName() + ':' + e.getLineNumber() + ", pos: " + newPos); if (newExprType.containsKey(newPos)) { String replacementType = null, assignedType = newExprType.get(newPos); Log.fine(assignedType + " at " + e.getFileName() + ':' + e.getLineNumber()); Class<?> assignTo = Class.forName(assignedType); for (String replacementClass : replacementClasses.get(e.getClassName())) { if (assignTo.isAssignableFrom(Class.forName(replacementClass))) { replacementType = replacementClass; break; } } if (replacementType == null) { return; } String block = "{$_=new " + replacementType + "($$);}"; Log.fine("Replaced with " + block + ", " + replacementType.length() + ':' + assignedType.length()); e.replace(block); } } catch (ClassNotFoundException el) { Log.severe("Could not replace instantiation, class not found.", el); } } }); } private static String classSignatureToName(String signature) { //noinspection HardcodedFileSeparator return signature.substring(1, signature.length() - 1).replace("/", "."); } }
package org.wyona.yanel.servlet; import java.io.File; import java.io.BufferedReader; import java.io.InputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeIdentifier; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.servlet.CreateUsecaseHelper; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yanel.servlet.communication.HttpResponse; import org.wyona.yanel.util.ResourceAttributeHelper; import org.wyona.security.core.AuthenticationException; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import org.apache.log4j.Category; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; //PolicyManager pm; //IdentityManager im; Map map; Yanel yanel; Sitetree sitetree; File xsltInfoAndException; File xsltLoginScreen; private static String IDENTITY_KEY = "identity"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_OPTIONS = "OPTIONS"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; private String sslPort = null; public void init(ServletConfig config) throws ServletException { this.config = config; xsltInfoAndException = org.wyona.commons.io.FileUtil.file(config.getServletContext().getRealPath("/"), config.getInitParameter("exception-and-info-screen-xslt")); xsltLoginScreen = org.wyona.commons.io.FileUtil.file(config.getServletContext().getRealPath("/"), config.getInitParameter("login-screen-xslt")); try { yanel = Yanel.getInstance(); yanel.init(); rtr = yanel.getResourceTypeRegistry(); map = (Map) yanel.getBeanFactory().getBean("map"); sitetree = (Sitetree) yanel.getBeanFactory().getBean("nav-sitetree"); sslPort = config.getInitParameter("ssl-port"); } catch (Exception e) { log.error(e); throw new ServletException(e.getMessage(), e); } } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); String httpUserAgent = request.getHeader("User-Agent"); log.debug("HTTP User Agent: " + httpUserAgent); String httpAcceptLanguage = request.getHeader("Accept-Language"); log.debug("HTTP Accept Language: " + httpAcceptLanguage); // Logout from Yanel String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("logout")) { if(doLogout(request, response) != null) return; } // Authentication if(doAuthenticate(request, response) != null) return; // Check authorization if(doAuthorize(request, response) != null) return; // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else if (method.equals(METHOD_OPTIONS)) { doOptions(request, response); } else { log.error("No such method implemented: " + method); response.sendError(response.SC_NOT_IMPLEMENTED); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if a new resource shall be created ... String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("create")) { CreateUsecaseHelper creator = new CreateUsecaseHelper(); creator.create(request, response, yanel); return; } getContent(request, response); } private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; doc = impl.createDocument("http: } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); String servletContextRealPath = config.getServletContext().getRealPath("/"); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); //log.deubg("servletContextRealPath: " + servletContextRealPath); //log.debug("contextPath: " + request.getContextPath()); //log.debug("servletPath: " + request.getServletPath()); Element requestElement = (Element) rootElement.appendChild(doc.createElement("request")); requestElement.setAttribute("uri", request.getRequestURI()); requestElement.setAttribute("servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } Realm realm; Path path; ResourceTypeIdentifier rti; try { realm = map.getRealm(request.getServletPath()); path = map.getPath(realm, request.getServletPath()); rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path); } catch (Exception e) { String message = "URL could not be mapped to realm/path " + e.getMessage(); log.error(message, e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } //String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); Resource res = null; long lastModified = -1; long size = -1; if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti.getUniversalName()); if (rtd == null) { String message = "No such resource type registered: " + rti.getUniversalName() + ", check " + rtr.getConfigurationFile(); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier")); rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace()); rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName()); try { HttpRequest httpRequest = new HttpRequest(request); HttpResponse httpResponse = new HttpResponse(response); res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path, rtd, rti); if (res != null) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { log.info("Resource is viewable V1"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors())); String viewId = request.getParameter("yanel.resource.viewid"); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node exception: " + e; log.warn(e); //log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(request, response, doc); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { log.info("Resource is viewable V2"); String viewId = request.getParameter("yanel.resource.viewid"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV2) res).getViewDescriptors())); size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); try { view = ((ViewableV2) res).getView(viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node exception: " + e; log.warn(e); //log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(request, response, doc); return; } } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // retrieve the revisions, but only in the meta usecase (for performance reasons): if (request.getParameter("yanel.resource.meta") != null) { String[] revisions = ((VersionableV2)res).getRevisions(); Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions")); if (revisions != null) { for (int i=0; i<revisions.length; i++) { Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision")); revisionElement.appendChild(doc.createTextNode(revisions[i])); } } else { Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet")); } } } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found")); noRTIFoundElement.setAttribute("servlet-path", request.getServletPath()); } String usecase = request.getParameter("yanel.resource.usecase"); if (usecase != null && usecase.equals("checkout")) { log.debug("Checkout data ..."); // TODO: Implement checkout ... log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.error("DEBUG: meta length: " + meta.length()); } else { log.error("DEBUG: Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { // check if the view contatins the response (otherwise assume that the resource // wrote the response, and just return). if (!view.isResponse()) return; response.setContentType(patchContentType(view.getMimeType(), request)); InputStream is = view.getInputStream(); //BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //String line; //System.out.println("getContentXML: "+path); //while ((line = reader.readLine()) != null) System.out.println(line); byte buffer[] = new byte[8192]; int bytesRead; if (is != null) { // TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ... bytesRead = is.read(buffer); if (bytesRead == -1) { String message = "InputStream of view does not seem to contain any data!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag String ifModifiedSince = request.getHeader("If-Modified-Since"); if (ifModifiedSince != null) { log.warn("TODO: Implement 304 ..."); } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); return; } else { String message = "InputStream of view is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } setYanelOutput(request, response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Create new Atom entry try { String atomEntryUniversalName = "<{http: org.wyona.yanel.core.map.Realm realm = yanel.getMap().getRealm(request.getServletPath()); Path newEntryPath = yanel.getMap().getPath(realm, request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml"); log.error("DEBUG: Realm and Path of new Atom entry: " + realm + " " + newEntryPath); Resource atomEntryResource = yanel.getResourceManager().getResource(request, response, realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new org.wyona.yanel.core.ResourceTypeIdentifier(atomEntryUniversalName, null)); ((ModifiableV2)atomEntryResource).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntryResource).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } getContent(request, response); } } /** * HTTP PUT implementation */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Overwrite existing atom entry try { String atomEntryUniversalName = "<{http: org.wyona.yanel.core.map.Realm realm = yanel.getMap().getRealm(request.getServletPath()); Path entryPath = yanel.getMap().getPath(realm, request.getServletPath()); log.error("DEBUG: Realm and Path of new Atom entry: " + realm + " " + entryPath); Resource atomEntryResource = yanel.getResourceManager().getResource(request, response, realm, entryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new org.wyona.yanel.core.ResourceTypeIdentifier(atomEntryUniversalName, null)); // TODO: There seems to be a problem ... ((ModifiableV2)atomEntryResource).write(in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.info("Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } else { save(request, response); /* log.warn("TODO: WebDAV PUT ..."); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); return; */ } } } /** * HTTP DELETE implementation */ public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete()) { log.debug("Resource has been deleted: " + res); response.setStatus(response.SC_OK); return; } else { log.warn("Resource could not be deleted: " + res); response.setStatus(response.SC_FORBIDDEN); return; } } else { log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." ); response.sendError(response.SC_NOT_IMPLEMENTED); return; } } catch (Exception e) { log.error("Could not delete resource with URL " + request.getRequestURL() + " " + e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } private Resource getResource(HttpServletRequest request, HttpServletResponse response) { try { Realm realm = map.getRealm(request.getServletPath()); Path path = map.getPath(realm, request.getServletPath()); HttpRequest httpRequest = new HttpRequest(request); HttpResponse httpResponse = new HttpResponse(response); Resource res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path); return res; } catch(Exception e) { log.error(e.getMessage(), e); return null; } } /** * Save data */ private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Save data ..."); InputStream in = request.getInputStream(); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0) { log.info("Check well-formedness ..."); javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); // TODO: Get log messages into log4j ... //parser.setErrorHandler(...); // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also // if isValidating is set to false. // Hence, for performance and network reasons we use a local catalog ... // TODO: What about a resolver factory? parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); parser.parse(new java.io.ByteArrayInputStream(memBuffer)); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage(), e); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: //sb.append("<message>" + e.getStackTrace() + "</message>"); //sb.append("<message>" + e.getMessage() + "</message>"); sb.append("<message>" + e + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.info("Data seems to be well-formed :-)"); } else { log.info("No well-formedness check required for content type: " + contentType); } java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer); // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write .... OutputStream out = null; Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); write(memIn, out, request, response); return; } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { try { out = ((ModifiableV2) res).getOutputStream(); if (out != null) { write(memIn, out, request, response); } else { ((ModifiableV2) res).write(memIn); } return; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); StringBuffer sb = new StringBuffer(); // TODO: Differentiate between Neutron based and other clients ... sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>" + message + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } } /** * Authorize request (and also authenticate for HTTP BASIC) */ private HttpServletResponse doAuthorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Role role = null; // TODO: Replace hardcoded roles by mapping between roles amd query strings ... String value = request.getParameter("yanel.resource.usecase"); String contentType = request.getContentType(); String method = request.getMethod(); if (value != null && value.equals("save")) { log.debug("Save data ..."); role = new Role("write"); } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); role = new Role("write"); } else if (value != null && value.equals("checkout")) { log.debug("Checkout data ..."); role = new Role("open"); } else if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { // TODO: Is posting atom entries different from a general post (see below)?! log.error("DEBUG: Write/Checkin Atom entry ..."); role = new Role("write"); } else if (method.equals(METHOD_PUT) || method.equals(METHOD_POST)) { log.error("DEBUG: Upload data ..."); role = new Role("write"); } else if (method.equals(METHOD_DELETE)) { log.error("DEBUG: Delete resource ..."); role = new Role("delete"); } else { log.debug("Role will be 'view'!"); role = new Role("view"); } value = request.getParameter("yanel.usecase"); if (value != null && value.equals("create")) { log.debug("Create new resource ..."); role = new Role("create"); } boolean authorized = false; Realm realm; Path path; try { realm = map.getRealm(request.getServletPath()); path = map.getPath(realm, request.getServletPath()); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } // HTTP BASIC Authorization (For clients such as for instance Sunbird, OpenOffice or cadaver) // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling String authorization = request.getHeader("Authorization"); log.debug("Checking for Authorization Header: " + authorization); if (authorization != null) { if (authorization.toUpperCase().startsWith("BASIC")) { log.debug("Using BASIC authorization ..."); // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.debug("Username and Password Decoded: " + userpassDecoded); String[] up = userpassDecoded.split(":"); String username = up[0]; String password = up[1]; log.debug("username: " + username + ", password: " + password); try { if (realm.getIdentityManager().authenticate(username, password)) { authorized = realm.getPolicyManager().authorize(path, new Identity(username, null), new Role("view")); if(authorized) { return null; } else { log.warn("HTTP BASIC Authorization failed for " + username + "!"); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authorization Failed!"); return response; } } else { log.warn("HTTP BASIC Authentication failed for " + username + "!"); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authentication Failed!"); return response; } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } else if (authorization.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented"); authorized = false; response.sendError(response.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); return response; } else { log.warn("No such authorization implemented resp. handled by session based authorization: " + authorization); authorized = false; } } // Custom Authorization log.debug("Do session based custom authorization"); //String[] groupnames = {"null", "null"}; HttpSession session = request.getSession(true); Identity identity = (Identity) session.getAttribute(IDENTITY_KEY); if (identity == null) { log.debug("Identity is WORLD"); identity = new Identity(); } //authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role); try { log.debug("Check authorization: realm: " + realm + ", path: " + path + ", identity: " + identity.getUsername() + ", role: " + role.getName()); authorized = realm.getPolicyManager().authorize(path, identity, role); log.debug("Check authorization result: " + authorized); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } if(!authorized) { log.warn("Access denied: " + getRequestURLQS(request, null, false)); if(!request.isSecure()) { if(sslPort != null) { log.info("Redirect to SSL ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); response.setHeader("Location", url.toString()); // TODO: Yulup has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e); } } else { log.warn("SSL does not seem to be configured!"); } } // TODO: Shouldn't this be here instead at the beginning of service() ...? //if(doAuthenticate(request, response) != null) return response; // Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request StringBuffer sb = new StringBuffer(""); String neutronVersions = request.getHeader("Neutron"); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { log.debug("Neutron Versions supported by client: " + neutronVersions); log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true) + "</message>"); sb.append("<authentication>"); sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true) + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); } else if (request.getRequestURI().endsWith(".ics")) { log.warn("Somebody seems to ask for a Calendar (ICS) ..."); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); } else { getXHTMLAuthenticationForm(request, response, realm, null); } return response; } else { log.info("Access granted: " + getRequestURLQS(request, null, false)); return null; } } private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { //Realm realm = map.getRealm(new Path(request.getServletPath())); try { Realm realm = map.getRealm(request.getServletPath()); // TODO: Handle this exception more gracefully! if (realm == null) log.error("No realm found for path " + new Path(request.getServletPath())); String proxyHostName = realm.getProxyHostName(); String proxyPort = realm.getProxyPort(); String proxyPrefix = realm.getProxyPrefix(); URL url = null; url = new URL(request.getRequestURL().toString()); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } if (proxyPort != null) { if (proxyPort.length() > 0) { url = new URL(url.getProtocol(), url.getHost(), new Integer(proxyPort).intValue(), url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } if(proxyHostName != null || proxyPort != null || proxyPrefix != null) { log.debug("Proxy enabled request: " + url); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); log.debug("Request: " + urlQS); return urlQS; } catch (Exception e) { log.error(e); return null; } } public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); //Node node = resource.getRealm().getSitetree().getNode(resource.getPath()); Node node = sitetree.getNode(resource.getRealm(),resource.getPath()); String depth = request.getHeader("Depth"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<multistatus xmlns=\"DAV:\">"); if (depth.equals("0")) { if (node.isCollection()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype><collection/></resourcetype>"); sb.append(" <getcontenttype>http/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else if (node.isResource()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype/>"); // TODO: Does getcontenttype also be set for resources? sb.append(" <getcontenttype>http/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else { log.error("Neither collection nor resource!"); } } else if (depth.equals("1")) { Node[] children = node.getChildren(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + children[i].getPath() + "/</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>A Directory</displayname>\n"); sb.append(" <resourcetype><collection/></resourcetype>\n"); sb.append(" <getcontenttype>http/unix-directory</getcontenttype>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else if(children[i].isResource()) { sb.append(" <response>\n"); sb.append(" <href>"+request.getRequestURI()+children[i].getPath()+"</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>A File</displayname>\n"); sb.append(" <resourcetype/>\n"); sb.append(" <getcontenttype>http/unix-directory</getcontenttype>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else { log.error("Neither collection nor resource: " + children[i].getPath()); } } } else { log.warn("No children!"); } } else if (depth.equals("infinity")) { log.warn("TODO: List children and their children and their children ..."); } else { log.error("No such depth: " + depth); } sb.append("</multistatus>"); //response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS); response.setStatus(207, "Multi-Status"); PrintWriter w = response.getWriter(); w.print(sb); } public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("DAV", "1"); // TODO: Is there anything else to do?! } /** * Authentication * @return null when authentication successful, otherwise return response */ public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Realm realm = map.getRealm(request.getServletPath()); Path path = map.getPath(realm, request.getServletPath()); //Realm realm = map.getRealm(new Path(request.getServletPath())); // HTML Form based authentication String loginUsername = request.getParameter("yanel.login.username"); if(loginUsername != null) { HttpSession session = request.getSession(true); try { if (realm.getIdentityManager().authenticate(loginUsername, request.getParameter("yanel.login.password"))) { log.debug("Realm: " + realm); session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null)); return null; } else { log.warn("Login failed: " + loginUsername); getXHTMLAuthenticationForm(request, response, realm, "Login failed!"); return response; } } catch (Exception e) { log.warn("Login failed: " + loginUsername + " " + e); getXHTMLAuthenticationForm(request, response, realm, "Login failed!"); return response; } } // Neutron-Auth based authentication String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) { log.debug("Neutron Authentication ..."); String username = null; String password = null; String originalRequest = null; DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { Configuration config = builder.build(request.getInputStream()); Configuration originalRequestConfig = config.getChild("original-request"); originalRequest = originalRequestConfig.getAttribute("url", null); Configuration[] paramConfig = config.getChildren("param"); for (int i = 0; i < paramConfig.length; i++) { String paramName = paramConfig[i].getAttribute("name", null); if (paramName != null) { if (paramName.equals("username")) { username = paramConfig[i].getValue(); } else if (paramName.equals("password")) { password = paramConfig[i].getValue(); } } } } catch(Exception e) { log.warn(e); } log.debug("Username: " + username); if (username != null) { HttpSession session = request.getSession(true); log.debug("Realm ID: " + realm.getID()); if (realm.getIdentityManager().authenticate(username, password)) { log.info("Authentication successful: " + username); session.setAttribute(IDENTITY_KEY, new Identity(username, null)); // TODO: send some XML content, e.g. <authentication-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Authentication Successful!"); return response; } else { log.warn("Neutron Authentication failed: " + username); // TODO: Refactor this code with the one from doAuthenticate ... log.debug("Original Request: " + originalRequest); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); return response; } } else { // TODO: Refactor resp. reuse response from above ... log.warn("Neutron Authentication failed because username is NULL!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed because no username was sent!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter writer = response.getWriter(); writer.print(sb); return response; } } else { log.debug("Neutron Authentication successful."); return null; } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Logout from Yanel ..."); HttpSession session = request.getSession(true); session.setAttribute(IDENTITY_KEY, null); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { // TODO: send some XML content, e.g. <logout-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Logout Successful!"); return response; } return null; } public String patchContentType(String contentType, HttpServletRequest request) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); if (contentType != null && contentType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.info("Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } return contentType; } /** * Intercept InputStream and log content ... */ public InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); log.error("DEBUG: InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException { try { String yanelFormat = request.getParameter("yanel.format"); if(yanelFormat != null && yanelFormat.equals("xml")) { response.setContentType("application/xml"); OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); out.close(); } else { response.setContentType("application/xhtml+xml"); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltInfoAndException)); transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter())); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } /** * Custom XHTML Form for authentication */ public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message) throws ServletException, IOException { org.w3c.dom.Document doc = null; javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; doc = impl.createDocument("http: Element rootElement = doc.getDocumentElement(); if (message != null) { Element messageElement = (Element) rootElement.appendChild(doc.createElement("message")); messageElement.appendChild(doc.createTextNode(message)); } Element requestElement = (Element) rootElement.appendChild(doc.createElement("request")); requestElement.setAttribute("urlqs", getRequestURLQS(request, null, true)); Element realmElement = (Element) rootElement.appendChild(doc.createElement("realm")); realmElement.setAttribute("name", realm.getName()); realmElement.setAttribute("mount-point", realm.getMountPoint().toString()); response.setContentType("application/xhtml+xml; charset=UTF-8"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltLoginScreen)); transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter())); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } /** * Write to output stream of modifiable resource */ private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (out != null) { log.debug("Content-Type: " + request.getContentType()); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml"); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } }
package de.danoeh.antennapod.activity; import android.media.AudioManager; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBarActivity; import android.text.format.DateUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.R; import de.danoeh.antennapod.dialog.DownloadRequestErrorDialogCreator; import de.danoeh.antennapod.feed.EventDistributor; import de.danoeh.antennapod.feed.FeedItem; import de.danoeh.antennapod.fragment.ItemDescriptionFragment; import de.danoeh.antennapod.fragment.ItemlistFragment; import de.danoeh.antennapod.preferences.UserPreferences; import de.danoeh.antennapod.storage.DBReader; import de.danoeh.antennapod.storage.DownloadRequestException; import de.danoeh.antennapod.util.QueueAccess; import de.danoeh.antennapod.util.StorageUtils; import de.danoeh.antennapod.util.menuhandler.FeedItemMenuHandler; import java.text.DateFormat; /** * Displays a single FeedItem and provides various actions */ public class ItemviewActivity extends ActionBarActivity { private static final String TAG = "ItemviewActivity"; private static final int EVENTS = EventDistributor.DOWNLOAD_HANDLED | EventDistributor.DOWNLOAD_QUEUED; private FeedItem item; private boolean guiInitialized; private AsyncTask<?, ?, ?> currentLoadTask; @Override public void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); StorageUtils.checkStorageAvailability(this); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); getSupportActionBar().setDisplayShowTitleEnabled(false); EventDistributor.getInstance().register(contentUpdate); setVolumeControlStream(AudioManager.STREAM_MUSIC); guiInitialized = false; long itemId = getIntent().getLongExtra( ItemlistFragment.EXTRA_SELECTED_FEEDITEM, -1); if (itemId == -1) { Log.e(TAG, "Received invalid selection of either feeditem or feed."); } else { loadData(itemId); } } @Override protected void onResume() { super.onResume(); StorageUtils.checkStorageAvailability(this); } @Override public void onStop() { super.onStop(); EventDistributor.getInstance().unregister(contentUpdate); if (currentLoadTask != null) { currentLoadTask.cancel(true); } if (AppConfig.DEBUG) Log.d(TAG, "Stopping Activity"); } private synchronized void loadData(long itemId) { if (currentLoadTask != null) { currentLoadTask.cancel(true); } AsyncTask<Long, Void, FeedItem> loadTask = new AsyncTask<Long, Void, FeedItem>() { @Override protected FeedItem doInBackground(Long... longs) { return DBReader.getFeedItem(ItemviewActivity.this, longs[0]); } @Override protected void onCancelled(FeedItem feedItem) { super.onCancelled(feedItem); if (AppConfig.DEBUG) Log.d(TAG, "loadTask was cancelled"); } @Override protected void onPostExecute(FeedItem feedItem) { super.onPostExecute(feedItem); if (feedItem != null && feedItem.getFeed() != null) { item = feedItem; populateUI(); supportInvalidateOptionsMenu(); } else { if (feedItem == null) { Log.e(TAG, "Error: FeedItem was null"); } else if (feedItem.getFeed() == null) { Log.e(TAG, "Error: Feed was null"); } } } }; loadTask.execute(itemId); currentLoadTask = loadTask; } private synchronized void populateUI() { if (!guiInitialized) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.feeditemview); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); ItemDescriptionFragment fragment = ItemDescriptionFragment .newInstance(item, false); fragmentTransaction.replace(R.id.description_fragment, fragment); fragmentTransaction.commit(); } TextView txtvTitle = (TextView) findViewById(R.id.txtvItemname); TextView txtvPublished = (TextView) findViewById(R.id.txtvPublished); setTitle(item.getFeed().getTitle()); txtvPublished.setText(DateUtils.formatSameDayTime(item.getPubDate() .getTime(), System.currentTimeMillis(), DateFormat.MEDIUM, DateFormat.SHORT)); txtvTitle.setText(item.getTitle()); guiInitialized = true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (item != null) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.feeditem, menu); return true; } else { return false; } } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { try { if (!FeedItemMenuHandler.onMenuItemClicked(this, menuItem.getItemId(), item)) { switch (menuItem.getItemId()) { case android.R.id.home: finish(); break; } } } catch (DownloadRequestException e) { e.printStackTrace(); DownloadRequestErrorDialogCreator.newRequestErrorDialog(this, e.getMessage()); } supportInvalidateOptionsMenu(); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { super.onPrepareOptionsMenu(menu); return FeedItemMenuHandler.onPrepareMenu( new FeedItemMenuHandler.MenuInterface() { @Override public void setItemVisibility(int id, boolean visible) { menu.findItem(id).setVisible(visible); } }, item, true, QueueAccess.NotInQueueAccess()); } private EventDistributor.EventListener contentUpdate = new EventDistributor.EventListener() { @Override public void update(EventDistributor eventDistributor, Integer arg) { if ((EVENTS & arg) != 0) { if (AppConfig.DEBUG) Log.d(TAG, "Received contentUpdate Intent."); if (item != null) { loadData(item.getId()); } } } }; }
package de.lmu.ifi.dbs.preprocessing; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.database.AssociationID; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.distance.Distance; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.utilities.QueryResult; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.varianceanalysis.LimitEigenPairFilter; import de.lmu.ifi.dbs.varianceanalysis.LinearLocalPCA; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Preprocessor for 4C local dimensionality and locally weighted matrix assignment * to objects of a certain database. * * @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class FourCPreprocessor extends ProjectedDBSCANPreprocessor { /** * Holds the class specific debug status. */ @SuppressWarnings({"UNUSED_SYMBOL"}) private static final boolean DEBUG = LoggingConfiguration.DEBUG; // private static final boolean DEBUG = true; /** * The logger of this class. */ @SuppressWarnings({"FieldCanBeLocal"}) private Logger logger = Logger.getLogger(this.getClass().getName()); /** * The parameter settings for the PCA. */ private String[] pcaParameters; /** * This method implements the type of variance analysis to be computed for a given point. * <p/> * Example1: for 4C, this method should implement a PCA for the given point. * Example2: for PreDeCon, this method should implement a simple axis-parallel variance analysis. * * @param id the given point * @param neighbors the neighbors as query results of the given point * @param database the database for which the preprocessing is performed */ protected <D extends Distance<D>> void runVarianceAnalysis(Integer id, List<QueryResult<D>> neighbors, Database<RealVector> database) { LinearLocalPCA pca = new LinearLocalPCA(); try { pca.setParameters(pcaParameters); } catch (ParameterException e) { // tested before throw new RuntimeException("This should never happen!"); } List<Integer> ids = new ArrayList<Integer>(neighbors.size()); for (QueryResult<D> neighbor : neighbors) { ids.add(neighbor.getID()); } pca.run(ids, database); if (DEBUG) { StringBuffer msg = new StringBuffer(); msg.append("\n").append(id).append(" ").append(database.getAssociation(AssociationID.LABEL, id)); msg.append("\ncorrDim ").append(pca.getCorrelationDimension()); // msg.append("\nsimMatrix ").append(pca.getSimilarityMatrix()); logger.fine(msg.toString()); } database.associate(AssociationID.LOCAL_DIMENSIONALITY, id, pca.getCorrelationDimension()); database.associate(AssociationID.LOCALLY_WEIGHTED_MATRIX, id, pca.getSimilarityMatrix()); } /** * Sets the values for the parameters alpha, pca and pcaDistancefunction if * specified. If the parameters are not specified default values are set. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ public String[] setParameters(String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); // save parameters for pca LinearLocalPCA tmpPCA = new LinearLocalPCA(); // save parameters for pca String[] tmpPCAParameters = new String[remainingParameters.length + 6]; System.arraycopy(remainingParameters, 0, tmpPCAParameters, 6, remainingParameters.length); // eigen pair filter tmpPCAParameters[0] = OptionHandler.OPTION_PREFIX + LinearLocalPCA.EIGENPAIR_FILTER_P; tmpPCAParameters[1] = LimitEigenPairFilter.class.getName(); // big value tmpPCAParameters[2] = OptionHandler.OPTION_PREFIX + LinearLocalPCA.BIG_VALUE_P; tmpPCAParameters[3] = "50"; // small value tmpPCAParameters[4] = OptionHandler.OPTION_PREFIX + LinearLocalPCA.SMALL_VALUE_P; tmpPCAParameters[5] = "1"; // FIXME: hier Fehler? (Simon hat Problem: keine Options gesetzt) remainingParameters = tmpPCA.setParameters(tmpPCAParameters); // XXX warum remainingParameters ueberschrieben? pcaParameters = tmpPCA.getParameters(); setParameters(args, remainingParameters); return remainingParameters; } /** * Returns the parameter setting of the attributes. * * @return the parameter setting of the attributes */ public List<AttributeSettings> getAttributeSettings() { List<AttributeSettings> attributeSettings = super.getAttributeSettings(); LinearLocalPCA tmpPCA = new LinearLocalPCA(); try { tmpPCA.setParameters(pcaParameters); } catch (ParameterException e) { // tested before throw new RuntimeException("This should never happen!"); } attributeSettings.addAll(tmpPCA.getAttributeSettings()); return attributeSettings; } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#description() */ public String description() { StringBuffer description = new StringBuffer(); description.append(FourCPreprocessor.class.getName()); description.append(" computes the local dimensionality and locally weighted matrix of objects of a certain database according to the 4C algorithm.\n"); description.append("The PCA is based on epsilon range queries.\n"); description.append(optionHandler.usage("", false)); return description.toString(); } }
package de.onyxbits.bureauengine.screen; import com.badlogic.gdx.Screen; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Texture; import de.onyxbits.bureauengine.BureauGame; /** * Implements a fading over effect between two screens (fade to black, fade from black). Note: * music is faded as well, meaning, this class will manipulate the <code>Music</code> object * on the target screen, potentially setting it to null or even replacing it. */ public class FadeOverScreen implements Screen { private Screen fromScreen; private BureauScreen toScreen; private BureauGame game; private int state; private int screenWidth,screenHeight; /** * timespan for fading in/out */ private float fadeDuration; /** * Accumulator for the fading */ private float fadeTime; /** * Progress status of the fading process */ private float fadePercent; /** * Fading state */ private static final int FADEOUT=1; /** * Fading state */ private static final int MIDWAY=2; /** * Fading state */ private static final int SKIP=3; /** * Fading state */ private static final int FADEIN=4; /** * Overlay for producing the fade effect */ private Texture blankTexture; /** * Fade over to another screen * @param toScreen target screen. * @param time time in seconds for how long the fading in/out takes each. */ public void fadeTo(BureauScreen toScreen, float time) { this.toScreen=toScreen; this.game=toScreen.game; this.fromScreen=game.getScreen(); // If this is null, someone is using the engine in a funky way. state=FADEOUT; screenWidth=Gdx.graphics.getWidth(); screenHeight=Gdx.graphics.getWidth(); fadeDuration=time; fadePercent=0; fadeTime=0; Gdx.input.setInputProcessor(null); game.setScreen(this); } @Override public void render(float delta) { switch(state) { case FADEOUT: { fromScreen.render(delta); if (fade(delta)) { state=MIDWAY; } break; } case MIDWAY: { // The overlay is fully opaque now -> we can get away with stalling the rendering thread // without the player noticing. fadePercent=0; fadeTime=0; if ((fromScreen instanceof BureauScreen) && ((BureauScreen)fromScreen).music!=null) { ((BureauScreen)fromScreen).music.stop(); } toScreen.prepareAssets(true); toScreen.readyScreen(); if (toScreen.music!=null) { toScreen.music.setVolume(0); if (!game.muteManager.isMusicMuted()) toScreen.music.play(); } fromScreen.dispose(); fromScreen=null; System.gc(); state=SKIP; break; } case SKIP: { // Skip the first frame on toScreen. We have to do this since textures can only be loaded // on the GL thread, potentially stalling it and resulting in a spike in delta time. Such // spikes mess with the fading math. Easiest way to compensate is by throwing one frame away. // Note: an alternative approach would be to call AssetManager.update() on every odd frame while // fading out and skip the actual rendering for those frames. However, tests showed that this // produces very choppy fading. state=FADEIN; break; } case FADEIN: { toScreen.render(delta); if (fade(delta)) { // We have to do a little dance with the music here. Game.setScreen() will call // BureauScreen.show() and that will call Music.play(). Ideally, Music.play() should // do nothing if it is already playing, but not all backends seem to implement it that // way. So, in order to prevent an audio glitch, take it away temporarily. // FIXME: Wouldn't it be better to use a NullMusic object here? Someone implementing a // screen may not be aware of this little hack and run into a nullpointerexcpetion. On // the other hand: its another object to lug around and may cause even weirder and harder // to debug side effects. Music tmp = toScreen.music; toScreen.music=null; game.setScreen(toScreen); toScreen.music=tmp; toScreen=null; } break; } } } /** * Fade this screen in or out. * @param delta detla from <code>render(delta)</code> * @return true when the screen is fully faded. */ private boolean fade(float delta) { if (fadePercent>=1) return true; // Calculate progress by accumulating delta time. fadeTime += delta; if (fadeTime>=fadeDuration) fadePercent = 1; else { fadePercent = fadeTime / fadeDuration; } Color tmp = game.spriteBatch.getColor(); // Apply the effect if (state==FADEOUT) { if ((fromScreen instanceof BureauScreen) && ((BureauScreen)fromScreen).music!=null) { ((BureauScreen)fromScreen).music.setVolume(1f-fadePercent); } game.spriteBatch.begin(); game.spriteBatch.setColor(0,0,0,fadePercent); game.spriteBatch.draw(blankTexture,0,0,screenWidth,screenHeight); game.spriteBatch.end(); } if (state==FADEIN) { if (toScreen.music!=null) { toScreen.music.setVolume(fadePercent); } game.spriteBatch.begin(); game.spriteBatch.setColor(0,0,0,1f-fadePercent); game.spriteBatch.draw(blankTexture,0,0,screenWidth,screenHeight); game.spriteBatch.end(); } game.spriteBatch.setColor(tmp); return fadePercent>=1; } /** * (re-)Create the blank texture */ private void dynamicTextures() { if (blankTexture!=null) blankTexture.dispose(); Pixmap pix = new Pixmap(2, 2, Format.RGBA8888); pix.setColor(Color.BLACK); pix.fill(); blankTexture=new Texture(pix); pix.dispose(); } @Override public void show() { dynamicTextures(); } @Override public void hide() { } @Override public void resume() { dynamicTextures(); } @Override public void resize(int w, int h) { dynamicTextures(); screenWidth=w; screenHeight=h; } @Override public void pause() {} @Override public void dispose() { if (blankTexture!=null) blankTexture.dispose(); } }
package de.unipaderborn.visuflow.ui.graph; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_FILTER_GRAPH; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_MODEL_CHANGED; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_SELECTION; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_UNIT_CHANGED; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToolBar; import javax.swing.JToolTip; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.graphstream.algorithm.Toolkit; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.MultiGraph; import org.graphstream.ui.geom.Point3; import org.graphstream.ui.graphicGraph.GraphicElement; import org.graphstream.ui.layout.Layout; import org.graphstream.ui.layout.springbox.implementations.SpringBox; import org.graphstream.ui.swingViewer.ViewPanel; import org.graphstream.ui.view.Viewer; import org.graphstream.ui.view.ViewerListener; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import com.google.common.base.Optional; import de.unipaderborn.visuflow.debug.handlers.NavigationHandler; import de.unipaderborn.visuflow.model.DataModel; import de.unipaderborn.visuflow.model.VFClass; import de.unipaderborn.visuflow.model.VFEdge; import de.unipaderborn.visuflow.model.VFMethod; import de.unipaderborn.visuflow.model.VFMethodEdge; import de.unipaderborn.visuflow.model.VFNode; import de.unipaderborn.visuflow.model.VFUnit; import de.unipaderborn.visuflow.model.graph.ControlFlowGraph; import de.unipaderborn.visuflow.model.graph.ICFGStructure; import de.unipaderborn.visuflow.util.ServiceUtil; public class GraphManager implements Runnable, ViewerListener, EventHandler { Graph graph; String styleSheet; int maxLength; private Viewer viewer; private ViewPanel view; List<VFClass> analysisData; Container panel; JApplet applet; JButton zoomInButton, zoomOutButton, viewCenterButton, toggleLayout, showICFGButton, btColor; JToolBar settingsBar; JDialog dialog; JPanel panelColor; JColorChooser jcc; double zoomInDelta, zoomOutDelta, maxZoomPercent, minZoomPercent, panXDelta, panYDelta; boolean autoLayoutEnabled = false; Layout graphLayout = new SpringBox(); private JToolTip tip; private JButton panLeftButton; private JButton panRightButton; private JButton panUpButton; private JButton panDownButton; private BufferedImage imgLeft; private BufferedImage imgRight; private BufferedImage imgUp; private BufferedImage imgDown; private BufferedImage imgPlus; private BufferedImage imgMinus; private boolean CFG; public GraphManager(String graphName, String styleSheet) { System.setProperty("sun.awt.noerasebackground", "true"); System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer"); this.panXDelta = 2; this.panYDelta = 2; this.zoomInDelta = .075; this.zoomOutDelta = .075; this.maxZoomPercent = 0.2; this.minZoomPercent = 1.0; this.maxLength = 45; this.styleSheet = styleSheet; createGraph(graphName); createUI(); renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); } public Container getApplet() { return applet.getRootPane(); } private void registerEventHandler() { String [] topics = new String[] { EA_TOPIC_DATA_FILTER_GRAPH, EA_TOPIC_DATA_SELECTION, EA_TOPIC_DATA_MODEL_CHANGED, EA_TOPIC_DATA_UNIT_CHANGED, "GraphReady" }; Hashtable<String, Object> properties = new Hashtable<>(); properties.put(EventConstants.EVENT_TOPIC, topics); ServiceUtil.registerService(EventHandler.class, this, properties); } void createGraph(String graphName) { graph = new MultiGraph(graphName); graph.addAttribute("ui.stylesheet", styleSheet); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD); viewer.setCloseFramePolicy(Viewer.CloseFramePolicy.CLOSE_VIEWER); view = viewer.addDefaultView(false); view.getCamera().setAutoFitView(true); // view.removeMouseMotionListener(view.getMouseMotionListeners()[0]); } private void reintializeGraph() throws Exception { if(graph != null) { graph.clear(); graph.addAttribute("ui.stylesheet", styleSheet); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); } else throw new Exception("Graph is null"); } private void createUI() { createIcons(); createZoomControls(); createShowICFGButton(); createPanningButtons(); createViewListeners(); createToggleLayoutButton(); createSettingsBar(); createPanel(); createAppletContainer(); // colorNode(); } private void panUp() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y + panYDelta, 0); } private void panDown() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y - panYDelta, 0); } private void panLeft() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x - panXDelta, currCenter.y, 0); } private void panRight() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x + panXDelta, currCenter.y, 0); } private void panToNode(String nodeId) { Node panToNode = graph.getNode(nodeId); double[] pos = Toolkit.nodePosition(panToNode); double currPosition = view.getCamera().getViewCenter().y; while(pos[1] > currPosition) { try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } view.getCamera().setViewCenter(pos[0], currPosition++, 0.0); } } private void defaultPanZoom() { /*try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); }*/ int count = 0; if(graph.getNodeCount() > 10) count = 10; for (int i = 0; i < count; i++) { try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GraphManager.this.zoomIn(); } }); } } private void createPanningButtons() { panLeftButton = new JButton(""); panRightButton = new JButton(""); panUpButton = new JButton(""); panDownButton = new JButton(""); panLeftButton.setIcon(new ImageIcon(getScaledImage(imgLeft, 20, 20))); panRightButton.setIcon(new ImageIcon(getScaledImage(imgRight, 20, 20))); panUpButton.setIcon(new ImageIcon(getScaledImage(imgUp, 20, 20))); panDownButton.setIcon(new ImageIcon(getScaledImage(imgDown, 20, 20))); panLeftButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panLeft(); } }); panRightButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panRight(); } }); panUpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panUp(); } }); panDownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panDown(); } }); } private void createIcons() { try { ClassLoader loader = GraphManager.class.getClassLoader(); imgLeft = ImageIO.read(loader.getResource("/icons/left.png")); imgRight = ImageIO.read(loader.getResource("/icons/right.png")); imgUp = ImageIO.read(loader.getResource("/icons/up.png")); imgDown = ImageIO.read(loader.getResource("/icons/down.png")); imgPlus = ImageIO.read(loader.getResource("/icons/plus.png")); imgMinus = ImageIO.read(loader.getResource("/icons/minus.png")); } catch (IOException e) { e.printStackTrace(); } } private Image getScaledImage(Image srcImg, int w, int h){ BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(srcImg, 0, 0, w, h, null); g2.dispose(); return resizedImg; } private void createShowICFGButton() { showICFGButton = new JButton("Show ICFG"); showICFGButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); } }); } private void createAppletContainer() { applet = new JApplet(); applet.add(panel); } private void createSettingsBar() { settingsBar = new JToolBar("ControlsBar", JToolBar.HORIZONTAL); settingsBar.add(zoomInButton); settingsBar.add(zoomOutButton); settingsBar.add(showICFGButton); settingsBar.add(viewCenterButton); settingsBar.add(toggleLayout); settingsBar.add(btColor); settingsBar.add(panLeftButton); settingsBar.add(panRightButton); settingsBar.add(panUpButton); settingsBar.add(panDownButton); } private void createPanel() { panel = new JFrame().getContentPane(); panel.add(view); panel.add(settingsBar, BorderLayout.PAGE_END); } private void createViewListeners() { view.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { int rotationDirection = e.getWheelRotation(); if(rotationDirection > 0) zoomIn(); else zoomOut(); } }); view.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent event) { GraphicElement curElement = view.findNodeOrSpriteAt(event.getX(), event.getY()); if(curElement == null && tip != null) { tip.setVisible(false); setTip(null); view.repaint(); } if(curElement != null && tip == null) { Node node=graph.getNode(curElement.getId()); String result = "<html><table>"; int maxToolTipLength=0; int height=0; for(String key:node.getEachAttributeKey()) { if(key.startsWith("nodeData")){ height++; Object value = node.getAttribute(key); String tempVal=key.substring(key.lastIndexOf(".")+1)+" : "+value.toString(); if(tempVal.length()>maxToolTipLength){ maxToolTipLength=tempVal.length(); } result+="<tr><td>"+key.substring(key.lastIndexOf(".")+1)+"</td>"+"<td>"+value.toString()+"</td></tr>"; } } result+="</table></html>"; tip = new JToolTip(); String tipText = result; tip.setTipText(tipText); tip.setBounds(event.getX() - tipText.length()*3 + 1, event.getY(), maxToolTipLength*3+3,height*30 ); setTip(tip); tip.setVisible(true); if(tipText.length() > 10) { tip.setLocation(event.getX()-15, event.getY()); } view.add(tip); tip.repaint(); } } @Override public void mouseDragged(MouseEvent e) { } }); view.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { //noop } @Override public void mousePressed(MouseEvent e) { //noop } @Override public void mouseExited(MouseEvent e) { //noop } @Override public void mouseEntered(MouseEvent e) { //noop } @Override public void mouseClicked(MouseEvent e) { DataModel dataModel = ServiceUtil.getService(DataModel.class); GraphicElement curElement = view.findNodeOrSpriteAt(e.getX(), e.getY()); if(curElement == null) return; Node curr = graph.getNode(curElement.getId()); if(e.getButton() == MouseEvent.BUTTON1 && !CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeMethod"); if(node instanceof VFMethod) { VFMethod selectedMethod = (VFMethod) node; try { if(selectedMethod.getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { // renderMethodCFG(selectedMethod.getControlFlowGraph()); dataModel.setSelectedMethod(selectedMethod, true); // List<VFMethodEdge> incEdges = selectedMethod.getIncomingEdges(); /*for(VFMethodEdge edge : incEdges){ System.out.println(edge); }*/ } } catch (Exception e1) { e1.printStackTrace(); } } } else if(e.getButton() == MouseEvent.BUTTON1 && CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if(node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.HighlightJimpleLine(units); ArrayList<VFNode> nodes = new ArrayList<>(); nodes.add((VFNode) node); try { dataModel.filterGraph(nodes, true); } catch (Exception e1) { e1.printStackTrace(); } } } else if(e.getButton() == MouseEvent.BUTTON1 && CFG && (e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { String id = curr.getId(); if(id != null) toggleNode(id); } /*else { Object node = curr.getAttribute("nodeUnit"); if(node instanceof VFNode) { dataModel.HighlightJimpleUnit((VFNode) node); if(((Stmt)((VFNode) node).getUnit()).containsInvokeExpr()){ callInvokeExpr(((Stmt)((VFNode) node).getUnit()).getInvokeExpr()); } } }*/ } }); } /*private void callInvokeExpr(InvokeExpr expr){ if(expr == null) return; DataModel dataModel = ServiceUtil.getService(DataModel.class); System.out.println(expr); VFMethod selectedMethod = dataModel.getVFMethodByName(expr.getMethod()); try { if(selectedMethod.getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(selectedMethod, true); } } catch (Exception e1) { e1.printStackTrace(); } }*/ private void zoomIn() { double viewPercent = view.getCamera().getViewPercent(); if(viewPercent > maxZoomPercent) view.getCamera().setViewPercent(viewPercent - zoomInDelta); } private void zoomOut() { double viewPercent = view.getCamera().getViewPercent(); if(viewPercent < minZoomPercent) view.getCamera().setViewPercent(viewPercent + zoomOutDelta); } private void createZoomControls() { zoomInButton = new JButton(); zoomOutButton = new JButton(); viewCenterButton = new JButton("reset"); zoomInButton.setIcon(new ImageIcon(getScaledImage(imgPlus, 20, 20))); zoomOutButton.setIcon(new ImageIcon(getScaledImage(imgMinus, 20, 20))); zoomInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomIn(); } }); zoomOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomOut(); } }); viewCenterButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { view.getCamera().resetView(); } }); colorNode(); } private void createToggleLayoutButton() { toggleLayout = new JButton(); toggleAutoLayout(); toggleLayout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleAutoLayout(); } }); } private void toggleAutoLayout() { if(!autoLayoutEnabled) { if(viewer != null && graphLayout != null) { // viewer.enableAutoLayout(graphLayout); experimentalLayout(); } else if(viewer != null) { // viewer.enableAutoLayout(); experimentalLayout(); } autoLayoutEnabled = true; toggleLayout.setText("Disable Layouting"); } else { viewer.disableAutoLayout(); autoLayoutEnabled = false; toggleLayout.setText("Enable Layouting"); } } private void colorNode(){ jcc = new JColorChooser(Color.BLUE); jcc.getSelectionModel().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { Color color = jcc.getColor(); System.out.println("color:"+ color); } }); dialog = JColorChooser.createDialog(null, "Color Chooser", true, jcc, null, null); panelColor = new JPanel(new GridLayout(0, 2)); btColor = new JButton ("Color nodes"); btColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { colorTheGraph(); } }); } private void filterGraphNodes(List<VFNode> nodes, boolean selected) { boolean panned = false; Iterable<? extends Node> graphNodes = graph.getEachNode(); for (Node node : graphNodes) { if(node.hasAttribute("ui.clicked")) node.removeAttribute("ui.clicked"); for (VFNode vfNode : nodes) { if(node.getAttribute("nodeData.unit").toString().contentEquals(vfNode.getUnit().toString())) { if(selected) node.setAttribute("ui.clicked"); if(!panned) this.panToNode(node.getId()); } } } } private void renderICFG(ICFGStructure icfg) { if(icfg == null) { return; } Iterator<VFMethodEdge> iterator = icfg.listEdges.iterator(); try { reintializeGraph(); } catch (Exception e) { e.printStackTrace(); } while(iterator.hasNext()) { VFMethodEdge curr = iterator.next(); VFMethod src = curr.getSourceMethod(); VFMethod dest = curr.getDestMethod(); createGraphMethodNode(src); createGraphMethodNode(dest); createGraphMethodEdge(src, dest); } this.CFG = false; experimentalLayout(); } private void createGraphMethodEdge(VFMethod src, VFMethod dest) { if(graph.getEdge("" + src.getId() + dest.getId()) == null) { graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); } } private void createGraphMethodNode(VFMethod src) { if(graph.getNode(src.getId() + "") == null) { Node createdNode = graph.addNode(src.getId() + ""); createdNode.setAttribute("ui.label", src.getSootMethod().getName().toString()); createdNode.setAttribute("nodeData.methodName", src.getSootMethod().getName()); createdNode.setAttribute("nodeData.methodSignature", src.getSootMethod().getSignature()); createdNode.setAttribute("nodeMethod", src); } } private void renderMethodCFG(ControlFlowGraph interGraph, boolean panToNode) throws Exception { if(interGraph == null) throw new Exception("GraphStructure is null"); this.reintializeGraph(); ListIterator<VFEdge> edgeIterator = interGraph.listEdges.listIterator(); while(edgeIterator.hasNext()) { VFEdge currEdgeIterator = edgeIterator.next(); VFNode src = currEdgeIterator.getSource(); VFNode dest = currEdgeIterator.getDestination(); createGraphNode(src); createGraphNode(dest); createGraphEdge(src,dest); } this.CFG = true; experimentalLayout(); if(panToNode) { defaultPanZoom(); panToNode(graph.getNodeIterator().next().getId()); } } private void createGraphEdge(VFNode src, VFNode dest) { if(graph.getEdge("" + src.getId() + dest.getId()) == null) { Edge createdEdge = graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); VFUnit unit = src.getVFUnit(); createdEdge.addAttribute("ui.label", Optional.fromNullable(unit.getOutSet()).or("").toString()); createdEdge.addAttribute("edgeData.outSet", Optional.fromNullable(unit.getInSet()).or("").toString()); } } private void createGraphNode(VFNode node) { if(graph.getNode(node.getId() + "") == null) { Node createdNode = graph.addNode(node.getId() + ""); if(node.getUnit().toString().length() > maxLength) { createdNode.setAttribute("ui.label", node.getUnit().toString().substring(0, maxLength) + "..."); } else { createdNode.setAttribute("ui.label", node.getUnit().toString()); } createdNode.setAttribute("nodeData.unit", node.getUnit().toString()); createdNode.setAttribute("nodeData.unitType", node.getUnit().getClass()); createdNode.setAttribute("nodeData.inSet", Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString()); createdNode.setAttribute("nodeData.outSet", Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString()); createdNode.setAttribute("nodeData.line", node.getUnit().getJavaSourceStartLineNumber()); createdNode.setAttribute("nodeData.column", node.getUnit().getJavaSourceStartColumnNumber()); createdNode.setAttribute("nodeUnit", node); } } /*private void experimentalLayout() { if(!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } viewer.disableAutoLayout(); double spacing = 2.0; double rowSpacing = 18.0; double nodeCount = graph.getNodeCount() * spacing; Iterator<Node> nodeIterator = graph.getNodeIterator(); while(nodeIterator.hasNext()) { Node curr = nodeIterator.next(); Iterator<Edge> leavingEdgeIterator = curr.getEdgeIterator(); double outEdges = 0.0; while(leavingEdgeIterator.hasNext()) { Edge outEdge = leavingEdgeIterator.next(); Node target = outEdge.getTargetNode(); target.setAttribute("xyz", outEdges, nodeCount, 0.0); outEdges += rowSpacing; } curr.setAttribute("xyz", 0.0, nodeCount, 0.0); nodeCount -= spacing; } }*/ private void experimentalLayout() { if(!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } viewer.disableAutoLayout(); double rowSpacing = 3.0; double columnSpacing = 3.0; Iterator<Node> nodeIterator = graph.getNodeIterator(); int totalNodeCount = graph.getNodeCount(); int currNodeIndex = 0; while(nodeIterator.hasNext()) { Node curr = nodeIterator.next(); if(curr.hasAttribute("layout.visited")) { continue; } int currEdgeCount = curr.getOutDegree(); int currEdgeIndex = 0; if(currEdgeCount > 1) { Iterator<Edge> currEdgeIterator = curr.getEdgeIterator(); curr.setAttribute("xyz", 0.0, ((totalNodeCount * rowSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currNodeIndex++; while(currEdgeIterator.hasNext()) { Node temp = currEdgeIterator.next().getOpposite(curr); temp.setAttribute("xyz", ((columnSpacing- currEdgeIndex) * currEdgeCount), ((totalNodeCount * columnSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currEdgeIndex++; } currNodeIndex++; } curr.setAttribute("xyz", 0.0, ((totalNodeCount * rowSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currNodeIndex++; } for (Node node : graph) { int inDegree = node.getInDegree(); int outDegree = node.getOutDegree(); if(inDegree == 0) continue; if(inDegree > outDegree) { double[] pos = Toolkit.nodePosition(graph, node.getId()); node.setAttribute("xyz", pos[0] - rowSpacing, pos[1], 0); } else if(outDegree > inDegree) { double[] pos = Toolkit.nodePosition(graph, node.getId()); node.setAttribute("xyz", pos[0] + rowSpacing, pos[1], 0); } else if(inDegree == outDegree) { continue; } else continue; } view.getCamera().resetView(); } /*private void experimentalLayout() { if(!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } viewer.disableAutoLayout(); viewer.enableAutoLayout(new HierarchicalLayout()); graph.addNode("temp"); viewer.disableAutoLayout(); view.getCamera().resetView(); for (Node node : graph) { double[] pos = Toolkit.nodePosition(node); node.setAttribute("xyz", pos[1], pos[0], pos[2]); } }*/ void toggleNode(String id){ Node n = graph.getNode(id); Object[] pos = n.getAttribute("xyz"); Iterator<Node> it = n.getBreadthFirstIterator(true); if(n.hasAttribute("collapsed")){ n.removeAttribute("collapsed"); while(it.hasNext()){ Node m = it.next(); for(Edge e : m.getLeavingEdgeSet()) { e.removeAttribute("ui.hide"); } m.removeAttribute("layout.frozen"); m.setAttribute("x",((double)pos[0])+Math.random()*0.0001); m.setAttribute("y",((double)pos[1])+Math.random()*0.0001); m.removeAttribute("ui.hide"); } n.removeAttribute("ui.class"); } else { n.setAttribute("ui.class", "plus"); n.setAttribute("collapsed"); while(it.hasNext()){ Node m = it.next(); for(Edge e : m.getLeavingEdgeSet()) { e.setAttribute("ui.hide"); } if(n != m) { m.setAttribute("layout.frozen"); // m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001); // m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001); m.setAttribute("xyz", ((double) pos[0]) + Math.random() * 0.0001, ((double) pos[1]) + Math.random() * 0.0001, 0.0); m.setAttribute("ui.hide"); } } } experimentalLayout(); panToNode(id); } @Override public void run() { this.registerEventHandler(); System.out.println("GraphManager ---> registered for events"); // ViewerPipe fromViewer = viewer.newViewerPipe(); // fromViewer.addViewerListener(this); // fromViewer.addSink(graph); // FIXME the Thread.sleep slows down the loop, so that it does not eat up the CPU // but this really should be implemented differently. isn't there an event listener // or something we can use, so that we call pump() only when necessary // while(true) { // try { // Thread.sleep(1); // } catch (InterruptedException e) { // fromViewer.pump(); } @Override public void buttonPushed(String id) { //noop } @Override public void buttonReleased(String id) { toggleNode(id); experimentalLayout(); } @Override public void viewClosed(String id) { //noop } protected void setTip(JToolTip toolTip) { this.tip = toolTip; } @SuppressWarnings("unchecked") @Override public void handleEvent(Event event) { if(event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_MODEL_CHANGED)) { renderICFG((ICFGStructure) event.getProperty("icfg")); } if(event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_SELECTION)) { VFMethod selectedMethod = (VFMethod) event.getProperty("selectedMethod"); boolean panToNode = (boolean) event.getProperty("panToNode"); try { renderMethodCFG(selectedMethod.getControlFlowGraph(), panToNode); } catch (Exception e) { e.printStackTrace(); } } if(event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_FILTER_GRAPH)) { filterGraphNodes((List<VFNode>) event.getProperty("nodesToFilter"), (boolean) event.getProperty("selection")); } if(event.getTopic().equals(DataModel.EA_TOPIC_DATA_UNIT_CHANGED)) { VFUnit unit = (VFUnit) event.getProperty("unit"); for (Edge edge : graph.getEdgeSet()) { Node src = edge.getSourceNode(); VFNode vfNode = src.getAttribute("nodeUnit"); if(vfNode != null) { VFUnit currentUnit = vfNode.getVFUnit(); if(unit.getFullyQualifiedName().equals(currentUnit.getFullyQualifiedName())) { String outset = Optional.fromNullable(unit.getOutSet()).or("").toString(); edge.setAttribute("ui.label", outset); edge.setAttribute("edgeData.outSet", outset); src.addAttribute("nodeData.inSet", unit.getInSet()); src.addAttribute("nodeData.outSet", unit.getOutSet()); System.out.println("GraphManager: Unit changed: " + unit.getFullyQualifiedName()); System.out.println("GraphManager: Unit in-set: " + unit.getInSet()); System.out.println("GraphManager: Unit out-set: " + unit.getOutSet()); } } } } } private boolean inPanel( String btName, JPanel panel){ boolean exist = false; for(Component c : panel.getComponents()){ if (!(c.getName()== null)) { if ((c.getClass().toString().equals("class javax.swing.JButton"))) { JButton bt = (JButton) c; System.out.println("Button's name = " + c.getName()); if (bt.getName().equals(btName)) { System.out.println("btName = " + btName + " , component name = " + bt.getName()); exist = true; break; } } } } return exist; } public void colorTheGraph(){ panelColor.removeAll(); for(Node n: graph.getEachNode()){ if(!(n.getAttribute("nodeData.unitType") == null)){ JLabel l = new JLabel("Change the color of this unit"); JButton bt = new JButton(n.getAttribute("nodeData.unitType").toString()); // bt.setName(n.getAttribute("nodeData.methodName").toString()); bt.setName(n.getAttribute("nodeData.unitType").toString()); bt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(true); System.out.println("Button's name is : " + bt.getName()); System.out.println("Button's name is..." ); for(Node n: graph.getEachNode()){ // if(n.getAttribute("nodeData.methodName").toString().equals(bt.getName())){ // if(n.getAttribute("ui.label").toString().equals(bt.getName())){ if(n.getAttribute("nodeData.unitType").toString().equals(bt.getName())){ n.setAttribute("ui.color", jcc.getColor()); // n.setAttribute("ui.text-size", "20%"); System.out.println(jcc.getColor()); } } } }); if(!(inPanel(bt.getName(), panelColor))){ panelColor.add(l); panelColor.add(bt); } } if(!(n.getAttribute("nodeData.methodName")== null)){ JLabel l = new JLabel("Change the color of this unit"); JButton bt = new JButton(n.getAttribute("nodeData.methodName").toString()); // bt.setName(n.getAttribute("nodeData.methodName").toString()); bt.setName(n.getAttribute("nodeData.methodName").toString()); bt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(true); System.out.println("Button's name is : " + bt.getName()); System.out.println("Button's name is..." ); for(Node n: graph.getEachNode()){ // if(n.getAttribute("nodeData.methodName").toString().equals(bt.getName())){ // if(n.getAttribute("ui.label").toString().equals(bt.getName())){ if(n.getAttribute("nodeData.methodName").toString().equals(bt.getName())){ n.setAttribute("ui.color", jcc.getColor()); System.out.println(jcc.getColor()); } } } }); if(!(inPanel(bt.getName(), panelColor))){ panelColor.add(l); panelColor.add(bt); } } } int result = JOptionPane.showConfirmDialog(null, panelColor, "Test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { }else{ System.out.println("Cancelled"); } } }
package org.jfree.data.xy; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ParamChecks; import org.jfree.data.general.Series; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesException; import org.jfree.util.ObjectUtilities; /** * Represents a sequence of zero or more data items in the form (x, y). By * default, items in the series will be sorted into ascending order by x-value, * and duplicate x-values are permitted. Both the sorting and duplicate * defaults can be changed in the constructor. Y-values can be * <code>null</code> to represent missing values. */ public class XYSeries extends Series implements Cloneable, Serializable { /** For serialization. */ static final long serialVersionUID = -5908509288197150436L; // In version 0.9.12, in response to several developer requests, I changed // the 'data' attribute from 'private' to 'protected', so that others can // make subclasses that work directly with the underlying data structure. /** Storage for the data items in the series. */ protected List data; /** The maximum number of items for the series. */ private int maximumItemCount = Integer.MAX_VALUE; /** * A flag that controls whether the items are automatically sorted * (by x-value ascending). */ private boolean autoSort; /** A flag that controls whether or not duplicate x-values are allowed. */ private boolean allowDuplicateXValues; /** The lowest x-value in the series, excluding Double.NaN values. */ private double minX; /** The highest x-value in the series, excluding Double.NaN values. */ private double maxX; /** The lowest y-value in the series, excluding Double.NaN values. */ private double minY; /** The highest y-value in the series, excluding Double.NaN values. */ private double maxY; /** * Creates a new empty series. By default, items added to the series will * be sorted into ascending order by x-value, and duplicate x-values will * be allowed (these defaults can be modified with another constructor. * * @param key the series key (<code>null</code> not permitted). */ public XYSeries(Comparable key) { this(key, true, true); } /** * Constructs a new empty series, with the auto-sort flag set as requested, * and duplicate values allowed. * * @param key the series key (<code>null</code> not permitted). * @param autoSort a flag that controls whether or not the items in the * series are sorted. */ public XYSeries(Comparable key, boolean autoSort) { this(key, autoSort, true); } /** * Constructs a new xy-series that contains no data. You can specify * whether or not duplicate x-values are allowed for the series. * * @param key the series key (<code>null</code> not permitted). * @param autoSort a flag that controls whether or not the items in the * series are sorted. * @param allowDuplicateXValues a flag that controls whether duplicate * x-values are allowed. */ public XYSeries(Comparable key, boolean autoSort, boolean allowDuplicateXValues) { super(key); this.data = new java.util.ArrayList(); this.autoSort = autoSort; this.allowDuplicateXValues = allowDuplicateXValues; this.minX = Double.NaN; this.maxX = Double.NaN; this.minY = Double.NaN; this.maxY = Double.NaN; } /** * Returns the smallest x-value in the series, ignoring any Double.NaN * values. This method returns Double.NaN if there is no smallest x-value * (for example, when the series is empty). * * @return The smallest x-value. * * @see #getMaxX() * * @since 1.0.13 */ public double getMinX() { return this.minX; } /** * Returns the largest x-value in the series, ignoring any Double.NaN * values. This method returns Double.NaN if there is no largest x-value * (for example, when the series is empty). * * @return The largest x-value. * * @see #getMinX() * * @since 1.0.13 */ public double getMaxX() { return this.maxX; } /** * Returns the smallest y-value in the series, ignoring any null and * Double.NaN values. This method returns Double.NaN if there is no * smallest y-value (for example, when the series is empty). * * @return The smallest y-value. * * @see #getMaxY() * * @since 1.0.13 */ public double getMinY() { return this.minY; } /** * Returns the largest y-value in the series, ignoring any Double.NaN * values. This method returns Double.NaN if there is no largest y-value * (for example, when the series is empty). * * @return The largest y-value. * * @see #getMinY() * * @since 1.0.13 */ public double getMaxY() { return this.maxY; } /** * Updates the cached values for the minimum and maximum data values. * * @param item the item added (<code>null</code> not permitted). * * @since 1.0.13 */ private void updateBoundsForAddedItem(XYDataItem item) { double x = item.getXValue(); this.minX = minIgnoreNaN(this.minX, x); this.maxX = maxIgnoreNaN(this.maxX, x); if (item.getY() != null) { double y = item.getYValue(); this.minY = minIgnoreNaN(this.minY, y); this.maxY = maxIgnoreNaN(this.maxY, y); } } /** * Updates the cached values for the minimum and maximum data values on * the basis that the specified item has just been removed. * * @param item the item added (<code>null</code> not permitted). * * @since 1.0.13 */ private void updateBoundsForRemovedItem(XYDataItem item) { boolean itemContributesToXBounds = false; boolean itemContributesToYBounds = false; double x = item.getXValue(); if (!Double.isNaN(x)) { if (x <= this.minX || x >= this.maxX) { itemContributesToXBounds = true; } } if (item.getY() != null) { double y = item.getYValue(); if (!Double.isNaN(y)) { if (y <= this.minY || y >= this.maxY) { itemContributesToYBounds = true; } } } if (itemContributesToYBounds) { findBoundsByIteration(); } else if (itemContributesToXBounds) { if (getAutoSort()) { this.minX = getX(0).doubleValue(); this.maxX = getX(getItemCount() - 1).doubleValue(); } else { findBoundsByIteration(); } } } /** * Finds the bounds of the x and y values for the series, by iterating * through all the data items. * * @since 1.0.13 */ private void findBoundsByIteration() { this.minX = Double.NaN; this.maxX = Double.NaN; this.minY = Double.NaN; this.maxY = Double.NaN; Iterator iterator = this.data.iterator(); while (iterator.hasNext()) { XYDataItem item = (XYDataItem) iterator.next(); updateBoundsForAddedItem(item); } } /** * Returns the flag that controls whether the items in the series are * automatically sorted. There is no setter for this flag, it must be * defined in the series constructor. * * @return A boolean. */ public boolean getAutoSort() { return this.autoSort; } /** * Returns a flag that controls whether duplicate x-values are allowed. * This flag can only be set in the constructor. * * @return A boolean. */ public boolean getAllowDuplicateXValues() { return this.allowDuplicateXValues; } /** * Returns the number of items in the series. * * @return The item count. * * @see #getItems() */ public int getItemCount() { return this.data.size(); } /** * Returns the list of data items for the series (the list contains * {@link XYDataItem} objects and is unmodifiable). * * @return The list of data items. */ public List getItems() { return Collections.unmodifiableList(this.data); } /** * Returns the maximum number of items that will be retained in the series. * The default value is <code>Integer.MAX_VALUE</code>. * * @return The maximum item count. * * @see #setMaximumItemCount(int) */ public int getMaximumItemCount() { return this.maximumItemCount; } /** * Sets the maximum number of items that will be retained in the series. * If you add a new item to the series such that the number of items will * exceed the maximum item count, then the first element in the series is * automatically removed, ensuring that the maximum item count is not * exceeded. * <p> * Typically this value is set before the series is populated with data, * but if it is applied later, it may cause some items to be removed from * the series (in which case a {@link SeriesChangeEvent} will be sent to * all registered listeners). * * @param maximum the maximum number of items for the series. */ public void setMaximumItemCount(int maximum) { this.maximumItemCount = maximum; int remove = this.data.size() - maximum; if (remove > 0) { this.data.subList(0, remove).clear(); findBoundsByIteration(); fireSeriesChanged(); } } /** * Adds a data item to the series and sends a {@link SeriesChangeEvent} to * all registered listeners. * * @param item the (x, y) item (<code>null</code> not permitted). */ public void add(XYDataItem item) { // argument checking delegated... add(item, true); } /** * Adds a data item to the series and sends a {@link SeriesChangeEvent} to * all registered listeners. * * @param x the x value. * @param y the y value. */ public void add(double x, double y) { add(new Double(x), new Double(y), true); } /** * Adds a data item to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param x the x value. * @param y the y value. * @param notify a flag that controls whether or not a * {@link SeriesChangeEvent} is sent to all registered * listeners. */ public void add(double x, double y, boolean notify) { add(new Double(x), new Double(y), notify); } /** * Adds a data item to the series and sends a {@link SeriesChangeEvent} to * all registered listeners. The unusual pairing of parameter types is to * make it easier to add <code>null</code> y-values. * * @param x the x value. * @param y the y value (<code>null</code> permitted). */ public void add(double x, Number y) { add(new Double(x), y); } /** * Adds a data item to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. The unusual * pairing of parameter types is to make it easier to add null y-values. * * @param x the x value. * @param y the y value (<code>null</code> permitted). * @param notify a flag that controls whether or not a * {@link SeriesChangeEvent} is sent to all registered * listeners. */ public void add(double x, Number y, boolean notify) { add(new Double(x), y, notify); } /** * Adds a new data item to the series (in the correct position if the * <code>autoSort</code> flag is set for the series) and sends a * {@link SeriesChangeEvent} to all registered listeners. * <P> * Throws an exception if the x-value is a duplicate AND the * allowDuplicateXValues flag is false. * * @param x the x-value (<code>null</code> not permitted). * @param y the y-value (<code>null</code> permitted). * * @throws SeriesException if the x-value is a duplicate and the * <code>allowDuplicateXValues</code> flag is not set for this series. */ public void add(Number x, Number y) { // argument checking delegated... add(x, y, true); } /** * Adds new data to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. * <P> * Throws an exception if the x-value is a duplicate AND the * allowDuplicateXValues flag is false. * * @param x the x-value (<code>null</code> not permitted). * @param y the y-value (<code>null</code> permitted). * @param notify a flag the controls whether or not a * {@link SeriesChangeEvent} is sent to all registered * listeners. */ public void add(Number x, Number y, boolean notify) { // delegate argument checking to XYDataItem... XYDataItem item = new XYDataItem(x, y); add(item, notify); } /** * Adds a data item to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param item the (x, y) item (<code>null</code> not permitted). * @param notify a flag that controls whether or not a * {@link SeriesChangeEvent} is sent to all registered * listeners. */ public void add(XYDataItem item, boolean notify) { ParamChecks.nullNotPermitted(item, "item"); item = (XYDataItem) item.clone(); if (this.autoSort) { int index = Collections.binarySearch(this.data, item); if (index < 0) { this.data.add(-index - 1, item); } else { if (this.allowDuplicateXValues) { // need to make sure we are adding *after* any duplicates int size = this.data.size(); while (index < size && item.compareTo( this.data.get(index)) == 0) { index++; } if (index < this.data.size()) { this.data.add(index, item); } else { this.data.add(item); } } else { throw new SeriesException("X-value already exists."); } } } else { if (!this.allowDuplicateXValues) { // can't allow duplicate values, so we need to check whether // there is an item with the given x-value already int index = indexOf(item.getX()); if (index >= 0) { throw new SeriesException("X-value already exists."); } } this.data.add(item); } updateBoundsForAddedItem(item); if (getItemCount() > this.maximumItemCount) { XYDataItem removed = (XYDataItem) this.data.remove(0); updateBoundsForRemovedItem(removed); } if (notify) { fireSeriesChanged(); } } /** * Deletes a range of items from the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param start the start index (zero-based). * @param end the end index (zero-based). */ public void delete(int start, int end) { this.data.subList(start, end + 1).clear(); findBoundsByIteration(); fireSeriesChanged(); } /** * Removes the item at the specified index and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param index the index. * * @return The item removed. */ public XYDataItem remove(int index) { XYDataItem removed = (XYDataItem) this.data.remove(index); updateBoundsForRemovedItem(removed); fireSeriesChanged(); return removed; } /** * Removes an item with the specified x-value and sends a * {@link SeriesChangeEvent} to all registered listeners. Note that when * a series permits multiple items with the same x-value, this method * could remove any one of the items with that x-value. * * @param x the x-value. * @return The item removed. */ public XYDataItem remove(Number x) { return remove(indexOf(x)); } /** * Removes all data items from the series and sends a * {@link SeriesChangeEvent} to all registered listeners. */ public void clear() { if (this.data.size() > 0) { this.data.clear(); this.minX = Double.NaN; this.maxX = Double.NaN; this.minY = Double.NaN; this.maxY = Double.NaN; fireSeriesChanged(); } } /** * Return the data item with the specified index. * * @param index the index. * * @return The data item with the specified index. */ public XYDataItem getDataItem(int index) { XYDataItem item = (XYDataItem) this.data.get(index); return (XYDataItem) item.clone(); } /** * Return the data item with the specified index. * * @param index the index. * * @return The data item with the specified index. * * @since 1.0.14 */ XYDataItem getRawDataItem(int index) { return (XYDataItem) this.data.get(index); } /** * Returns the x-value at the specified index. * * @param index the index (zero-based). * * @return The x-value (never <code>null</code>). */ public Number getX(int index) { return getRawDataItem(index).getX(); } /** * Returns the y-value at the specified index. * * @param index the index (zero-based). * * @return The y-value (possibly <code>null</code>). */ public Number getY(int index) { return getRawDataItem(index).getY(); } /** * Updates the value of an item in the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param index the item (zero based index). * @param y the new value (<code>null</code> permitted). * * @deprecated Renamed {@link #updateByIndex(int, Number)} to avoid * confusion with the {@link #update(Number, Number)} method. */ public void update(int index, Number y) { XYDataItem item = getRawDataItem(index); // figure out if we need to iterate through all the y-values boolean iterate = false; double oldY = item.getYValue(); if (!Double.isNaN(oldY)) { iterate = oldY <= this.minY || oldY >= this.maxY; } item.setY(y); if (iterate) { findBoundsByIteration(); } else if (y != null) { double yy = y.doubleValue(); this.minY = minIgnoreNaN(this.minY, yy); this.maxY = maxIgnoreNaN(this.maxY, yy); } fireSeriesChanged(); } /** * A function to find the minimum of two values, but ignoring any * Double.NaN values. * * @param a the first value. * @param b the second value. * * @return The minimum of the two values. */ private double minIgnoreNaN(double a, double b) { if (Double.isNaN(a)) { return b; } if (Double.isNaN(b)) { return a; } return Math.min(a, b); } /** * A function to find the maximum of two values, but ignoring any * Double.NaN values. * * @param a the first value. * @param b the second value. * * @return The maximum of the two values. */ private double maxIgnoreNaN(double a, double b) { if (Double.isNaN(a)) { return b; } if (Double.isNaN(b)) { return a; } return Math.max(a, b); } /** * Updates the value of an item in the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param index the item (zero based index). * @param y the new value (<code>null</code> permitted). * * @since 1.0.1 */ public void updateByIndex(int index, Number y) { update(index, y); } /** * Updates an item in the series. * * @param x the x-value (<code>null</code> not permitted). * @param y the y-value (<code>null</code> permitted). * * @throws SeriesException if there is no existing item with the specified * x-value. */ public void update(Number x, Number y) { int index = indexOf(x); if (index < 0) { throw new SeriesException("No observation for x = " + x); } updateByIndex(index, y); } /** * Adds or updates an item in the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param x the x-value. * @param y the y-value. * * @return The item that was overwritten, if any. * * @since 1.0.10 */ public XYDataItem addOrUpdate(double x, double y) { return addOrUpdate(new Double(x), new Double(y)); } /** * Adds or updates an item in the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param x the x-value (<code>null</code> not permitted). * @param y the y-value (<code>null</code> permitted). * * @return A copy of the overwritten data item, or <code>null</code> if no * item was overwritten. */ public XYDataItem addOrUpdate(Number x, Number y) { // defer argument checking return addOrUpdate(new XYDataItem(x, y)); } /** * Adds or updates an item in the series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param item the data item (<code>null</code> not permitted). * * @return A copy of the overwritten data item, or <code>null</code> if no * item was overwritten. * * @since 1.0.14 */ public XYDataItem addOrUpdate(XYDataItem item) { ParamChecks.nullNotPermitted(item, "item"); if (this.allowDuplicateXValues) { add(item); return null; } // if we get to here, we know that duplicate X values are not permitted XYDataItem overwritten = null; int index = indexOf(item.getX()); if (index >= 0) { XYDataItem existing = (XYDataItem) this.data.get(index); overwritten = (XYDataItem) existing.clone(); // figure out if we need to iterate through all the y-values boolean iterate = false; double oldY = existing.getYValue(); if (!Double.isNaN(oldY)) { iterate = oldY <= this.minY || oldY >= this.maxY; } existing.setY(item.getY()); if (iterate) { findBoundsByIteration(); } else if (item.getY() != null) { double yy = item.getY().doubleValue(); this.minY = minIgnoreNaN(this.minY, yy); this.maxY = minIgnoreNaN(this.maxY, yy); } } else { // if the series is sorted, the negative index is a result from // Collections.binarySearch() and tells us where to insert the // new item...otherwise it will be just -1 and we should just // append the value to the list... item = (XYDataItem) item.clone(); if (this.autoSort) { this.data.add(-index - 1, item); } else { this.data.add(item); } updateBoundsForAddedItem(item); // check if this addition will exceed the maximum item count... if (getItemCount() > this.maximumItemCount) { XYDataItem removed = (XYDataItem) this.data.remove(0); updateBoundsForRemovedItem(removed); } } fireSeriesChanged(); return overwritten; } /** * Returns the index of the item with the specified x-value, or a negative * index if the series does not contain an item with that x-value. Be * aware that for an unsorted series, the index is found by iterating * through all items in the series. * * @param x the x-value (<code>null</code> not permitted). * * @return The index. */ public int indexOf(Number x) { if (this.autoSort) { return Collections.binarySearch(this.data, new XYDataItem(x, null)); } else { for (int i = 0; i < this.data.size(); i++) { XYDataItem item = (XYDataItem) this.data.get(i); if (item.getX().equals(x)) { return i; } } return -1; } } /** * Returns a new array containing the x and y values from this series. * * @return A new array containing the x and y values from this series. * * @since 1.0.4 */ public double[][] toArray() { int itemCount = getItemCount(); double[][] result = new double[2][itemCount]; for (int i = 0; i < itemCount; i++) { result[0][i] = this.getX(i).doubleValue(); Number y = getY(i); if (y != null) { result[1][i] = y.doubleValue(); } else { result[1][i] = Double.NaN; } } return result; } /** * Returns a clone of the series. * * @return A clone of the series. * * @throws CloneNotSupportedException if there is a cloning problem. */ public Object clone() throws CloneNotSupportedException { XYSeries clone = (XYSeries) super.clone(); clone.data = (List) ObjectUtilities.deepClone(this.data); return clone; } /** * Creates a new series by copying a subset of the data in this time series. * * @param start the index of the first item to copy. * @param end the index of the last item to copy. * * @return A series containing a copy of this series from start until end. * * @throws CloneNotSupportedException if there is a cloning problem. */ public XYSeries createCopy(int start, int end) throws CloneNotSupportedException { XYSeries copy = (XYSeries) super.clone(); copy.data = new java.util.ArrayList(); if (this.data.size() > 0) { for (int index = start; index <= end; index++) { XYDataItem item = (XYDataItem) this.data.get(index); XYDataItem clone = (XYDataItem) item.clone(); try { copy.add(clone); } catch (SeriesException e) { System.err.println("Unable to add cloned data item."); } } } return copy; } /** * Tests this series for equality with an arbitrary object. * * @param obj the object to test against for equality * (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYSeries)) { return false; } if (!super.equals(obj)) { return false; } XYSeries that = (XYSeries) obj; if (this.maximumItemCount != that.maximumItemCount) { return false; } if (this.autoSort != that.autoSort) { return false; } if (this.allowDuplicateXValues != that.allowDuplicateXValues) { return false; } if (!ObjectUtilities.equal(this.data, that.data)) { return false; } return true; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { int result = super.hashCode(); // it is too slow to look at every data item, so let's just look at // the first, middle and last items... int count = getItemCount(); if (count > 0) { XYDataItem item = getRawDataItem(0); result = 29 * result + item.hashCode(); } if (count > 1) { XYDataItem item = getRawDataItem(count - 1); result = 29 * result + item.hashCode(); } if (count > 2) { XYDataItem item = getRawDataItem(count / 2); result = 29 * result + item.hashCode(); } result = 29 * result + this.maximumItemCount; result = 29 * result + (this.autoSort ? 1 : 0); result = 29 * result + (this.allowDuplicateXValues ? 1 : 0); return result; } }
import java.io.*; import java.util.*; import macroutils.*; import macroutils.templates.*; import star.common.*; import star.flow.*; public class Demo14_GCI extends StarMacro { final double R = 25; //-- Pipe Radius in mm final double L = R / 2; //-- Pipe length in mm final double den = 1000.; //-- Density in kg/m^3 final double visc = 0.001; //-- Viscosity in Pa.s public void execute() { initMacro(); preRun(); solveGrids(); assessGCI(); mu.saveSim(); } public void assessGCI() { ud.starPlot = mu.get.plots.byREGEX(plotName, true); mu.templates.gci.evaluate(ud.starPlot, ud.files); } private void initMacro() { mu = new MacroUtils(getActiveSimulation()); ud = mu.userDeclarations; ud.simTitle = "Demo14_GCI"; } public void preRun() { ud.defCamView = mu.io.read.cameraView("cam1|-2.733933e-04,-2.870785e-04,2.535976e-03|9.205652e-02,1.539672e-02,1.080102e-01|1.614315e-02,9.868431e-01,-1.608729e-01|2.689607e-02|1", true); if (mu.check.has.volumeMesh()) { mu.io.say.loud("Volume Mesh Found. Skipping Prep"); return; } setupPhysics(); setupRegion(); setupMesh(); setupBCs(); setupPost(); } public void solveGrids() { int n = 1; ArrayList<Double> sizes = new ArrayList(); ArrayList<Double> dps = new ArrayList(); ArrayList<String> grids = new ArrayList(); mu.templates.prettify.all(); mu.set.solver.aggressiveSettings(); mu.open.allPlots(true); while (true) { double baseSize = baseSize0 / Math.pow(gridRefFactor, n - 1); mu.set.mesh.baseSize(ud.mshOp, baseSize, ud.defUnitLength, true); String gridN = String.format("Grid%03d", n); mu.io.say.loud(String.format("Solving %s for base size %g[%s].", gridN, baseSize, ud.defUnitLength.getPresentationName())); mu.update.volumeMesh(); mu.run(); mu.io.write.all(ud.simTitle + "_" + gridN); File f = new File(ud.simPath, String.format("%s_%s.sim", ud.simTitle, gridN)); mu.saveSim(f.toString()); ud.files.add(f); TemplateGCI gci = mu.templates.gci; sizes.add(gci.getGridSize()); dps.add(ud.rep1.getReportMonitorValue()); grids.add(mu.getSimulation().getPresentationName()); gci.evaluate(sizes, dps, grids); if (n >= maxGrids || mu.get.mesh.fvr().getCellCount() > maxGridSize) { mu.io.say.loud("Finishing run. Limits reached."); mu.io.say.value("Case", gridN, true, true); mu.io.say.cellCount(); break; } n++; mu.set.solver.maxIterations(mu.get.solver.iteration() + ud.maxIter, true); } } private void setupBCs() { MomentumUserSourceOption muso = ud.region.getConditions().get(MomentumUserSourceOption.class); muso.setSelected(MomentumUserSourceOption.Type.SPECIFIED); MomentumUserSource mus = ud.region.getValues().get(MomentumUserSource.class); mu.set.object.physicalQuantity(mus.getMethod(ConstantVectorProfileMethod.class).getQuantity(), "[0.0, 0.0, $dPdL]", "Momentum Source", true); ud.bdryIntrf = mu.add.intrf.boundaryInterface(mu.get.boundaries.byREGEX("z0", true), mu.get.boundaries.byREGEX("z1", true), InterfaceConfigurationOption.Type.PERIODIC); } private void setupPlotData(InternalDataSet ids, SymbolShapeOption.Type type, StaticDeclarations.Colors color) { ids.getSymbolStyle().getSymbolShapeOption().setSelected(type); ids.getSymbolStyle().setColor(color.getColor()); } private void setupMesh() { ud.mshBaseSize = baseSize0; ud.mshSrfSizeMin = 80; ud.prismsLayers = 3; ud.prismsRelSizeHeight = 40; ud.prismsNearCoreAspRat = 0.5; ud.mshOp = mu.add.meshOperation.directedMeshing_AutoMesh(mu.get.partSurfaces.byREGEX("z0", true), mu.get.partSurfaces.byREGEX("z1", true), 5, StaticDeclarations.Meshers.POLY_MESHER_2D, StaticDeclarations.Meshers.PRISM_LAYER_MESHER); ud.scene = mu.add.scene.mesh(); ud.scene.open(true); } private void setupPhysics() { ud.urfVel = 0.95; ud.urfP = 0.15; ud.maxIter = 3000; ud.physCont = mu.add.physicsContinua.generic(StaticDeclarations.Space.THREE_DIMENSIONAL, StaticDeclarations.Time.STEADY, StaticDeclarations.Material.LIQUID, StaticDeclarations.Solver.SEGREGATED, StaticDeclarations.Density.INCOMPRESSIBLE, StaticDeclarations.Energy.ISOTHERMAL, StaticDeclarations.Viscous.LAMINAR); mu.set.physics.materialProperty(ud.physCont, "H2O", StaticDeclarations.Vars.DEN, den, ud.unit_kgpm3); mu.set.physics.materialProperty(ud.physCont, "H2O", StaticDeclarations.Vars.VISC, visc, ud.unit_Pa_s); mu.set.physics.initialCondition(ud.physCont, StaticDeclarations.Vars.VEL.getVar(), new double[]{0, 0, 0.1}, ud.unit_mps); ud.ff1 = mu.add.tools.fieldFunction("r", "sqrt(pow($$Position[0], 2) + pow($$Position[1], 2))", ud.dimLength, FieldFunctionTypeOption.Type.SCALAR); ud.ff2 = mu.add.tools.fieldFunction("dPdL", "1", ud.dimDimensionless, FieldFunctionTypeOption.Type.SCALAR); ud.ff3 = mu.add.tools.fieldFunction("Analytical Solution", String.format("$dPdL / %g * (pow(%g, 2)-pow($r, 2))", 4 * visc, R / 1000.), ud.dimVel, FieldFunctionTypeOption.Type.SCALAR); } private void setupPost() { FieldFunction fx, fVz; fx = mu.get.objects.fieldFunction(StaticDeclarations.Vars.POS.getVar(), true).getComponentFunction(0); fVz = mu.get.objects.fieldFunction(StaticDeclarations.Vars.VEL.getVar(), true).getComponentFunction(2); ud.bdry = ud.bdryIntrf.getInterfaceBoundary0(); ud.rep1 = mu.add.report.massFlowAverage(ud.bdry, repMean, fVz, ud.defUnitVel, true); ud.rep2 = mu.add.report.maximum(ud.bdry, repMax, fVz, ud.defUnitVel, true); ud.mon = mu.get.monitors.byREGEX("Z-momentum", true); mu.add.solver.stoppingCriteria(ud.mon, StaticDeclarations.StopCriteria.MIN, 1e-6, 0); //-- Setup Plot ud.namedObjects.addAll(mu.get.regions.all(true)); ud.namedObjects2.add(mu.add.derivedPart.line(ud.namedObjects, new double[]{-0.98 * R, 0, L / 2}, new double[]{0.98 * R, 0, L / 2}, 20)); XYPlot plot = mu.add.plot.xy(ud.namedObjects2, fx, ud.defUnitLength, fVz, ud.defUnitVel); plot.setPresentationName(plotName); ud.updEvent = mu.add.tools.updateEvent_Iteration(100, 0); mu.set.object.updateEvent(plot, ud.updEvent, true); YAxisType yxN = plot.getYAxes().getDefaultAxis(); YAxisType yxA = plot.getYAxes().createAxisType(); InternalDataSet idsN = (InternalDataSet) yxN.getDataSetManager().getDataSets().iterator().next(); InternalDataSet idsA = (InternalDataSet) yxA.getDataSetManager().getDataSets().iterator().next(); setupPlotData(idsN, SymbolShapeOption.Type.EMPTY_CIRCLE, StaticDeclarations.Colors.BLACK); setupPlotData(idsA, SymbolShapeOption.Type.FILLED_TRIANGLE, StaticDeclarations.Colors.DARK_GREEN); yxA.getScalarFunction().setFieldFunction(ud.ff3); idsN.setSeriesName("Numerical"); idsA.setSeriesName("Analytical"); mu.set.object.plotAxesTitles(plot, String.format("Radius [%s]", ud.defUnitLength.getPresentationName()), String.format("Axial Velocity [%s]", ud.defUnitVel.getPresentationName()), true); } private void setupRegion() { ud.cadPrt = mu.add.geometry.cylinder3DCAD(R, L, StaticDeclarations.COORD0, ud.unit_mm, StaticDeclarations.Axis.Z); ud.geometryParts.add(ud.cadPrt); ud.region = mu.add.region.fromPart(ud.cadPrt, StaticDeclarations.BoundaryMode.ONE_FOR_EACH_PART_SURFACE, StaticDeclarations.InterfaceMode.CONTACT, StaticDeclarations.FeatureCurveMode.ONE_FOR_ALL, true); } private MacroUtils mu; private UserDeclarations ud; private final double baseSize0 = 5; //-- Initial Mesh Size in mm. private final double gridRefFactor = 2; //-- Refinement factor between grids. private final double gridSafetyFactor = 1.25; private final double maxGridSize = 1e7; private final int maxGrids = 3; private final String plotName = "Numerical vs Analytical Solutions"; private final String repMean = "Vmean"; private final String repMax = "Vmax"; }
package com.splicemachine.management; import org.spark_project.guava.collect.Sets; import com.splicemachine.EngineDriver; import com.splicemachine.access.api.DatabaseVersion; import com.splicemachine.derby.utils.DatabasePropertyManagementImpl; import com.splicemachine.pipeline.PipelineDriver; import com.splicemachine.utils.logging.LogManager; import com.splicemachine.utils.logging.Logging; import java.sql.SQLException; import java.util.*; public class DirectDatabaseAdministrator implements DatabaseAdministrator{ private final Logging logging = new LogManager(); @Override public void setLoggerLevel(String loggerName,String logLevel) throws SQLException{ logging.setLoggerLevel(loggerName,logLevel); } @Override public List<String> getLoggerLevel(String loggerName) throws SQLException{ return Collections.singletonList(logging.getLoggerLevel(loggerName)); } @Override public Set<String> getLoggers() throws SQLException{ return Sets.newHashSet(logging.getLoggerNames()); } @Override public Map<String, DatabaseVersion> getClusterDatabaseVersions() throws SQLException{ return Collections.singletonMap("mem",EngineDriver.driver().getVersion()); } @Override public Map<String,Map<String,String>> getDatabaseVersionInfo() throws SQLException{ DatabaseVersion databaseVersion = EngineDriver.driver().getVersion(); Map<String,String> attrs = new HashMap<>(); attrs.put("release", databaseVersion.getRelease()); attrs.put("implementationVersion", databaseVersion.getImplementationVersion()); attrs.put("buildTime", databaseVersion.getBuildTime()); attrs.put("url", databaseVersion.getURL()); return Collections.singletonMap("mem",attrs); } @Override public void setWritePoolMaxThreadCount(int maxThreadCount) throws SQLException{ PipelineDriver.driver().writeCoordinator().setMaxAsyncThreads(maxThreadCount); } @Override public Map<String, Integer> getWritePoolMaxThreadCount() throws SQLException{ return Collections.singletonMap("mem",PipelineDriver.driver().writeCoordinator().getMaxAsyncThreads()); } @Override public String getDatabaseProperty(String key) throws SQLException{ return DatabasePropertyManagementImpl.instance().getDatabaseProperty(key); } @Override public void setGlobalDatabaseProperty(String key,String value) throws SQLException{ DatabasePropertyManagementImpl.instance().setDatabaseProperty(key,value); } @Override public void emptyGlobalStatementCache() throws SQLException{ //TODO -sf- no-op for now --eventually may need to implement } }
package com.ettrema.http.caldav.demo; import com.bradmcevoy.common.Path; import com.bradmcevoy.http.Resource; import com.bradmcevoy.http.ResourceFactory; public class TResourceFactory implements ResourceFactory { private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger( TResourceFactory.class ); public static final TFolderResource ROOT = new TFolderResource( (TFolderResource) null, "http://localhost:9080" ); static { TFolderResource folder = new TFolderResource( ROOT, "folder1" ); TFolderResource principals = new TFolderResource( ROOT, "principals" ); TCalendarResource cal1 = new TCalendarResource( folder, "calenderOne" ); } public Resource getResource( String host, String url ) { log.debug( "getResource: url: " + url ); Path path = Path.path( url ); Resource r = find( path ); log.debug( "_found: " + r ); return r; } private Resource find( Path path ) { if( isRoot( path ) ) return ROOT; Resource r = find( path.getParent() ); if( r == null ) return null; if( r instanceof TFolderResource ) { TFolderResource folder = (TFolderResource) r; for( Resource rChild : folder.getChildren() ) { Resource r2 = (Resource) rChild; if( r2.getName().equals( path.getName() ) ) { return r2; } else { // log.debug( "IS NOT: " + r2.getName() + " - " + path.getName()); } } } log.debug( "not found: " + path ); return null; } private boolean isRoot( Path path ) { if( path == null ) return true; return ( path.getParent() == null || path.getParent().isRoot() ); } }
package ai.susi.server.api.cms; import ai.susi.DAO; import org.json.JSONObject; import ai.susi.json.JsonObjectWithDefault; import ai.susi.server.APIHandler; import ai.susi.server.AbstractAPIHandler; import ai.susi.server.Authorization; import ai.susi.server.BaseUserRole; import ai.susi.server.Query; import ai.susi.server.ServiceResponse; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class GetSkillJsonService extends AbstractAPIHandler implements APIHandler { private static final long serialVersionUID = 18344223L; @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { return null; } @Override public String getAPIPath() { return "/cms/getSkill.json"; } @Override public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights, final JsonObjectWithDefault permissions) { JSONObject json = new JSONObject(true); // modify caching json.put("$EXPIRES", 0); String model_name = call.get("model", "general"); File model = new File(DAO.model_watch_dir, model_name); String group_name = call.get("group", "knowledge"); File group = new File(model, group_name); String language_name = call.get("language", "en"); File language = new File(group, language_name); String skill_name = call.get("skill", "wikipedia"); File skill = new File(language, skill_name + ".txt"); try { String content = new String(Files.readAllBytes(skill.toPath())); json.put("text",content); json.put("accepted",true); return new ServiceResponse(json); } catch (IOException e) { e.printStackTrace(); } return null; } }
package org.vaadin.mockapp.samples.authentication; import java.io.Serializable; import com.vaadin.event.ShortcutAction; import com.vaadin.server.Page; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.PasswordField; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; /** * UI content when the user is not logged in yet. */ public class LoginScreen extends CssLayout { private TextField username; private PasswordField password; private Button login; private Button forgotPassword; private LoginListener loginListener; private AccessControl accessControl; public LoginScreen(AccessControl accessControl, LoginListener loginListener) { this.loginListener = loginListener; this.accessControl = accessControl; buildUI(); username.focus(); } private void buildUI() { addStyleName("login-screen"); // login form, centered in the available part of the screen Component loginForm = buildLoginForm(); // layout to center login form when there is sufficient screen space // - see the theme for how this is made responsive for various screen // sizes VerticalLayout centeringLayout = new VerticalLayout(); centeringLayout.setStyleName("centering-layout"); centeringLayout.addComponent(loginForm); centeringLayout.setComponentAlignment(loginForm, Alignment.MIDDLE_CENTER); // information text about logging in CssLayout loginInformation = buildLoginInformation(); addComponent(centeringLayout); addComponent(loginInformation); } private Component buildLoginForm() { FormLayout loginForm = new FormLayout(); loginForm.addStyleName("login-form"); loginForm.setSizeUndefined(); loginForm.setMargin(false); loginForm.addComponent(username = new TextField("Username", "admin")); username.setWidth(15, Unit.EM); loginForm.addComponent(password = new PasswordField("Password")); password.setWidth(15, Unit.EM); password.setDescription("Write anything"); CssLayout buttons = new CssLayout(); buttons.setStyleName("buttons"); loginForm.addComponent(buttons); buttons.addComponent(login = new Button("Login")); login.setDisableOnClick(true); login.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { try { login(); } finally { login.setEnabled(true); } } }); login.setClickShortcut(ShortcutAction.KeyCode.ENTER); login.addStyleName(ValoTheme.BUTTON_FRIENDLY); buttons.addComponent(forgotPassword = new Button("Forgot password?")); forgotPassword.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { showNotification(new Notification("Hint: Try anything")); } }); forgotPassword.addStyleName(ValoTheme.BUTTON_LINK); return loginForm; } private CssLayout buildLoginInformation() { CssLayout loginInformation = new CssLayout(); loginInformation.setStyleName("login-information"); Label loginInfoText = new Label( "<h1>Login Information</h1>" + "Log in as &quot;admin&quot; to have full access. Log in with any other username to have read-only access. For all users, any password is fine", ContentMode.HTML); loginInformation.addComponent(loginInfoText); return loginInformation; } private void login() { if (accessControl.signIn(username.getValue(), password.getValue())) { loginListener.loginSuccessful(); } else { showNotification(new Notification("Login failed", "Please check your username and password and try again.", Notification.Type.HUMANIZED_MESSAGE)); username.focus(); } } private void showNotification(Notification notification) { // keep the notification visible a little while after moving the // mouse, or until clicked notification.setDelayMsec(2000); notification.show(Page.getCurrent()); } public interface LoginListener extends Serializable { void loginSuccessful(); } }
package com.haulmont.cuba.desktop.gui.components; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.cuba.core.global.AppBeans; import com.haulmont.cuba.core.global.MessageTools; import com.haulmont.cuba.core.global.MetadataTools; import com.haulmont.cuba.core.global.Security; import com.haulmont.cuba.desktop.sys.DesktopToolTipManager; import com.haulmont.cuba.desktop.sys.layout.LayoutAdapter; import com.haulmont.cuba.desktop.sys.layout.MigLayoutHelper; import com.haulmont.cuba.desktop.sys.vcl.CollapsiblePanel; import com.haulmont.cuba.desktop.sys.vcl.ToolTipButton; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.DsContext; import net.miginfocom.layout.CC; import net.miginfocom.layout.LC; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang.StringUtils; import org.dom4j.Element; import javax.swing.*; import java.util.*; /** * @author krivopustov * @version $Id$ */ public class DesktopFieldGroup extends DesktopAbstractComponent<JPanel> implements FieldGroup, AutoExpanding { protected MigLayout layout; protected Datasource datasource; protected int rows; protected int cols = 1; protected boolean editable = true; protected boolean enabled = true; protected boolean borderVisible = false; protected Map<String, FieldConfig> fields = new LinkedHashMap<>(); protected Map<FieldConfig, Integer> fieldsColumn = new HashMap<>(); protected Map<FieldConfig, Component> fieldComponents = new HashMap<>(); protected Map<FieldConfig, JLabel> fieldLabels = new HashMap<>(); protected Map<FieldConfig, ToolTipButton> fieldTooltips = new HashMap<>(); protected Map<Integer, List<FieldConfig>> columnFields = new HashMap<>(); protected Map<FieldConfig, CustomFieldGenerator> generators = new HashMap<>(); protected AbstractFieldFactory fieldFactory = new FieldFactory(); protected Set<FieldConfig> readOnlyFields = new HashSet<>(); protected Set<FieldConfig> disabledFields = new HashSet<>(); protected CollapsiblePanel collapsiblePanel; protected Security security = AppBeans.get(Security.NAME); public DesktopFieldGroup() { LC lc = new LC(); lc.hideMode(3); // Invisible components will not participate in the layout at all and it will for instance not take up a grid cell. lc.insets("0 0 0 0"); if (LayoutAdapter.isDebug()) { lc.debug(1000); } layout = new MigLayout(lc); impl = new JPanel(layout); assignClassDebugProperty(impl); collapsiblePanel = new CollapsiblePanel(super.getComposition()); assignClassDebugProperty(collapsiblePanel); collapsiblePanel.setBorderVisible(false); } @Override public List<FieldConfig> getFields() { return new ArrayList<>(fields.values()); } @Override public FieldConfig getField(String id) { for (final Map.Entry<String, FieldConfig> entry : fields.entrySet()) { if (entry.getKey().equals(id)) { return entry.getValue(); } } return null; } private void fillColumnFields(int col, FieldConfig field) { List<FieldConfig> fields = columnFields.get(col); if (fields == null) { fields = new ArrayList<>(); columnFields.put(col, fields); } fields.add(field); } @Override public void addField(FieldConfig field) { if (cols == 0) { cols = 1; } addField(field, 0); } @Override public void addField(FieldConfig field, int col) { if (col < 0 || col >= cols) { throw new IllegalStateException(String.format("Illegal column number %s, available amount of columns is %s", col, cols)); } fields.put(field.getId(), field); fieldsColumn.put(field, col); fillColumnFields(col, field); } @Override public void removeField(FieldConfig field) { if (fields.remove(field.getId()) != null) { Integer col = fieldsColumn.get(field.getId()); final List<FieldConfig> fields = columnFields.get(col); fields.remove(field); fieldsColumn.remove(field.getId()); } } @Override public void requestFocus() { SwingUtilities.invokeLater(new Runnable() { public void run() { if (!columnFields.isEmpty()) { List<FieldConfig> fields = columnFields.get(0); if (!fields.isEmpty()) { FieldConfig f = fields.get(0); Component c = fieldComponents.get(f); if (c != null) { c.requestFocus(); } } } } }); } @Override public Datasource getDatasource() { return datasource; } @Override public void setDatasource(Datasource datasource) { this.datasource = datasource; if (this.fields.isEmpty() && datasource != null) { //collect fields by entity view MetadataTools metadataTools = AppBeans.get(MetadataTools.class); Collection<MetaPropertyPath> fieldsMetaProps = metadataTools.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass()); for (MetaPropertyPath mpp : fieldsMetaProps) { MetaProperty mp = mpp.getMetaProperty(); if (!mp.getRange().getCardinality().isMany() && !metadataTools.isSystem(mp)) { FieldConfig field = new FieldConfig(mpp.toString()); addField(field); } } } rows = rowsCount(); createFields(); } @Override public boolean isRequired(FieldConfig field) { Component component = fieldComponents.get(field); return component instanceof com.haulmont.cuba.gui.components.Field && ((com.haulmont.cuba.gui.components.Field) component).isRequired(); } @Override public void setRequired(FieldConfig field, boolean required, String message) { Component component = fieldComponents.get(field); if (component instanceof Field) { ((Field) component).setRequired(required); ((Field) component).setRequiredMessage(message); } } @Override public boolean isRequired(String fieldId) { FieldConfig field = fields.get(fieldId); return field != null && isRequired(field); } @Override public void setRequired(String fieldId, boolean required, String message) { FieldConfig field = fields.get(fieldId); if (field != null) { setRequired(field, required, message); } } @Override public void addValidator(FieldConfig field, Field.Validator validator) { Component component = fieldComponents.get(field); if (component instanceof Field) { ((Field) component).addValidator(validator); } } @Override public void addValidator(String fieldId, Field.Validator validator) { FieldConfig field = fields.get(fieldId); if (fieldId != null) { addValidator(field, validator); } } @Override public boolean isEditable(FieldConfig field) { return !readOnlyFields.contains(field); } @Override public void setEditable(FieldConfig field, boolean editable) { doSetEditable(field, editable); if (editable) { readOnlyFields.remove(field); } else { readOnlyFields.add(field); } } protected void doSetEditable(FieldConfig field, boolean editable) { Component component = fieldComponents.get(field); if (component instanceof Editable) { ((Editable) component).setEditable(editable); } if (fieldLabels.containsKey(field)) { fieldLabels.get(field).setEnabled(editable); } } @Override public boolean isEditable(String fieldId) { FieldConfig field = fields.get(fieldId); return field != null && isEditable(field); } @Override public void setEditable(String fieldId, boolean editable) { FieldConfig field = fields.get(fieldId); if (field != null) { setEditable(field, editable); } } @Override public boolean isEnabled(FieldConfig field) { Component component = fieldComponents.get(field); return component != null && component.isEnabled(); } @Override public void setEnabled(FieldConfig field, boolean enabled) { doSetEnabled(field, enabled); if (enabled) { disabledFields.remove(field); } else { disabledFields.add(field); } } protected void doSetEnabled(FieldConfig field, boolean enabled) { Component component = fieldComponents.get(field); if (component != null) { component.setEnabled(enabled); } if (fieldLabels.containsKey(field)) { fieldLabels.get(field).setEnabled(enabled); } } @Override public boolean isEnabled(String fieldId) { FieldConfig field = fields.get(fieldId); return field != null && isEnabled(field); } @Override public void setEnabled(String fieldId, boolean enabled) { FieldConfig field = fields.get(fieldId); if (field != null) { setEnabled(field, enabled); } } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; for (FieldConfig field : fields.values()) { doSetEnabled(field, enabled && !disabledFields.contains(field)); } } @Override public boolean isEnabled() { return enabled; } @Override public boolean isVisible(FieldConfig field) { Component component = fieldComponents.get(field); return component != null && component.isVisible() && isVisible(); } @Override public void setVisible(FieldConfig field, boolean visible) { Component component = fieldComponents.get(field); if (component != null) { component.setVisible(visible); } if (fieldLabels.containsKey(field)) { fieldLabels.get(field).setVisible(visible); } } @Override public boolean isVisible(String fieldId) { FieldConfig field = fields.get(fieldId); return field != null && isVisible(field); } @Override public void setVisible(String fieldId, boolean visible) { FieldConfig field = fields.get(fieldId); if (field != null) { setVisible(field, visible); } } @Override public boolean isBorderVisible() { return borderVisible; } @Override public void setBorderVisible(boolean borderVisible) { this.borderVisible = borderVisible; collapsiblePanel.setBorderVisible(borderVisible); } @Override public Object getFieldValue(FieldConfig field) { Component component = fieldComponents.get(field); if (component instanceof HasValue) { return ((HasValue) component).getValue(); } return null; } @Override public void setFieldValue(FieldConfig field, Object value) { Component component = fieldComponents.get(field); if (component instanceof HasValue) { ((HasValue) component).setValue(value); } } @Override public Object getFieldValue(String fieldId) { FieldConfig field = getField(fieldId); if (field == null) { throw new IllegalArgumentException(String.format("Field '%s' doesn't exist", fieldId)); } return getFieldValue(field); } @Override public void setFieldValue(String fieldId, Object value) { FieldConfig field = getField(fieldId); if (field == null) { throw new IllegalArgumentException(String.format("Field '%s' doesn't exist", fieldId)); } setFieldValue(field, value); } @Override public void requestFocus(String fieldId) { FieldConfig field = getField(fieldId); if (field == null) { throw new IllegalArgumentException(String.format("Field '%s' doesn't exist", fieldId)); } final Component fieldComponent = fieldComponents.get(field); if (fieldComponent != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { fieldComponent.requestFocus(); } }); } } @Override public void setFieldCaption(String fieldId, String caption) { FieldConfig field = getField(fieldId); if (field == null) { throw new IllegalArgumentException(String.format("Field '%s' doesn't exist", fieldId)); } JLabel label = fieldLabels.get(field); if (label == null) { throw new IllegalStateException(String.format("Label for field '%s' not found", fieldId)); } label.setText(caption); } @Override public void setCaptionAlignment(FieldCaptionAlignment captionAlignment) { } protected int rowsCount() { int rowsCount = 0; for (final List<FieldConfig> fields : columnFields.values()) { rowsCount = Math.max(rowsCount, fields.size()); } return rowsCount; } @Override public int getColumns() { return cols; } @Override public void setColumns(int cols) { this.cols = cols; } @Override public float getColumnExpandRatio(int col) { return 0; } @Override public void setColumnExpandRatio(int col, float ratio) { } @Override public void addCustomField(String fieldId, CustomFieldGenerator fieldGenerator) { FieldConfig field = getField(fieldId); if (field == null) { throw new IllegalArgumentException(String.format("Field '%s' doesn't exist", fieldId)); } addCustomField(field, fieldGenerator); } @Override public void addCustomField(FieldConfig field, CustomFieldGenerator fieldGenerator) { if (!field.isCustom()) { throw new IllegalStateException(String.format("Field '%s' must be custom", field.getId())); } generators.put(field, fieldGenerator); // immediately create field, even before postInit() createFieldComponent(field); } @Override public void postInit() { } protected void createFields() { impl.removeAll(); for (FieldConfig field : fields.values()) { if (field.isCustom()) { continue; // custom field is generated in another method } createFieldComponent(field); } } protected void createFieldComponent(FieldConfig fieldConf) { int col = fieldsColumn.get(fieldConf); int row = columnFields.get(col).indexOf(fieldConf); Datasource ds; if (fieldConf.getDatasource() != null) { ds = fieldConf.getDatasource(); } else { ds = datasource; } String caption = null; String description = null; CustomFieldGenerator generator = generators.get(fieldConf); if (generator == null) { generator = createDefaultGenerator(fieldConf); } Component fieldComponent = generator.generateField(ds, fieldConf.getId()); if (fieldComponent instanceof Field) { // do not create caption for buttons etc. Field cubaField = (Field) fieldComponent; caption = fieldConf.getCaption(); if (caption == null) { MetaPropertyPath propertyPath = ds.getMetaClass().getPropertyPath(fieldConf.getId()); if (propertyPath != null) { caption = AppBeans.get(MessageTools.class).getPropertyCaption(propertyPath.getMetaClass(), fieldConf.getId()); } } if (StringUtils.isNotEmpty(cubaField.getCaption())) { caption = cubaField.getCaption(); // custom field has manually set caption } description = fieldConf.getDescription(); if (StringUtils.isNotEmpty(cubaField.getDescription())) { description = cubaField.getDescription(); // custom field has manually set description } else if (StringUtils.isNotEmpty(description)) { cubaField.setDescription(description); } if (!cubaField.isRequired()) { cubaField.setRequired(fieldConf.isRequired()); } if (fieldConf.getRequiredError() != null) { cubaField.setRequiredMessage(fieldConf.getRequiredError()); } } if (fieldComponent instanceof HasFormatter) { ((HasFormatter) fieldComponent).setFormatter(fieldConf.getFormatter()); } // some components (e.g. LookupPickerField) have width from the creation, so I commented out this check if (/*f.getWidth() == -1f &&*/ fieldConf.getWidth() != null) { fieldComponent.setWidth(fieldConf.getWidth()); } applyPermissions(fieldComponent); JLabel label = new JLabel(caption); label.setVisible(fieldComponent.isVisible()); CC labelCc = new CC(); MigLayoutHelper.applyAlignment(labelCc, Alignment.MIDDLE_LEFT); impl.add(label, labelCc.cell(col * 3, row, 1, 1)); fieldLabels.put(fieldConf, label); if (description != null && !(fieldComponent instanceof CheckBox)) { fieldConf.setDescription(description); ToolTipButton tooltipBtn = new ToolTipButton(); tooltipBtn.setVisible(fieldComponent.isVisible()); tooltipBtn.setToolTipText(description); DesktopToolTipManager.getInstance().registerTooltip(tooltipBtn); impl.add(tooltipBtn, new CC().cell(col * 3 + 2, row, 1, 1).alignY("top")); fieldTooltips.put(fieldConf, tooltipBtn); } fieldComponents.put(fieldConf, fieldComponent); assignTypicalAttributes(fieldComponent); JComponent jComponent = DesktopComponentsHelper.getComposition(fieldComponent); CC cell = new CC().cell(col * 3 + 1, row, 1, 1); MigLayoutHelper.applyWidth(cell, (int) fieldComponent.getWidth(), fieldComponent.getWidthUnits(), false); MigLayoutHelper.applyHeight(cell, (int) fieldComponent.getHeight(), fieldComponent.getHeightUnits(), false); MigLayoutHelper.applyAlignment(cell, fieldComponent.getAlignment()); jComponent.putClientProperty(getSwingPropertyId(), fieldConf.getId()); impl.add(jComponent, cell); } protected void applyPermissions(Component c) { if (c instanceof DatasourceComponent) { DatasourceComponent dsComponent = (DatasourceComponent) c; MetaProperty metaProperty = dsComponent.getMetaProperty(); if (metaProperty != null) { dsComponent.setEditable(security.isEntityAttrModificationPermitted(metaProperty) && dsComponent.isEditable()); } } } protected void assignTypicalAttributes(Component c) { if (c instanceof BelongToFrame) { BelongToFrame belongToFrame = (BelongToFrame) c; if (belongToFrame.getFrame() == null) { belongToFrame.setFrame(getFrame()); } } } protected CustomFieldGenerator createDefaultGenerator(final FieldConfig field) { return new CustomFieldGenerator() { @Override public Component generateField(Datasource datasource, String propertyId) { Component component = fieldFactory.createField(datasource, propertyId, field.getXmlDescriptor()); if (component instanceof HasFormatter) { ((HasFormatter) component).setFormatter(field.getFormatter()); } return component; } }; } @Override public boolean isEditable() { return editable; } @Override public void setEditable(boolean editable) { this.editable = editable; for (FieldConfig field : fields.values()) { doSetEditable(field, editable && !readOnlyFields.contains(field)); } } @Override public String getCaption() { return collapsiblePanel.getCaption(); } @Override public void setCaption(String caption) { collapsiblePanel.setCaption(caption); } @Override public String getDescription() { return null; } @Override public void setDescription(String description) { } public Collection<Component> getComponents() { return fieldComponents.values(); } @Override public JComponent getComposition() { return collapsiblePanel; } @Override public boolean expandsWidth() { return true; } @Override public boolean expandsHeight() { return false; } @Override public boolean isValid() { try { validate(); return true; } catch (ValidationException e) { return false; } } @Override public void validate() throws ValidationException { if (!isVisible() || !isEditable() || !isEnabled()) { return; } Map<FieldConfig, Exception> problems = new HashMap<>(); for (Map.Entry<FieldConfig, Component> componentEntry : fieldComponents.entrySet()) { FieldConfig field = componentEntry.getKey(); Component component = componentEntry.getValue(); if (!isEditable(field) || !isEnabled(field) || !isVisible(field)) { continue; } // If has valid state if ((component instanceof Validatable) && (component instanceof Editable)) { // If editable if (component.isVisible() && component.isEnabled() && ((Editable) component).isEditable()) { try { ((Validatable) component).validate(); } catch (ValidationException ex) { problems.put(field, ex); } } } } if (!problems.isEmpty()) { StringBuilder msgBuilder = new StringBuilder(); for (Iterator<FieldConfig> iterator = problems.keySet().iterator(); iterator.hasNext(); ) { FieldConfig field = iterator.next(); Exception ex = problems.get(field); msgBuilder.append(ex.getMessage()); if (iterator.hasNext()) { msgBuilder.append("<br>"); } } FieldsValidationException validationException = new FieldsValidationException(msgBuilder.toString()); validationException.setProblemFields(problems); throw validationException; } } protected class FieldFactory extends AbstractFieldFactory { @Override protected CollectionDatasource getOptionsDatasource(Datasource datasource, String property) { final FieldConfig field = fields.get(property); DsContext dsContext; if (datasource == null) { if (field.getDatasource() == null) { throw new IllegalStateException("FieldGroup datasource is null"); } dsContext = field.getDatasource().getDsContext(); } else { dsContext = datasource.getDsContext(); } Element descriptor = field.getXmlDescriptor(); String optDsName = descriptor == null ? null : descriptor.attributeValue("optionsDatasource"); if (!StringUtils.isBlank(optDsName)) { CollectionDatasource optDs = dsContext.get(optDsName); if (optDs == null) { throw new IllegalStateException("Options datasource not found: " + optDsName); } return optDs; } else { return null; } } } }
package org.laladev.moneyjinn.server.jwt; import javax.inject.Inject; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Inject JwtTokenProvider jwtTokenProvider; @Bean public AuthenticationManager authenticationManager(final AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain securityFilterChain(final HttpSecurity http) throws Exception { //@formatter:off http .httpBasic().disable() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests()
package at.ac.tuwien.dsg.myx.monitor.comp; import java.util.Collection; import java.util.Iterator; import at.ac.tuwien.dsg.myx.monitor.MyxProperties; import at.ac.tuwien.dsg.myx.monitor.aim.ArchitectureInstantiationException; import at.ac.tuwien.dsg.myx.monitor.aim.Launcher; import at.ac.tuwien.dsg.myx.monitor.model.ModelRoot; import at.ac.tuwien.dsg.myx.util.DBLUtils; import at.ac.tuwien.dsg.myx.util.MyxUtils; import edu.uci.isr.myx.fw.AbstractMyxSimpleBrick; import edu.uci.isr.myx.fw.IMyxName; import edu.uci.isr.xarch.types.IArchStructure; public class BootstrapComponent extends AbstractMyxSimpleBrick { public static final IMyxName INTERFACE_NAME_OUT_LAUNCHER = MyxUtils.createName("launcher"); public static final IMyxName INTERFACE_NAME_OUT_MODELROOT = MyxUtils.createName("model-root"); public static final String ARCHITECTURE_NAME = "main"; protected Launcher launcher = null; protected ModelRoot modelRoot = null; @Override public Object getServiceObject(IMyxName interfaceName) { return null; } @Override public void begin() { launcher = MyxUtils.getFirstRequiredServiceObject(this, INTERFACE_NAME_OUT_LAUNCHER); modelRoot = MyxUtils.getFirstRequiredServiceObject(this, INTERFACE_NAME_OUT_MODELROOT); // structure to be instantiated IArchStructure archStructure = null; // extract arch structures Collection<IArchStructure> archStructures = DBLUtils.getArchStructures(modelRoot.getArchitectureRoot()); // which archstructe should be instantiated? String structureDescription = MyxUtils.getInitProperties(this).getProperty(MyxProperties.STRUCTURE_NAME); if (structureDescription != null) { // extract a certain archstructure for (IArchStructure as : archStructures) { if (as.getDescription() != null && as.getDescription().getValue().equals(structureDescription)) { archStructure = as; break; } } } else { // use the first one if we got one Iterator<IArchStructure> it = archStructures.iterator(); if (it.hasNext()) { archStructure = it.next(); } } if (archStructure == null) { throw new RuntimeException("No suitable structure found!"); } try { launcher.instantiate(ARCHITECTURE_NAME, archStructure); } catch (ArchitectureInstantiationException e) { System.err.println("Architecture could not be instantiated! See error below:"); e.printStackTrace(); System.exit(-1); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.lessvoid.nifty.controls.treebox; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.AbstractController; import de.lessvoid.nifty.controls.ListBox; import de.lessvoid.nifty.controls.TreeBox; import de.lessvoid.nifty.controls.TreeItem; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.xml.xpp3.Attributes; import java.util.Properties; /** * * @author ractoc */ public class TreeBoxControl extends AbstractController implements TreeBox { private int indentWidth = 15; private TreeItem tree; @Override public void bind(Nifty nifty, Screen screen, Element element, Properties parameter, Attributes controlDefinitionAttributes) { super.bind(element); System.out.println("binding the treebox"); if (tree != null) { System.out.println("tree items found"); ListBox<TreeEntryModelClass> treeListBox = getListBox("#listbox"); addTreeItem(treeListBox, tree, 0); } else { System.out.println("no tree items found"); } ListBox<TreeEntryModelClass> treeListBox = getListBox("#listbox"); if (treeListBox != null) { System.out.println("tree listbox found"); } else { System.out.println("no tree listbox found"); } } @Override public void onStartScreen() { } @Override public boolean inputEvent(NiftyInputEvent inputEvent) { return true; } @Override public void setTree(TreeItem treeRoot) { this.tree = treeRoot; ListBox<TreeEntryModelClass> treeListBox = getListBox("#listbox"); if (treeListBox != null) { System.out.println("tree listbox found"); addTreeItem(treeListBox, tree, 0); getElement().layoutElements(); } else { System.out.println("no tree listbox found"); } } @SuppressWarnings("unchecked") private ListBox<TreeEntryModelClass> getListBox(final String name) { return (ListBox<TreeEntryModelClass>) getElement().findNiftyControl(name, ListBox.class); } private void addTreeItem(ListBox<TreeEntryModelClass> treeListBox, TreeItem treeItem, int currentIndent) { if (currentIndent != 0) { System.out.println("adding tree item " + treeItem.getDisplayCaption() + " with indent " + indentWidth * currentIndent); treeListBox.addItem(new TreeEntryModelClass(indentWidth * currentIndent, treeItem)); } if (treeItem.isExpanded()) { for (Object childItem : treeItem.getTreeItems()) { addTreeItem(treeListBox, (TreeItem) childItem, currentIndent + 1); } } } }
package com.esotericsoftware.reflectasm; import junit.framework.TestCase; public class FieldAccessTest extends TestCase { public void testNameSetAndGet () { FieldAccess access = FieldAccess.get(SomeClass.class); SomeClass someObject = new SomeClass(); assertEquals(null, someObject.name); access.set(someObject, "name", "first"); assertEquals("first", someObject.name); assertEquals("first", access.get(someObject, "name")); assertEquals(0, someObject.intValue); access.set(someObject, "intValue", 1234); assertEquals(1234, someObject.intValue); assertEquals(1234, access.get(someObject, "intValue")); } public void testIndexSetAndGet () { FieldAccess access = FieldAccess.get(SomeClass.class); SomeClass someObject = new SomeClass(); int index; assertEquals(null, someObject.name); index = access.getIndex("name"); access.set(someObject, index, "first"); assertEquals("first", someObject.name); assertEquals("first", access.get(someObject, index)); index = access.getIndex("intValue"); assertEquals(0, someObject.intValue); access.set(someObject, index, 1234); assertEquals(1234, someObject.intValue); assertEquals(1234, access.get(someObject, index)); } static public class SomeClass { public String name; public int intValue; protected float test1; Float test2; private String test3; } }
package com.yahoo.vespa.orchestrator.resources; import com.google.common.util.concurrent.UncheckedTimeoutException; import com.yahoo.container.jaxrs.annotation.Component; import com.yahoo.log.LogLevel; import com.yahoo.vespa.applicationmodel.HostName; import com.yahoo.vespa.orchestrator.Host; import com.yahoo.vespa.orchestrator.HostNameNotFoundException; import com.yahoo.vespa.orchestrator.OrchestrationException; import com.yahoo.vespa.orchestrator.Orchestrator; import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException; import com.yahoo.vespa.orchestrator.policy.HostedVespaPolicy; import com.yahoo.vespa.orchestrator.restapi.HostApi; import com.yahoo.vespa.orchestrator.restapi.wire.GetHostResponse; import com.yahoo.vespa.orchestrator.restapi.wire.HostService; import com.yahoo.vespa.orchestrator.restapi.wire.HostStateChangeDenialReason; import com.yahoo.vespa.orchestrator.restapi.wire.PatchHostRequest; import com.yahoo.vespa.orchestrator.restapi.wire.PatchHostResponse; import com.yahoo.vespa.orchestrator.restapi.wire.UpdateHostResponse; import com.yahoo.vespa.orchestrator.status.HostStatus; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.time.Instant; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author oyving */ @Path(HostApi.PATH_PREFIX) public class HostResource implements HostApi { private static final Logger log = Logger.getLogger(HostResource.class.getName()); private final Orchestrator orchestrator; private final UriInfo uriInfo; @Inject public HostResource(@Component Orchestrator orchestrator, @Context UriInfo uriInfo) { this.orchestrator = orchestrator; this.uriInfo = uriInfo; } @Override public GetHostResponse getHost(String hostNameString) { HostName hostName = new HostName(hostNameString); try { Host host = orchestrator.getHost(hostName); URI applicationUri = uriInfo.getBaseUriBuilder() .path(InstanceResource.class) .path(host.getApplicationInstanceReference().asString()) .build(); List<HostService> hostServices = host.getServiceInstances().stream() .map(serviceInstance -> new HostService( serviceInstance.getServiceCluster().clusterId().s(), serviceInstance.getServiceCluster().serviceType().s(), serviceInstance.configId().s(), serviceInstance.serviceStatus().name())) .collect(Collectors.toList()); return new GetHostResponse( host.getHostName().s(), host.getHostInfo().status().name(), host.getHostInfo().suspendedSince().map(Instant::toString).orElse(null), applicationUri.toString(), hostServices); } catch (UncheckedTimeoutException e) { log.log(LogLevel.DEBUG, "Failed to get host " + hostName + ": " + e.getMessage()); throw webExceptionFromTimeout("getHost", hostName, e); } catch (HostNameNotFoundException e) { log.log(LogLevel.DEBUG, "Host not found: " + hostName); throw new NotFoundException(e); } } @Override public PatchHostResponse patch(String hostNameString, PatchHostRequest request) { HostName hostName = new HostName(hostNameString); if (request.state != null) { HostStatus state; try { state = HostStatus.valueOf(request.state); } catch (IllegalArgumentException dummy) { throw new BadRequestException("Bad state in request: '" + request.state + "'"); } try { orchestrator.setNodeStatus(hostName, state); } catch (HostNameNotFoundException e) { log.log(LogLevel.DEBUG, "Host not found: " + hostName); throw new NotFoundException(e); } catch (UncheckedTimeoutException e) { log.log(LogLevel.DEBUG, "Failed to patch " + hostName + ": " + e.getMessage()); throw webExceptionFromTimeout("patch", hostName, e); } catch (OrchestrationException e) { String message = "Failed to set " + hostName + " to " + state + ": " + e.getMessage(); log.log(LogLevel.DEBUG, message, e); throw new InternalServerErrorException(message); } } PatchHostResponse response = new PatchHostResponse(); response.description = "ok"; return response; } @Override public UpdateHostResponse suspend(String hostNameString) { HostName hostName = new HostName(hostNameString); try { orchestrator.suspend(hostName); } catch (HostNameNotFoundException e) { log.log(LogLevel.DEBUG, "Host not found: " + hostName); throw new NotFoundException(e); } catch (UncheckedTimeoutException e) { log.log(LogLevel.DEBUG, "Failed to suspend " + hostName + ": " + e.getMessage()); throw webExceptionFromTimeout("suspend", hostName, e); } catch (HostStateChangeDeniedException e) { log.log(LogLevel.DEBUG, "Failed to suspend " + hostName + ": " + e.getMessage()); throw webExceptionWithDenialReason("suspend", hostName, e); } return new UpdateHostResponse(hostName.s(), null); } @Override public UpdateHostResponse resume(final String hostNameString) { HostName hostName = new HostName(hostNameString); try { orchestrator.resume(hostName); } catch (HostNameNotFoundException e) { log.log(LogLevel.DEBUG, "Host not found: " + hostName); throw new NotFoundException(e); } catch (UncheckedTimeoutException e) { log.log(LogLevel.DEBUG, "Failed to resume " + hostName + ": " + e.getMessage()); throw webExceptionFromTimeout("resume", hostName, e); } catch (HostStateChangeDeniedException e) { log.log(LogLevel.DEBUG, "Failed to resume " + hostName + ": " + e.getMessage()); throw webExceptionWithDenialReason("resume", hostName, e); } return new UpdateHostResponse(hostName.s(), null); } private static WebApplicationException webExceptionFromTimeout(String operationDescription, HostName hostName, UncheckedTimeoutException e) { // Return timeouts as 409 Conflict instead of 504 Gateway Timeout to reduce noise in 5xx graphs. return createWebException(operationDescription, hostName, e, HostedVespaPolicy.DEADLINE_CONSTRAINT, e.getMessage(), Response.Status.CONFLICT); } private static WebApplicationException webExceptionWithDenialReason( String operationDescription, HostName hostName, HostStateChangeDeniedException e) { return createWebException(operationDescription, hostName, e, e.getConstraintName(), e.getMessage(), Response.Status.CONFLICT); } private static WebApplicationException createWebException(String operationDescription, HostName hostname, Exception e, String constraint, String message, Response.Status status) { HostStateChangeDenialReason hostStateChangeDenialReason = new HostStateChangeDenialReason( constraint, operationDescription + " failed: " + message); UpdateHostResponse response = new UpdateHostResponse(hostname.s(), hostStateChangeDenialReason); return new WebApplicationException( hostStateChangeDenialReason.toString(), e, Response.status(status) .entity(response) .type(MediaType.APPLICATION_JSON_TYPE) .build()); } }
package com.psddev.dari.db; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public interface Recordable { /** * Returns the state {@linkplain State#linkObject linked} to this * instance. */ public State getState(); /** * Sets the state {@linkplain State#linkObject linked} to this * instance. This method must also {@linkplain State#unlinkObject * unlink} the state previously set. */ public void setState(State state); /** * Returns an instance of the given {@code modificationClass} linked * to this object. */ public <T> T as(Class<T> modificationClass); /** * Specifies whether the target type is abstract and can't be used * to create a concrete instance. */ @Documented @ObjectType.AnnotationProcessorClass(AbstractProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Abstract { boolean value() default true; } /** * Specifies the JavaBeans property name that can be used to access an * instance of the target type as a modification. * * <p>For example, given the following modification:</p> * * <blockquote><pre><code data-type="java"> *@Modification.BeanProperty("css") *class CustomCss extends Modification&lt;Object&gt; { * public String getBodyClass() { * return getOriginalObject().getClass().getName().replace('.', '_'); * } *} * </code></pre></blockquote> * * * <p>The following becomes valid and will invoke the {@code getBodyClass} * above, even if the {@code content} object doesn't define a * {@code getCss} method.</p> * * <blockquote><pre><code data-type="jsp"> *${content.css.bodyClass} * </code></pre></blockquote> */ @Documented @ObjectType.AnnotationProcessorClass(BeanPropertyProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface BeanProperty { String value(); } /** Specifies the maximum number of items allowed in the target field. */ @Documented @ObjectField.AnnotationProcessorClass(CollectionMaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CollectionMaximum { int value(); } /** Specifies the minimum number of items required in the target field. */ @Documented @ObjectField.AnnotationProcessorClass(CollectionMinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CollectionMinimum { int value(); } /** * Specifies whether the target field is always denormalized within * another instance. */ @Documented @Inherited @ObjectField.AnnotationProcessorClass(DenormalizedProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface Denormalized { boolean value() default true; String[] fields() default { }; } /** Specifies the target's display name. */ @Documented @ObjectField.AnnotationProcessorClass(DisplayNameProcessor.class) @ObjectType.AnnotationProcessorClass(DisplayNameProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface DisplayName { String value(); } /** * Specifies whether the target data is always embedded within * another instance. */ @Documented @Inherited @ObjectField.AnnotationProcessorClass(EmbeddedProcessor.class) @ObjectType.AnnotationProcessorClass(EmbeddedProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface Embedded { boolean value() default true; } /** * Specifies the prefix for the internal names of all fields in the * target type. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FieldInternalNamePrefix { String value(); } /** Specifies whether the target field is ignored. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Ignored { boolean value() default true; } /** Specifies whether the target field value is indexed. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Indexed { String[] extraFields() default { }; boolean unique() default false; boolean caseSensitive() default false; boolean visibility() default false; /** @deprecated Use {@link #unique} instead. */ @Deprecated boolean isUnique() default false; } /** Specifies the target's internal name. */ @Documented @ObjectType.AnnotationProcessorClass(InternalNameProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface InternalName { String value(); } /** * Specifies the name of the field in the junction query that should be * used to populate the target field. */ @Documented @ObjectField.AnnotationProcessorClass(JunctionFieldProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface JunctionField { String value(); } /** * Specifies the name of the position field in the junction query that * should be used to order the collection in the target field. */ @Documented @ObjectField.AnnotationProcessorClass(JunctionPositionFieldProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface JunctionPositionField { String value(); } /** * Specifies the field names that are used to retrieve the * labels of the objects represented by the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(LabelFieldsProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface LabelFields { String[] value(); } /** * Specifies either the maximum numeric value or string length of the * target field. */ @Documented @ObjectField.AnnotationProcessorClass(MaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Maximum { double value(); } /** Specifies the field the metric is recorded in. */ @Documented @Retention(RetentionPolicy.RUNTIME) @ObjectField.AnnotationProcessorClass(MetricValueProcessor.class) @Target(ElementType.FIELD) public @interface MetricValue { Class<? extends MetricInterval> interval() default MetricInterval.Hourly.class; } /** * Specifies either the minimum numeric value or string length of the * target field. */ @Documented @ObjectField.AnnotationProcessorClass(MinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Minimum { double value(); } /** * Specifies the field name used to retrieve the previews of the * objects represented by the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(PreviewFieldProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface PreviewField { String value(); } /** * Specifies the regular expression pattern that the target field value * must match. */ @Documented @ObjectField.AnnotationProcessorClass(RegexProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Regex { String value(); } /** Specifies whether the target field value is required. */ @Documented @ObjectField.AnnotationProcessorClass(RequiredProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Required { boolean value() default true; } /** Specifies the source database class for the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(SourceDatabaseClassProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SourceDatabaseClass { Class<? extends Database> value(); } /** Specifies the source database name for the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(SourceDatabaseNameProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SourceDatabaseName { String value(); } /** * Specifies the step between the minimum and the maximum that the * target field must match. */ @Documented @ObjectField.AnnotationProcessorClass(StepProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Step { double value(); } /** Specifies the valid types for the target field value. */ @Documented @ObjectField.AnnotationProcessorClass(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Types { Class<?>[] value(); } /** Specifies the valid values for the target field value. */ @Documented @ObjectField.AnnotationProcessorClass(ValuesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Values { String[] value(); } @Documented @Inherited @ObjectField.AnnotationProcessorClass(WhereProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Where { String value(); } @ObjectType.AnnotationProcessorClass(BootstrapPackagesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface BootstrapPackages { String[] value(); String[] depends() default { }; } /** @deprecated Use {@link Denormalized} instead. */ @Deprecated @Documented @Inherited @ObjectType.AnnotationProcessorClass(DenormalizedFieldsProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DenormalizedFields { String[] value(); } /** @deprecated Use {@link CollectionMaximum} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(CollectionMaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldCollectionMaximum { int value(); } /** @deprecated Use {@link CollectionMinimum} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(CollectionMinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldCollectionMinimum { int value(); } /** @deprecated Use {@link DisplayName} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(DisplayNameProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldDisplayName { String value(); } /** @deprecated Use {@link Embedded} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(EmbeddedProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldEmbedded { boolean value() default true; } /** @deprecated Use {@link Modification} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldGlobal { } /** @deprecated Use {@link Ignored} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIgnored { } /** @deprecated Use {@link Indexed} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIndexed { String[] extraFields() default { }; boolean isUnique() default false; } /** @deprecated Use {@link InternalName} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface FieldInternalName { String value(); } /** @deprecated Use {@link FieldTypes} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldItemTypes { Class<?>[] value(); } /** @deprecated Use {@link Maximum} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(MaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldMaximum { double value(); } /** @deprecated Use {@link Minimum} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(MinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldMinimum { double value(); } /** @deprecated Use {@link Regex} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(RegexProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldPattern { String value(); } /** @deprecated Use {@link Required} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(RequiredProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldRequired { boolean value() default true; } /** @deprecated Use {@link Step} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(StepProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldStep { double value(); } /** @deprecated Use {@link Types} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldTypes { Class<?>[] value(); } /** @deprecated Use {@link FieldIndexed} with {@code isUnique} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldUnique { } /** @deprecated Use {@link Values} instead. */ @Deprecated @Documented @ObjectField.AnnotationProcessorClass(ValuesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldValues { String[] value(); } } class AbstractProcessor implements ObjectType.AnnotationProcessor<Recordable.Abstract> { @Override public void process(ObjectType type, Recordable.Abstract annotation) { type.setAbstract(annotation.value()); } } class BeanPropertyProcessor implements ObjectType.AnnotationProcessor<Recordable.BeanProperty> { @Override public void process(ObjectType type, Recordable.BeanProperty annotation) { if (type.getGroups().contains(Modification.class.getName())) { type.setJavaBeanProperty(annotation.value()); } } } class CollectionMaximumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { if (field.isInternalCollectionType()) { field.setCollectionMaximum(annotation instanceof Recordable.FieldCollectionMaximum ? ((Recordable.FieldCollectionMaximum) annotation).value() : ((Recordable.CollectionMaximum) annotation).value()); } else { throw new IllegalArgumentException(String.format( "[%s] annotation cannot be applied to a non-collection field!", annotation.getClass().getName())); } } } class CollectionMinimumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { if (field.isInternalCollectionType()) { field.setCollectionMinimum(annotation instanceof Recordable.FieldCollectionMinimum ? ((Recordable.FieldCollectionMinimum) annotation).value() : ((Recordable.CollectionMinimum) annotation).value()); } else { throw new IllegalArgumentException(String.format( "[%s] annotation cannot be applied to a non-collection field!", annotation.getClass().getName())); } } } class DenormalizedProcessor implements ObjectField.AnnotationProcessor<Recordable.Denormalized>, ObjectType.AnnotationProcessor<Recordable.Denormalized> { @Override public void process(ObjectType type, ObjectField field, Recordable.Denormalized annotation) { field.setDenormalized(annotation.value()); Collections.addAll(field.getDenormalizedFields(), annotation.fields()); } @Override public void process(ObjectType type, Recordable.Denormalized annotation) { type.setDenormalized(annotation.value()); Collections.addAll(type.getDenormalizedFields(), annotation.fields()); } } class DenormalizedFieldsProcessor implements ObjectType.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, Annotation annotation) { type.setDenormalized(true); Collections.addAll(type.getDenormalizedFields(), ((Recordable.DenormalizedFields) annotation).value()); } } class DisplayNameProcessor implements ObjectField.AnnotationProcessor<Annotation>, ObjectType.AnnotationProcessor<Recordable.DisplayName> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setDisplayName(annotation instanceof Recordable.FieldDisplayName ? ((Recordable.FieldDisplayName) annotation).value() : ((Recordable.DisplayName) annotation).value()); } @Override public void process(ObjectType type, Recordable.DisplayName annotation) { Class<?> objectClass = type.getObjectClass(); if (objectClass != null) { Recordable.DisplayName displayName = objectClass.getAnnotation(Recordable.DisplayName.class); // Only sets the display name if the annotation came from the type being modified. if (displayName != null && displayName.value() != null && displayName.value().equals(annotation.value())) { type.setDisplayName(annotation.value()); } } } } class EmbeddedProcessor implements ObjectField.AnnotationProcessor<Annotation>, ObjectType.AnnotationProcessor<Recordable.Embedded> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setEmbedded(annotation instanceof Recordable.FieldEmbedded ? ((Recordable.FieldEmbedded) annotation).value() : ((Recordable.Embedded) annotation).value()); } @Override public void process(ObjectType type, Recordable.Embedded annotation) { type.setEmbedded(annotation.value()); } } class InternalNameProcessor implements ObjectType.AnnotationProcessor<Recordable.InternalName> { @Override public void process(ObjectType type, Recordable.InternalName annotation) { type.setInternalName(annotation.value()); } } class JunctionFieldProcessor implements ObjectField.AnnotationProcessor<Recordable.JunctionField> { @Override public void process(ObjectType type, ObjectField field, Recordable.JunctionField annotation) { field.setJunctionField(annotation.value()); } } class JunctionPositionFieldProcessor implements ObjectField.AnnotationProcessor<Recordable.JunctionPositionField> { @Override public void process(ObjectType type, ObjectField field, Recordable.JunctionPositionField annotation) { field.setJunctionPositionField(annotation.value()); } } class LabelFieldsProcessor implements ObjectType.AnnotationProcessor<Recordable.LabelFields> { @Override public void process(ObjectType type, Recordable.LabelFields annotation) { List<String> labelFields = type.getLabelFields(); for (String field : annotation.value()) { if (!labelFields.contains(field)) { labelFields.add(field); } } } } class MaximumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setMaximum(annotation instanceof Recordable.FieldMaximum ? ((Recordable.FieldMaximum) annotation).value() : ((Recordable.Maximum) annotation).value()); } } class MetricValueProcessor implements ObjectField.AnnotationProcessor<Recordable.MetricValue> { @Override public void process(ObjectType type, ObjectField field, Recordable.MetricValue annotation) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); MetricAccess.FieldData metricFieldData = field.as(MetricAccess.FieldData.class); fieldData.setIndexTable(MetricAccess.METRIC_TABLE); fieldData.setIndexTableColumnName(MetricAccess.METRIC_DATA_FIELD); fieldData.setIndexTableSameColumnNames(false); fieldData.setIndexTableSource(true); fieldData.setIndexTableReadOnly(true); metricFieldData.setEventDateProcessorClass(annotation.interval()); metricFieldData.setMetricValue(true); } } class MinimumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setMinimum(annotation instanceof Recordable.FieldMinimum ? ((Recordable.FieldMinimum) annotation).value() : ((Recordable.Minimum) annotation).value()); } } class PreviewFieldProcessor implements ObjectType.AnnotationProcessor<Recordable.PreviewField> { @Override public void process(ObjectType type, Recordable.PreviewField annotation) { type.setPreviewField(annotation.value()); } } class RegexProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setPattern(annotation instanceof Recordable.FieldPattern ? ((Recordable.FieldPattern) annotation).value() : ((Recordable.Regex) annotation).value()); } } class RequiredProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setRequired(annotation instanceof Recordable.FieldRequired ? ((Recordable.FieldRequired) annotation).value() : ((Recordable.Required) annotation).value()); } } class SourceDatabaseClassProcessor implements ObjectType.AnnotationProcessor<Recordable.SourceDatabaseClass> { @Override public void process(ObjectType type, Recordable.SourceDatabaseClass annotation) { type.setSourceDatabaseClassName(annotation.value().getName()); } } class SourceDatabaseNameProcessor implements ObjectType.AnnotationProcessor<Recordable.SourceDatabaseName> { @Override public void process(ObjectType type, Recordable.SourceDatabaseName annotation) { type.setSourceDatabaseName(annotation.value()); } } class StepProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setStep(annotation instanceof Recordable.FieldStep ? ((Recordable.FieldStep) annotation).value() : ((Recordable.Step) annotation).value()); } } class TypesProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { Set<ObjectType> types = new LinkedHashSet<ObjectType>(); DatabaseEnvironment environment = field.getParent().getEnvironment(); for (Class<?> typeClass : annotation instanceof Recordable.FieldTypes ? ((Recordable.FieldTypes) annotation).value() : annotation instanceof Recordable.FieldItemTypes ? ((Recordable.FieldItemTypes) annotation).value() : ((Recordable.Types) annotation).value()) { types.add(environment.getTypeByClass(typeClass)); } field.setTypes(types); } } class ValuesProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { Set<ObjectField.Value> values = new LinkedHashSet<ObjectField.Value>(); for (String valueValue : annotation instanceof Recordable.FieldValues ? ((Recordable.FieldValues) annotation).value() : ((Recordable.Values) annotation).value()) { ObjectField.Value value = new ObjectField.Value(); value.setValue(valueValue); values.add(value); } field.setValues(values); } } class WhereProcessor implements ObjectField.AnnotationProcessor<Recordable.Where> { @Override public void process(ObjectType type, ObjectField field, Recordable.Where annotation) { field.setPredicate(annotation.value()); } } class BootstrapPackagesProcessor implements ObjectType.AnnotationProcessor<Recordable.BootstrapPackages> { @Override public void process(ObjectType type, Recordable.BootstrapPackages annotation) { Set<String> packageNames = new LinkedHashSet<String>(); for (String packageName : annotation.value()) { packageNames.add(packageName); for (String dependency : annotation.depends()) { ObjectType dependentType = type.getEnvironment().getTypeByName(dependency); if (dependentType != null) { dependentType.as(BootstrapPackage.TypeData.class).getPackageNames().add(packageName); } } } type.as(BootstrapPackage.TypeData.class).setPackageNames(packageNames); } }
package org.jgrapes.osgi.upnpserver; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; public class RootDeviceListener implements ServiceListener { @Override public void serviceChanged(ServiceEvent event) { // TODO Auto-generated method stub } }
package org.metaborg.core.project; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; import org.apache.commons.vfs2.FileName; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.MetaborgException; import org.metaborg.core.config.ConfigRequest; import org.metaborg.core.config.IProjectConfig; import org.metaborg.core.config.IProjectConfigService; import org.metaborg.core.messages.StreamMessagePrinter; import org.metaborg.core.source.ISourceTextService; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.LoggerUtils; import com.google.common.collect.Maps; import com.google.inject.Inject; public class SimpleProjectService implements ISimpleProjectService { private static final ILogger logger = LoggerUtils.logger(SimpleProjectService.class); private final ISourceTextService sourceTextService; private final IProjectConfigService projectConfigService; private final ConcurrentMap<FileName, IProject> projects = Maps.newConcurrentMap(); @Inject public SimpleProjectService(ISourceTextService sourceTextService, IProjectConfigService projectConfigService) { this.sourceTextService = sourceTextService; this.projectConfigService = projectConfigService; } @Override public @Nullable IProject get(FileObject resource) { final FileName name = resource.getName(); for(Entry<FileName, IProject> entry : projects.entrySet()) { final FileName projectName = entry.getKey(); if(name.equals(projectName) || name.isAncestor(projectName)) { return entry.getValue(); } } return null; } @Override public IProject create(FileObject location) throws MetaborgException { final FileName name = location.getName(); for(FileName projectName : projects.keySet()) { if(name.equals(projectName) || name.isAncestor(projectName)) { final String message = String.format("Location %s is equal to or nested in project %s", name, projectName); throw new MetaborgException(message); } } final ConfigRequest<? extends IProjectConfig> configRequest = projectConfigService.get(location); if(!configRequest.valid()) { logger.error("Errors occurred when retrieving project configuration from project directory {}", location); configRequest.reportErrors(new StreamMessagePrinter(sourceTextService, false, false, logger)); } final IProjectConfig config; if(configRequest.config() != null) { config = configRequest.config(); } else { logger.info("Using default configuration for project at {}", location); config = projectConfigService.defaultConfig(location); } final IProject project = new Project(location, config); if(projects.putIfAbsent(name, project) != null) { final String message = String.format("Project with location %s already exists", name); throw new MetaborgException(message); } return project; } @Override public void remove(IProject project) throws MetaborgException { final FileName name = project.location().getName(); if(projects.remove(name) == null) { final String message = String.format("Project with location %s does not exists", name); throw new MetaborgException(message); } } }
package org.mockitousage.stubbing; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockitoutil.TestBase; public class CallingRealMethodTest extends TestBase { @Mock TestedObject mock; static class TestedObject { String value; void setValue(String value) { this.value = value; } String getValue() { return "HARD_CODED_RETURN_VALUE"; } String callInternalMethod() { return getValue(); } } @Test public void shouldAllowCallingInternalMethod() { when(mock.getValue()).thenReturn("foo"); when(mock.callInternalMethod()).thenCallRealMethod(); assertEquals("foo", mock.callInternalMethod()); } @Test public void shouldReturnRealValue() { when(mock.getValue()).thenCallRealMethod(); Assert.assertEquals("HARD_CODED_RETURN_VALUE", mock.getValue()); } @Test public void shouldExecuteRealMethod() { doCallRealMethod().when(mock).setValue(anyString()); mock.setValue("REAL_VALUE"); Assert.assertEquals("REAL_VALUE", mock.value); } @Test public void shouldCallRealMethodByDefault() { TestedObject mock = mock(TestedObject.class, CALLS_REAL_METHODS); Assert.assertEquals("HARD_CODED_RETURN_VALUE", mock.getValue()); } @Test public void shouldNotCallRealMethodWhenStubbedLater() { TestedObject mock = mock(TestedObject.class); when(mock.getValue()).thenCallRealMethod(); when(mock.getValue()).thenReturn("FAKE_VALUE"); Assert.assertEquals("FAKE_VALUE", mock.getValue()); } }
package org.exist.xquery.functions.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.exist.storage.DBBroker; import org.exist.xmldb.DatabaseInstanceManager; import org.exist.xquery.XPathException; import org.exist.xquery.modules.counters.CountersModule; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XPathQueryService; /** * @author Jasper Linthorst (jasper.linthorst@gmail.com) */ public class CounterTest { private final static String IMPORT = "import module namespace counter=\"" + CountersModule.NAMESPACE_URI + "\" " + "at \"java:org.exist.xquery.modules.counters.CountersModule\"; "; private XPathQueryService service; private Collection root = null; private Database database = null; public CounterTest() { } @Before public void setUp() throws Exception { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null); service = (XPathQueryService) root.getService("XQueryService", "1.0"); } @After public void tearDown() throws Exception { DatabaseManager.deregisterDatabase(database); DatabaseInstanceManager dim = (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0"); dim.shutdown(); // clear instance variables service = null; root = null; } @Test public void testCreateAndDestroyCounter() throws XPathException { ResourceSet result = null; String r = ""; try { String query = IMPORT + "counter:create('jasper1')"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("0", r); query = IMPORT +"counter:next-value('jasper1')"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1", r); query = IMPORT +"counter:destroy('jasper1')"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testCreateAndDestroyCounter(): " + e.getMessage()); fail(e.getMessage()); } } @Test public void testCreateAndInitAndDestroyCounter() throws XPathException { ResourceSet result = null; String r = ""; try { String query = IMPORT +"counter:create('jasper3',xs:long(1200))"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1200", r); query = IMPORT +"counter:next-value('jasper3')"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1201", r); query = IMPORT +"counter:destroy('jasper3')"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testCreateAndDestroyCounter(): " + e.getMessage()); fail(e.getMessage()); } } @Test public void threadedIncrementTest() throws XPathException, InterruptedException, XMLDBException { service = (XPathQueryService) root.getService("XQueryService", "1.0"); String query = IMPORT +"counter:create('jasper2')"; ResourceSet result = service.query(query); assertEquals("0", result.getResource(0).getContent()); Thread a = new IncrementThread(); a.start(); Thread b = new IncrementThread(); b.start(); Thread c = new IncrementThread(); c.start(); a.join(); b.join(); c.join(); query = IMPORT +"counter:next-value('jasper2')"; ResourceSet valueAfter = service.query(query); query = IMPORT +"counter:destroy('jasper2')"; result = service.query(query); assertEquals("601", (String)valueAfter.getResource(0).getContent()); } class IncrementThread extends Thread { public void run() { ResourceSet result = null; String query=""; try { service = (XPathQueryService) root.getService("XQueryService", "1.0"); for (int i=0; i<200; i++) { query = IMPORT +"counter:next-value('jasper2')"; result = service.query(query); System.out.println("Thread "+getId()+": Counter value:"+result.getResource(0).getContent()); } } catch (XMLDBException e) { e.printStackTrace(); } } } }
package com.artemis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import com.artemis.annotations.Wire; import com.artemis.component.ComponentX; import com.artemis.component.ComponentY; import com.artemis.managers.TagManager; import com.artemis.systems.EntityProcessingSystem; import com.artemis.systems.VoidEntitySystem; public class WireTest { private World world; private MappedSystem mappedSystem; private MappedSystemAll mappedSystemAll; private ExtendedSystem extendedSystem; private MappedManager mappedManager; private MappedManagerAll mappedManagerAll; private ExtendedManager extendedManager; private Entity entity; @Before public void init() { mappedSystem = new MappedSystem(); mappedSystemAll = new MappedSystemAll(); extendedSystem = new ExtendedSystem(); mappedManager = new MappedManager(); mappedManagerAll = new MappedManagerAll(); extendedManager = new ExtendedManager(); world = new World(new WorldConfiguration() .setManager(TagManager.class) .setManager(mappedManager) .setManager(mappedManagerAll) .setManager(extendedManager) .setSystem(mappedSystem) .setSystem(mappedSystemAll) .setSystem(extendedSystem)); entity = world.createEntity(); EntityEdit edit = entity.edit(); edit.create(ComponentX.class); edit.create(ComponentY.class); world.process(); } @Test public void systems_support_wire_annotation() { assertNotNull(mappedSystem.x); assertNotNull(mappedSystem.y); assertNotNull(mappedSystem.tagManager); assertNotNull(mappedSystem.mappedSystemAll); assertNotNull(extendedSystem.x); assertNotNull(extendedSystem.y); assertEquals(ComponentX.class, mappedSystem.x.get(entity).getClass()); assertEquals(ComponentY.class, mappedSystem.y.get(entity).getClass()); } @Test public void managers_support_wire_annotation() { assertNotNull(mappedManager.x); assertNotNull(mappedManager.y); assertNotNull(mappedManager.tagManager); assertNotNull(mappedManager.mappedSystem); assertEquals(ComponentX.class, mappedSystem.x.get(entity).getClass()); assertEquals(ComponentY.class, mappedSystem.y.get(entity).getClass()); } @Test public void systems_all_support_wire_annotation() { assertNotNull(mappedSystemAll.x); assertNotNull(mappedSystemAll.y); assertNotNull(mappedSystemAll.tagManager); assertNotNull(mappedSystemAll.mappedSystem); assertEquals(ComponentX.class, mappedSystem.x.get(entity).getClass()); assertEquals(ComponentY.class, mappedSystem.y.get(entity).getClass()); } @Test public void managers_all_support_wire_annotation() { assertNotNull(mappedManagerAll.x); assertNotNull(mappedManagerAll.y); assertNotNull(mappedManagerAll.tagManager); assertNotNull(mappedManagerAll.mappedSystem); assertNotNull(extendedManager.x); assertNotNull(extendedManager.y); assertEquals(ComponentX.class, mappedSystem.x.get(entity).getClass()); assertEquals(ComponentY.class, mappedSystem.y.get(entity).getClass()); } @Test(expected=MundaneWireException.class) public void ensure_inherited_systems_not_injected() { World world = new World(new WorldConfiguration() .setSystem(new FailingSystem())); } @Test public void ensure_inherited_managers_not_injected() { FailingSystem failingSystem = new FailingSystem(); FailingManager failingManager = new FailingManager(); World world = new World(new WorldConfiguration() .setManager(failingManager) .setSystem(failingSystem)); assertNull(failingManager.x); assertNull(failingSystem.x); } @Test(expected=MundaneWireException.class) public void fail_on_system_not_injected() { World world = new World(new WorldConfiguration() .setSystem(new FailingNpeSystem())); } @Test(expected=MundaneWireException.class) public void fail_on_manager_not_injected() { World world = new World(new WorldConfiguration() .setManager(new FailingNpeManager())); } @Test public void inject_pojo_object() { World world = new World(new WorldConfiguration() .setManager(TagManager.class) .setSystem(new MappedSystem()) .setSystem(new MappedSystemAll())); PojoWireNoWorld obj = new PojoWireNoWorld(); world.inject(obj); assertNotNull(obj.componentXMapper); assertNotNull(obj.tagManager); assertNotNull(obj.mappedSystem); } @Test public void inject_anything_into_everything() { World world = new World(new WorldConfiguration() .register("world") .register("hupp", "n1") .register("blergh", "n2") .setManager(TagManager.class)); SomeThing st = new SomeThing(); world.inject(st); assertNotNull(st.tagManager); assertEquals("n1", st.helloN1); assertEquals("world", st.hello); assertEquals("n2", st.helloN2); } @Test public void try_inject_on_wired_object_mirrors_inject_behaviour() { World world = new World(new WorldConfiguration().register("world").setManager(TagManager.class)); SomeThing st = new SomeThing(); world.tryInject(st); assertEquals("world", st.hello); } @Test public void try_inject_on_plain_object_does_nothing() { World world = new World(new WorldConfiguration()); Object object = new Object(); world.tryInject(object); } @Test @SuppressWarnings("static-method") public void inject_static_field() { World w = new World(new WorldConfiguration() .setManager(new ManagerWithStaticField())); w.process(); assertNotNull(ManagerWithStaticField.mapper); } @Test @SuppressWarnings("static-method") public void inject_static_field_extended() { World w = new World(new WorldConfiguration() .setManager(new ExtendedStaticManager())); w.process(); assertNotNull(ManagerWithStaticField.mapper); } @Test @SuppressWarnings("static-method") public void inject_static_field_inherited() { World w = new World(new WorldConfiguration() .setManager(new ManagerWithStaticField())); w.process(); assertNotNull(ManagerWithStaticField.mapper); } @Wire private static class SomeThing { @Wire(name="hupp") private String helloN1; @Wire private String hello; @Wire(name="blergh") private String helloN2; private TagManager tagManager; } @Wire private static class PojoWireNoWorld { private ComponentMapper<ComponentX> componentXMapper; private TagManager tagManager; private MappedSystem mappedSystem; } @Wire private static class MappedSystemAll extends EntityProcessingSystem { private ComponentMapper<ComponentX> x; private ComponentMapper<ComponentY> y; private TagManager tagManager; private MappedSystem mappedSystem; @SuppressWarnings("unchecked") public MappedSystemAll() { super(Aspect.all(ComponentX.class, ComponentY.class)); } @Override protected void process(Entity e) {} } private static class MappedSystem extends EntityProcessingSystem { @Wire private ComponentMapper<ComponentX> x; @Wire private ComponentMapper<ComponentY> y; @Wire private TagManager tagManager; @Wire private MappedSystemAll mappedSystemAll; @SuppressWarnings("unchecked") public MappedSystem() { super(Aspect.all(ComponentX.class, ComponentY.class)); } @Override protected void process(Entity e) {} } @Wire(injectInherited=true) private static class ExtendedStaticManager extends ManagerWithStaticField {} @Wire private static class ManagerWithStaticField extends Manager{ static ComponentMapper<ComponentX> mapper; } private static class MappedManager extends Manager { @Wire private ComponentMapper<ComponentX> x; @Wire private ComponentMapper<ComponentY> y; @Wire private MappedSystem mappedSystem; @Wire private TagManager tagManager; } @Wire private static class MappedManagerAll extends Manager { private ComponentMapper<ComponentX> x; private ComponentMapper<ComponentY> y; private MappedSystem mappedSystem; private TagManager tagManager; } private static class BaseManager extends Manager { protected ComponentMapper<ComponentX> x; } @Wire(injectInherited=true) private static class ExtendedManager extends BaseManager { private ComponentMapper<ComponentY> y; } @Wire private static class FailingManager extends BaseManager { @SuppressWarnings("unused") private ComponentMapper<ComponentY> y; } private static abstract class BaseSystem extends VoidEntitySystem { protected ComponentMapper<ComponentX> x; } @Wire(injectInherited=true) private static class ExtendedSystem extends BaseSystem { private ComponentMapper<ComponentY> y; @Override protected void processSystem() {} } @Wire private static class FailingSystem extends BaseSystem { @SuppressWarnings("unused") private FailingManager manager; @Override protected void processSystem() {} } @Wire private static class FailingNpeSystem extends VoidEntitySystem { @SuppressWarnings("unused") private FailingManager manager; @Override protected void processSystem() {} } @Wire private static class FailingNpeManager extends Manager { @SuppressWarnings("unused") private FailingSystem fail; } }
// nospam (at) thbbpt (dot) net // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA package interfascia; import processing.core.*; import java.awt.event.*; public class GUIController { private GUIComponent[] contents; private int numItems = 0; private int focusIndex = -1; private PApplet parent; private IFLookAndFeel lookAndFeel; public GUIController (PApplet newParent) { //this (10); parent = newParent; contents = new GUIComponent[5]; lookAndFeel = new IFLookAndFeel(IFLookAndFeel.DEFAULT); lookAndFeel.initWithParent(parent); parent.registerKeyEvent(this); } //public GUIController (int argCapacity) { // contents = new GUIComponent[argCapacity]; public void add (GUIComponent component) { if (numItems == contents.length) { GUIComponent[] temp = contents; contents = new GUIComponent[contents.length * 2]; System.arraycopy(temp, 0, contents, 0, numItems); } component.setIndex(numItems); contents[numItems++] = component; component.setParent (parent); component.setController(this); component.setLookAndFeel(lookAndFeel); } public void remove (GUIComponent component) { } public void requestFocus(GUIComponent c) { if (focusIndex >= 0 && focusIndex < contents.length) contents[focusIndex].setFocus(false); c.setFocus(true); focusIndex = c.getIndex(); } public void yieldFocus(GUIComponent c) { if (focusIndex > -1 && focusIndex < numItems && contents[focusIndex] == c) { c.setFocus(false); focusIndex = -1; } } public GUIComponent getComponentWithFocus() { return contents[focusIndex]; } public boolean getFocusStatusForComponent(GUIComponent c) { return c == contents[focusIndex]; } public void keyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_TAB) { if (focusIndex >= 0 && focusIndex < contents.length) contents[focusIndex].setFocus(false); if (focusIndex >= numItems - 1 || focusIndex < 0) focusIndex = 0; else focusIndex++; contents[focusIndex].setFocus(true); } else if (e.getKeyCode() != KeyEvent.VK_TAB) { if (focusIndex >= 0 && focusIndex < contents.length) contents[focusIndex].keyEvent(e); } } }
package com.dooble.phonertc; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.graphics.Point; import android.webkit.WebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.webrtc.AudioSource; import org.webrtc.DataChannel; import org.webrtc.IceCandidate; import org.webrtc.MediaConstraints; import org.webrtc.MediaStream; import org.webrtc.MediaStreamTrack; import org.webrtc.PeerConnection; import org.webrtc.PeerConnectionFactory; import org.webrtc.SdpObserver; import org.webrtc.SessionDescription; import org.webrtc.PeerConnection.IceConnectionState; import org.webrtc.PeerConnection.IceGatheringState; import org.webrtc.VideoCapturer; import org.webrtc.VideoRenderer; import org.webrtc.VideoRenderer.I420Frame; import org.webrtc.VideoSource; import org.webrtc.VideoTrack; import android.media.AudioManager; import android.util.Log; public class PhoneRTCPlugin extends CordovaPlugin { public static final String ACTION_CALL = "call"; public static final String ACTION_RECEIVE_MESSAGE = "receiveMessage"; public static final String ACTION_DISCONNECT = "disconnect"; public static final String ACTION_UPDATE_VIDEO_POSITION = "updateVideoPosition"; public static final String ACTION_SET_ENABLED_MEDIUM = "setEnabledMedium"; CallbackContext _callbackContext; private final SDPObserver sdpObserver = new SDPObserver(); private final PCObserver pcObserver = new PCObserver(); private boolean isInitiator; private PeerConnectionFactory factory; private PeerConnection pc; private MediaConstraints sdpMediaConstraints; private LinkedList<IceCandidate> queuedRemoteCandidates ; private MediaStream localStream; private MediaStream remoteStream; // Synchronize on quit[0] to avoid teardown-related crashes. private final Boolean[] quit = new Boolean[] { false }; private AudioSource audioSource; private VideoCapturer videoCapturer; private VideoSource videoSource; private VideoStreamsView localVideoView; private VideoStreamsView remoteVideoView; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals(ACTION_CALL)) { isInitiator = args.getBoolean(0); final String turnServerHost = args.getString(1); final String turnUsername = args.getString(2); final String turnPassword = args.getString(3); final JSONObject video = (!args.isNull(4)) ? args.getJSONObject(4) : null; _callbackContext = callbackContext; queuedRemoteCandidates = new LinkedList<IceCandidate>(); quit[0] = false; cordova.getThreadPool().execute(new Runnable() { public void run() { PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); AudioManager audioManager = ((AudioManager) cordova.getActivity().getSystemService(cordova.getActivity().AUDIO_SERVICE)); @SuppressWarnings("deprecation") boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn(); //audioManager.setMode(isWiredHeadsetOn ? AudioManager.MODE_IN_CALL // : AudioManager.MODE_IN_COMMUNICATION); audioManager.setSpeakerphoneOn(!isWiredHeadsetOn); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0); abortUnless(PeerConnectionFactory.initializeAndroidGlobals(cordova.getActivity(), true, true), "Failed to initializeAndroidGlobals"); final LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<PeerConnection.IceServer>(); iceServers.add(new PeerConnection.IceServer( "stun:stun.l.google.com:19302")); iceServers.add(new PeerConnection.IceServer( turnServerHost, turnUsername, turnPassword)); sdpMediaConstraints = new MediaConstraints(); sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair( "OfferToReceiveAudio", "true")); sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair( "OfferToReceiveVideo", (video != null) ? "true" : "false")); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { factory = new PeerConnectionFactory(); MediaConstraints pcMediaConstraints = new MediaConstraints(); pcMediaConstraints.optional.add(new MediaConstraints.KeyValuePair( "DtlsSrtpKeyAgreement", "true")); pc = factory.createPeerConnection(iceServers, pcMediaConstraints, pcObserver); localStream = factory.createLocalMediaStream("ARDAMS"); if (video != null) { try { localVideoView = createVideoView(video.getJSONObject("localVideo")); remoteVideoView = createVideoView(video.getJSONObject("remoteVideo")); VideoCapturer capturer = getVideoCapturer(); videoSource = factory.createVideoSource(capturer, new MediaConstraints()); VideoTrack videoTrack = factory.createVideoTrack("ARDAMSv0", videoSource); videoTrack.addRenderer(new VideoRenderer(new VideoCallbacks( localVideoView, VideoStreamsView.Endpoint.REMOTE))); localStream.addTrack(videoTrack); } catch (JSONException e) { Log.e("com.dooble.phonertc", "A JSON exception has occured while trying to add video.", e); } } audioSource = factory.createAudioSource(new MediaConstraints()); localStream.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource)); pc.addStream(localStream, new MediaConstraints()); if (isInitiator) { pc.createOffer(sdpObserver, sdpMediaConstraints); } } }); } }); return true; } else if (action.equals(ACTION_RECEIVE_MESSAGE)) { final String message = args.getString(0); cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject json = new JSONObject(message); String type = (String) json.get("type"); if (type.equals("candidate")) { final IceCandidate candidate = new IceCandidate( (String) json.get("id"), json.getInt("label"), (String) json.get("candidate")); if (queuedRemoteCandidates != null) { queuedRemoteCandidates.add(candidate); } else { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pc.addIceCandidate(candidate); } }); } } else if (type.equals("answer") || type.equals("offer")) { final SessionDescription sdp = new SessionDescription( SessionDescription.Type.fromCanonicalForm(type), preferISAC((String) json.get("sdp"))); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pc.setRemoteDescription(sdpObserver, sdp); } }); } else if (type.equals("bye")) { Log.d("com.dooble.phonertc", "Remote end hung up; dropping PeerConnection"); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { disconnect(); } }); } else { //throw new RuntimeException("Unexpected message: " + message); } } catch (JSONException e) { throw new RuntimeException(e); } } }); return true; } else if (action.equals(ACTION_DISCONNECT)) { Log.e("com.dooble.phonertc", "DISCONNECT"); disconnect(); } else if (action.equals(ACTION_UPDATE_VIDEO_POSITION)) { final JSONObject videoElements = args.getJSONObject(0); cordova.getActivity().runOnUiThread(new Runnable() { public void run () { try { if (localVideoView != null && videoElements.has("localVideo")) { localVideoView.setLayoutParams(getLayoutParams(videoElements.getJSONObject("localVideo"))); } if (remoteVideoView != null && videoElements.has("remoteVideo")) { remoteVideoView.setLayoutParams(getLayoutParams(videoElements.getJSONObject("remoteVideo"))); } } catch (JSONException e) { throw new RuntimeException(e); } } }); } else if (action.equals(ACTION_SET_ENABLED_MEDIUM)) { String mediumType = args.getString(0); Boolean enabled = args.getBoolean(1); setEnabledMedium(mediumType, enabled); } callbackContext.error("Invalid action"); return false; } private void setEnabledMedium (String mediumType, final boolean enabled) { setEnabledStream(localStream, mediumType, enabled); setEnabledStream(remoteStream, mediumType, enabled); if ("video".equals(mediumType)) { cordova.getActivity().runOnUiThread(new Runnable() { public void run () { if (enabled) { localVideoView.setVisibility(WebView.VISIBLE); remoteVideoView.setVisibility(WebView.VISIBLE); } else { localVideoView.setVisibility(WebView.GONE); remoteVideoView.setVisibility(WebView.GONE); } } }); } } private void setEnabledStream (MediaStream stream, String mediumType, boolean enabled) { if (stream == null) { return; } if ("audio".equals(mediumType)) { setEnabledTracks(stream.audioTracks, enabled); } else if ("video".equals(mediumType)) { setEnabledTracks(stream.videoTracks, enabled); } } private void setEnabledTracks (List<? extends MediaStreamTrack> tracks, boolean enabled) { for (MediaStreamTrack track : tracks) { track.setEnabled(enabled); } } WebView.LayoutParams getLayoutParams (JSONObject config) throws JSONException { int devicePixelRatio = config.getInt("devicePixelRatio"); int width = config.getInt("width") * devicePixelRatio; int height = config.getInt("height") * devicePixelRatio; int x = config.getInt("x") * devicePixelRatio; int y = config.getInt("y") * devicePixelRatio; WebView.LayoutParams params = new WebView.LayoutParams(width, height, x, y); return params; } VideoStreamsView createVideoView(JSONObject config) throws JSONException { WebView.LayoutParams params = getLayoutParams(config); Point displaySize = new Point(params.width, params.height); VideoStreamsView view = new VideoStreamsView(cordova.getActivity(), displaySize); webView.addView(view, params); return view; } void sendMessage(JSONObject data) { PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } private String preferISAC(String sdpDescription) { String[] lines = sdpDescription.split("\r?\n"); int mLineIndex = -1; String isac16kRtpMap = null; Pattern isac16kPattern = Pattern .compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$"); for (int i = 0; (i < lines.length) && (mLineIndex == -1 || isac16kRtpMap == null); ++i) { if (lines[i].startsWith("m=audio ")) { mLineIndex = i; continue; } Matcher isac16kMatcher = isac16kPattern.matcher(lines[i]); if (isac16kMatcher.matches()) { isac16kRtpMap = isac16kMatcher.group(1); continue; } } if (mLineIndex == -1) { Log.d("com.dooble.phonertc", "No m=audio line, so can't prefer iSAC"); return sdpDescription; } if (isac16kRtpMap == null) { Log.d("com.dooble.phonertc", "No ISAC/16000 line, so can't prefer iSAC"); return sdpDescription; } String[] origMLineParts = lines[mLineIndex].split(" "); StringBuilder newMLine = new StringBuilder(); int origPartIndex = 0; // Format is: m=<media> <port> <proto> <fmt> ... newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(isac16kRtpMap).append(" "); for (; origPartIndex < origMLineParts.length; ++origPartIndex) { if (!origMLineParts[origPartIndex].equals(isac16kRtpMap)) { newMLine.append(origMLineParts[origPartIndex]).append(" "); } } lines[mLineIndex] = newMLine.toString(); StringBuilder newSdpDescription = new StringBuilder(); for (String line : lines) { newSdpDescription.append(line).append("\r\n"); } return newSdpDescription.toString(); } private static void abortUnless(boolean condition, String msg) { if (!condition) { throw new RuntimeException(msg); } } // Cycle through likely device names for the camera and return the first // capturer that works, or crash if none do. private VideoCapturer getVideoCapturer() { if (videoCapturer != null) { return videoCapturer; } String[] cameraFacing = { "front", "back" }; int[] cameraIndex = { 0, 1 }; int[] cameraOrientation = { 0, 90, 180, 270 }; for (String facing : cameraFacing) { for (int index : cameraIndex) { for (int orientation : cameraOrientation) { String name = "Camera " + index + ", Facing " + facing + ", Orientation " + orientation; VideoCapturer capturer = VideoCapturer.create(name); if (capturer != null) { // logAndToast("Using camera: " + name); return capturer; } } } } throw new RuntimeException("Failed to open capturer"); } private class PCObserver implements PeerConnection.Observer { @Override public void onIceCandidate(final IceCandidate iceCandidate) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { JSONObject json = new JSONObject(); json.put("type", "candidate"); json.put("label", iceCandidate.sdpMLineIndex); json.put("id", iceCandidate.sdpMid); json.put("candidate", iceCandidate.sdp); sendMessage(json); } catch (JSONException e) { // TODO Auto-generated catch bloc e.printStackTrace(); } } }); } @Override public void onAddStream(final MediaStream stream) { remoteStream = stream; PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { if (remoteVideoView != null) { stream.videoTracks.get(0).addRenderer(new VideoRenderer( new VideoCallbacks(remoteVideoView, VideoStreamsView.Endpoint.REMOTE))); } try { JSONObject data = new JSONObject(); data.put("type", "__answered"); sendMessage(data); } catch (JSONException e) { } } }); } @Override public void onDataChannel(DataChannel stream) { // TODO Auto-generated method stub } @Override public void onError() { // TODO Auto-generated method stub } @Override public void onIceConnectionChange(IceConnectionState arg0) { // TODO Auto-generated method stub } @Override public void onIceGatheringChange(IceGatheringState arg0) { try { JSONObject json = new JSONObject(); json.put("type", "IceGatheringChange"); json.put("state", arg0.name()); sendMessage(json); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onRemoveStream(MediaStream arg0) { // TODO Auto-generated method stub } @Override public void onRenegotiationNeeded() { // TODO Auto-generated method stub } @Override public void onSignalingChange( PeerConnection.SignalingState signalingState) { } } private class SDPObserver implements SdpObserver { @Override public void onCreateSuccess(final SessionDescription origSdp) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { SessionDescription sdp = new SessionDescription( origSdp.type, preferISAC(origSdp.description)); try { JSONObject json = new JSONObject(); json.put("type", sdp.type.canonicalForm()); json.put("sdp", sdp.description); sendMessage(json); pc.setLocalDescription(sdpObserver, sdp); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } @Override public void onSetSuccess() { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { if (isInitiator) { if (pc.getRemoteDescription() != null) { // We've set our local offer and received & set the // remote // answer, so drain candidates. drainRemoteCandidates(); } } else { if (pc.getLocalDescription() == null) { // We just set the remote offer, time to create our // answer. pc.createAnswer(SDPObserver.this, sdpMediaConstraints); } else { // Sent our answer and set it as local description; // drain // candidates. drainRemoteCandidates(); } } } }); } @Override public void onCreateFailure(final String error) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { throw new RuntimeException("createSDP error: " + error); } }); } @Override public void onSetFailure(final String error) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { //throw new RuntimeException("setSDP error: " + error); } }); } private void drainRemoteCandidates() { if (queuedRemoteCandidates == null) return; for (IceCandidate candidate : queuedRemoteCandidates) { pc.addIceCandidate(candidate); } queuedRemoteCandidates = null; } } private void disconnect() { synchronized (quit[0]) { if (quit[0]) { return; } quit[0] = true; if (pc != null) { pc.dispose(); pc = null; } try { JSONObject json = new JSONObject(); json.put("type", "bye"); sendMessage(json); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } cordova.getActivity().runOnUiThread(new Runnable() { public void run() { if (localVideoView != null) { webView.removeView(localVideoView); localVideoView = null; } if (remoteVideoView != null) { webView.removeView(remoteVideoView); remoteVideoView = null; } } }); if (videoSource != null) { videoSource.dispose(); videoSource = null; } if (factory != null) { factory.dispose(); factory = null; } } try { JSONObject data = new JSONObject(); data.put("type", "__disconnected"); sendMessage(data); } catch (JSONException e) { } } // Implementation detail: bridge the VideoRenderer.Callbacks interface to the // VideoStreamsView implementation. private class VideoCallbacks implements VideoRenderer.Callbacks { private final VideoStreamsView view; private final VideoStreamsView.Endpoint stream; public VideoCallbacks( VideoStreamsView view, VideoStreamsView.Endpoint stream) { this.view = view; this.stream = stream; Log.d("CordovaLog", "VideoCallbacks"); } @Override public void setSize(final int width, final int height) { Log.d("setSize", width + " " + height); view.queueEvent(new Runnable() { public void run() { view.setSize(stream, width, height); } }); } @Override public void renderFrame(I420Frame frame) { view.queueFrame(stream, frame); } } }
package com.angcyo.uiview.widget; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.view.Gravity; import com.angcyo.uiview.R; import com.angcyo.uiview.resources.ResUtil; import com.angcyo.uiview.skin.SkinHelper; public class Button extends RTextView { public static final int DEFAULT = 1; public static final int ROUND = 2; public static final int ROUND_BORDER = 3; int mButtonStyle = DEFAULT; public Button(Context context) { this(context, null); } public Button(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Button); mButtonStyle = typedArray.getInt(R.styleable.Button_r_button_style, DEFAULT); typedArray.recycle(); initButton(); } private void initButton() { if (isInEditMode()) { setBackgroundColor(Color.BLUE); } else { if (mButtonStyle == ROUND) { setBackground(ResUtil.ripple(SkinHelper.getSkin().getThemeSubColor(), ResUtil.selector( ResUtil.createDrawable(SkinHelper.getSkin().getThemeSubColor(), 300), ResUtil.createDrawable(SkinHelper.getSkin().getThemeDarkColor(), 300) ))); } else if (mButtonStyle == ROUND_BORDER) { setBackground(ResUtil.ripple(SkinHelper.getSkin().getThemeSubColor(), ResUtil.selector( ResUtil.createDrawable(SkinHelper.getSkin().getThemeSubColor(), Color.TRANSPARENT, (int) (1 * density()), 300), ResUtil.createDrawable(SkinHelper.getSkin().getThemeDarkColor(), Color.TRANSPARENT, (int) (1 * density()), 300) ))); setTextColor(ColorStateList.valueOf(SkinHelper.getSkin().getThemeSubColor())); } else { setBackground(SkinHelper.getSkin().getThemeMaskBackgroundRoundSelector()); } } } @Override protected void initView() { super.initView(); setGravity(Gravity.CENTER); setClickable(true); setTextColor(ColorStateList.valueOf(Color.WHITE)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); if ((heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) && getPaddingTop() == 0 && getPaddingBottom() == 0) { setMeasuredDimension(getMeasuredWidth(), getResources().getDimensionPixelOffset(R.dimen.default_button_height)); } } }
package org.mwc.debrief.lite.menu; import java.awt.Dimension; import java.awt.Image; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import org.geotools.swing.JMapPane; import org.mwc.debrief.lite.DebriefLiteApp; import org.mwc.debrief.lite.map.GeoToolMapRenderer; import org.mwc.debrief.lite.util.DoSave; import org.mwc.debrief.lite.util.DoSaveAs; import org.pushingpixels.flamingo.api.common.FlamingoCommand; import org.pushingpixels.flamingo.api.common.JCommandButton; import org.pushingpixels.flamingo.api.common.JCommandMenuButton; import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon; import org.pushingpixels.flamingo.api.common.popup.JCommandPopupMenu; import org.pushingpixels.flamingo.api.common.popup.JPopupPanel; import org.pushingpixels.flamingo.api.common.popup.PopupPanelCallback; import org.pushingpixels.flamingo.api.ribbon.JRibbon; import org.pushingpixels.flamingo.api.ribbon.JRibbonBand; import org.pushingpixels.flamingo.api.ribbon.JRibbonFrame; import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority; import org.pushingpixels.flamingo.api.ribbon.RibbonTask; import Debrief.GUI.Frames.Application; import Debrief.GUI.Frames.Session; import Debrief.ReaderWriter.XML.DebriefXMLReaderWriter; import MWC.GUI.ToolParent; public class DebriefRibbonFile { private static class CopyPlotAsPNG extends AbstractAction { private static final long serialVersionUID = 1L; private final GeoToolMapRenderer mapRenderer; public CopyPlotAsPNG(final GeoToolMapRenderer _geoMapRenderer) { mapRenderer = _geoMapRenderer; } @Override public void actionPerformed(final ActionEvent e) { final JMapPane map = (JMapPane) mapRenderer.getMap(); org.mwc.debrief.lite.util.ClipboardUtils.copyToClipboard(map); } } @SuppressWarnings("unused") private static class ImportFileAction extends AbstractAction { private static final String TYPE_REP="rep"; private String importFileType; protected ImportFileAction(String type) { importFileType = type; } private static final long serialVersionUID = -804226120198968206L; @Override public void actionPerformed(final ActionEvent e) { final String initialFileLocation = DebriefLiteApp.getDefault() .getProperty(LAST_FILE_OPEN_LOCATION); final File fileToOpen ; if(TYPE_REP.equals(importFileType)) { fileToOpen = showOpenDialog(initialFileLocation, new String[] {"rep"}, "Debrief replay file (*.rep, *.dsf, *.dtf)"); } else { fileToOpen = showOpenDialog(initialFileLocation, new String[] {"dpf"}, "Debrief plot file (*.dpf)"); } if (fileToOpen != null) { if(TYPE_REP.equalsIgnoreCase(importFileType)) { DebriefLiteApp.openRepFile(fileToOpen); } else { DebriefLiteApp.openPlotFile(fileToOpen); } DebriefLiteApp.getDefault().setProperty(LAST_FILE_OPEN_LOCATION, fileToOpen.getParentFile().getAbsolutePath()); } } } private static class NewFileAction extends AbstractAction { private static final long serialVersionUID = 1L; private final JFrame _theFrame; private final Session _session; private final Runnable _doReset; private final boolean _close; public NewFileAction(final JFrame theFrame, final Session session, final Runnable doReset, final boolean close) { _theFrame = theFrame; _session = session; _doReset = doReset; _close = close; } @Override public void actionPerformed(final ActionEvent e) { // ask user whether to save, if file is dirty. if (DebriefLiteApp.isDirty()) { final int res = JOptionPane.showConfirmDialog(null, _close ? "Do you want to save the plot before closing?" : "Save changes before creating new file?"); if (res == JOptionPane.OK_OPTION) { if (DebriefLiteApp.currentFileName != null && DebriefLiteApp.currentFileName.endsWith(".rep")) { final File f = new File(DebriefLiteApp.currentFileName); final String newname = f.getName().substring(0, f.getName() .lastIndexOf(".rep")); final String newFileName = DoSaveAs.showSaveDialog(f .getParentFile(), newname); if (newFileName == null || newFileName.length() == 0) { // drop out, don't do reset. return; } DebriefLiteApp.currentFileName.replaceAll(".rep", ".dpf"); DebriefRibbonFile.saveChanges(newFileName, _session, _theFrame); } else if (DebriefLiteApp.currentFileName == null) { // ok, we have to do a save-as operation final DoSaveAs saveAs = new DoSaveAs(_session, _theFrame); saveAs.actionPerformed(e); } else { // ok, it's a DPF file. we can juse save it DebriefRibbonFile.saveChanges(DebriefLiteApp.currentFileName, _session, _theFrame); } _doReset.run(); } else if (res == JOptionPane.NO_OPTION) { _doReset.run(); } else { // do nothing } } else { _doReset.run(); } } } private static class OpenPlotAction extends AbstractAction { private static final long serialVersionUID = 1L; private final JFrame _theFrame; private final Session _session; private final Runnable _doReset; private final boolean isRepFile; public OpenPlotAction(final JFrame theFrame, final Session session, final Runnable doReset, final boolean isRep) { _theFrame = theFrame; _session = session; _doReset = doReset; isRepFile = isRep; } @Override public void actionPerformed(final ActionEvent e) { final String[] fileTypes = isRepFile ? new String[] {"rep"} : new String[] {"dpf", "xml"}; final String descr = isRepFile ? "Debrief Replay File" : "Debrief Plot Files"; if (DebriefLiteApp.isDirty()) { final int res = JOptionPane.showConfirmDialog(null, "Save changes before opening new plot?"); if (res == JOptionPane.OK_OPTION) { if (DebriefLiteApp.currentFileName != null && DebriefLiteApp.currentFileName.endsWith(".rep")) { final File f = new File(DebriefLiteApp.currentFileName); final String newname = f.getName().substring(0, f.getName() .lastIndexOf(".rep")); final String newFileName = DoSaveAs.showSaveDialog(f .getParentFile(), newname); if (newFileName == null || newFileName.length() == 0) { // drop out, don't do reset. return; } DebriefLiteApp.currentFileName.replaceAll(".rep", ".dpf"); DebriefRibbonFile.saveChanges(newFileName, _session, _theFrame); } else if (DebriefLiteApp.currentFileName == null) { // ok, we have to do a save-as operation final DoSaveAs saveAs = new DoSaveAs(_session, _theFrame); saveAs.actionPerformed(e); } else { // ok, it's a DPF file. we can juse save it DebriefRibbonFile.saveChanges(DebriefLiteApp.currentFileName, _session, _theFrame); } doFileOpen(fileTypes, descr, isRepFile, _doReset); } else if (res == JOptionPane.NO_OPTION) { doFileOpen(fileTypes, descr, isRepFile, _doReset); } else { // do nothing } } else { doFileOpen(fileTypes, descr, isRepFile, _doReset); } } } private static class SavePopupMenu extends JCommandPopupMenu { private static final long serialVersionUID = 1L; public SavePopupMenu(final Session session, final JRibbonFrame theFrame) { final Image saveImage = MenuUtils.createImage("icons/16/save.png"); final ImageWrapperResizableIcon imageIcon = ImageWrapperResizableIcon .getIcon(saveImage, new Dimension(16, 16)); final JCommandMenuButton saveButton = new JCommandMenuButton("Save", imageIcon); saveButton.getActionModel().addActionListener(new DoSave(session, theFrame)); addMenuButton(saveButton); final Image saveAsImage = MenuUtils.createImage("icons/16/save-as.png"); final ImageWrapperResizableIcon imageIcon2 = ImageWrapperResizableIcon .getIcon(saveAsImage, new Dimension(16, 16)); final JCommandMenuButton saveAsButton = new JCommandMenuButton("Save As", imageIcon2); saveAsButton.getActionModel().addActionListener(new DoSaveAs(session, theFrame)); addMenuButton(saveAsButton); } } private static final String LAST_FILE_OPEN_LOCATION = "last_fileopen_location"; public static FlamingoCommand closeButton; private static RibbonTask fileTask; protected static void addFileTab(final JRibbon ribbon, final GeoToolMapRenderer geoMapRenderer, final Session session, final Runnable resetAction) { final JRibbonBand fileMenu = new JRibbonBand("File", null); MenuUtils.addCommand("New", "icons/24/new.png", new NewFileAction(ribbon .getRibbonFrame(), session, resetAction, false), fileMenu, RibbonElementPriority.TOP); MenuUtils.addCommand("Open", "icons/24/open.png", new OpenPlotAction(ribbon .getRibbonFrame(), session, resetAction, false), fileMenu, RibbonElementPriority.TOP); final SavePopupMenu savePopup = new SavePopupMenu(session, ribbon .getRibbonFrame()); MenuUtils.addCommand("Save", "icons/24/save.png", new DoSave(session, ribbon .getRibbonFrame()), fileMenu, RibbonElementPriority.TOP, new PopupPanelCallback() { @Override public JPopupPanel getPopupPanel(final JCommandButton commandButton) { return savePopup; } }); closeButton = MenuUtils.addCommand("Close", "icons/24/close.png", new NewFileAction(ribbon.getRibbonFrame(), session, resetAction, true), fileMenu, RibbonElementPriority.TOP); closeButton.setEnabled(false); fileMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies( fileMenu)); final JRibbonBand importMenu = new JRibbonBand("Import", null); MenuUtils.addCommand("Replay", "icons/24/import.png", new ImportFileAction(ImportFileAction.TYPE_REP), importMenu, RibbonElementPriority.TOP); MenuUtils.addCommand("Plot", "icons/24/plot_file.png", new ImportFileAction(".dpf"), importMenu, RibbonElementPriority.TOP); importMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies( importMenu)); final JRibbonBand exportMenu = new JRibbonBand("Export", null); MenuUtils.addCommand("PNG", "icons/24/export_gpx.png", new CopyPlotAsPNG( geoMapRenderer), exportMenu, RibbonElementPriority.TOP); exportMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies( exportMenu)); fileMenu.setPreferredSize(new Dimension(150, 50)); importMenu.setPreferredSize(new Dimension(50, 50)); fileTask = new RibbonTask("File", fileMenu, importMenu, exportMenu); fileMenu.setPreferredSize(new Dimension(50, 50)); ribbon.addTask(fileTask); } public static void doFileOpen(final String[] fileTypes, final String descr, final boolean isRepFile, final Runnable doReset) { // load the new selected file final String initialFileLocation = DebriefLiteApp.getDefault().getProperty( LAST_FILE_OPEN_LOCATION); final File fileToOpen = showOpenDialog(initialFileLocation, fileTypes, descr); if (fileToOpen != null) { doReset.run(); if (isRepFile) { DebriefLiteApp.openRepFile(fileToOpen); } else { DebriefLiteApp.openPlotFile(fileToOpen); } DebriefLiteApp.getDefault().setProperty(LAST_FILE_OPEN_LOCATION, fileToOpen.getParentFile().getAbsolutePath()); } } public static RibbonTask getFileTask() { return fileTask; } public static void saveChanges(final String currentFileName, final Session session, final JFrame theFrame) { final File targetFile = new File(currentFileName); if ((targetFile != null && targetFile.exists() && targetFile.canWrite()) || (targetFile != null && !targetFile.exists() && targetFile .getParentFile().canWrite())) { // export to this file. // if it already exists, check with rename/cancel OutputStream stream = null; try { stream = new FileOutputStream(targetFile.getAbsolutePath()); DebriefXMLReaderWriter.exportThis(session, stream); // remember the last file save location DebriefLiteApp.getDefault().setProperty(DoSaveAs.LAST_FILE_LOCATION, targetFile.getParentFile().getAbsolutePath()); } catch (final FileNotFoundException e1) { Application.logError2(ToolParent.ERROR, "Can't find file", e1); } finally { try { stream.close(); DebriefLiteApp.currentFileName = targetFile.getAbsolutePath(); DebriefLiteApp.setDirty(false); } catch (final IOException e1) { // ignore } } } } public static File showOpenDialog(final String openDir, final String[] fileTypes, final String descr) { final JFileChooser fileChooser = new JFileChooser(); if (openDir != null) { fileChooser.setCurrentDirectory(new File(openDir)); } final FileNameExtensionFilter restrict = new FileNameExtensionFilter(descr, fileTypes); fileChooser.setFileFilter(restrict); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); final int res = fileChooser.showOpenDialog(null); if (res == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } return null; } }
package org.bimserver.geometry; public class Matrix { public static void main(String[] args) { float[] x = new float[16]; setIdentityM(x, 0); translateM(x, 0, 2, 3, 4); dump(x); } /** Temporary memory for operations that need temporary matrix data. */ private final static float[] sTemp = new float[32]; private final static double[] sTempD = new double[32]; public static void multiplyMM(float[] result, int resultOffset, float[] lhs, int lhsOffset, float[] rhs, int rhsOffset) { result[resultOffset + 0] = rhs[0] * lhs[0] + rhs[1] * lhs[4] + rhs[2] * lhs[8] + rhs[3] * lhs[12]; result[resultOffset + 1] = rhs[0] * lhs[1] + rhs[1] * lhs[5] + rhs[2] * lhs[9] + rhs[3] * lhs[13]; result[resultOffset + 2] = rhs[0] * lhs[2] + rhs[1] * lhs[6] + rhs[2] * lhs[10] + rhs[3] * lhs[14]; result[resultOffset + 3] = rhs[0] * lhs[3] + rhs[1] * lhs[7] + rhs[2] * lhs[11] + rhs[3] * lhs[15]; result[resultOffset + 4] = rhs[4] * lhs[0] + rhs[5] * lhs[4] + rhs[6] * lhs[8] + rhs[7] * lhs[12]; result[resultOffset + 5] = rhs[4] * lhs[1] + rhs[5] * lhs[5] + rhs[6] * lhs[9] + rhs[7] * lhs[13]; result[resultOffset + 6] = rhs[4] * lhs[2] + rhs[5] * lhs[6] + rhs[6] * lhs[10] + rhs[7] * lhs[14]; result[resultOffset + 7] = rhs[4] * lhs[3] + rhs[5] * lhs[7] + rhs[6] * lhs[11] + rhs[7] * lhs[15]; result[resultOffset + 8] = rhs[8] * lhs[0] + rhs[9] * lhs[4] + rhs[10] * lhs[8] + rhs[11] * lhs[12]; result[resultOffset + 9] = rhs[8] * lhs[1] + rhs[9] * lhs[5] + rhs[10] * lhs[9] + rhs[11] * lhs[13]; result[resultOffset + 10] = rhs[8] * lhs[2] + rhs[9] * lhs[6] + rhs[10] * lhs[10] + rhs[11] * lhs[14]; result[resultOffset + 11] = rhs[8] * lhs[3] + rhs[9] * lhs[7] + rhs[10] * lhs[11] + rhs[11] * lhs[15]; result[resultOffset + 12] = rhs[12] * lhs[0] + rhs[13] * lhs[4] + rhs[14] * lhs[8] + rhs[15] * lhs[12]; result[resultOffset + 13] = rhs[12] * lhs[1] + rhs[13] * lhs[5] + rhs[14] * lhs[9] + rhs[15] * lhs[13]; result[resultOffset + 14] = rhs[12] * lhs[2] + rhs[13] * lhs[6] + rhs[14] * lhs[10] + rhs[15] * lhs[14]; result[resultOffset + 15] = rhs[12] * lhs[3] + rhs[13] * lhs[7] + rhs[14] * lhs[11] + rhs[15] * lhs[15]; } public static void multiplyMM(double[] result, int resultOffset, double[] lhs, int lhsOffset, double[] rhs, int rhsOffset) { result[resultOffset + 0] = rhs[0] * lhs[0] + rhs[1] * lhs[4] + rhs[2] * lhs[8] + rhs[3] * lhs[12]; result[resultOffset + 1] = rhs[0] * lhs[1] + rhs[1] * lhs[5] + rhs[2] * lhs[9] + rhs[3] * lhs[13]; result[resultOffset + 2] = rhs[0] * lhs[2] + rhs[1] * lhs[6] + rhs[2] * lhs[10] + rhs[3] * lhs[14]; result[resultOffset + 3] = rhs[0] * lhs[3] + rhs[1] * lhs[7] + rhs[2] * lhs[11] + rhs[3] * lhs[15]; result[resultOffset + 4] = rhs[4] * lhs[0] + rhs[5] * lhs[4] + rhs[6] * lhs[8] + rhs[7] * lhs[12]; result[resultOffset + 5] = rhs[4] * lhs[1] + rhs[5] * lhs[5] + rhs[6] * lhs[9] + rhs[7] * lhs[13]; result[resultOffset + 6] = rhs[4] * lhs[2] + rhs[5] * lhs[6] + rhs[6] * lhs[10] + rhs[7] * lhs[14]; result[resultOffset + 7] = rhs[4] * lhs[3] + rhs[5] * lhs[7] + rhs[6] * lhs[11] + rhs[7] * lhs[15]; result[resultOffset + 8] = rhs[8] * lhs[0] + rhs[9] * lhs[4] + rhs[10] * lhs[8] + rhs[11] * lhs[12]; result[resultOffset + 9] = rhs[8] * lhs[1] + rhs[9] * lhs[5] + rhs[10] * lhs[9] + rhs[11] * lhs[13]; result[resultOffset + 10] = rhs[8] * lhs[2] + rhs[9] * lhs[6] + rhs[10] * lhs[10] + rhs[11] * lhs[14]; result[resultOffset + 11] = rhs[8] * lhs[3] + rhs[9] * lhs[7] + rhs[10] * lhs[11] + rhs[11] * lhs[15]; result[resultOffset + 12] = rhs[12] * lhs[0] + rhs[13] * lhs[4] + rhs[14] * lhs[8] + rhs[15] * lhs[12]; result[resultOffset + 13] = rhs[12] * lhs[1] + rhs[13] * lhs[5] + rhs[14] * lhs[9] + rhs[15] * lhs[13]; result[resultOffset + 14] = rhs[12] * lhs[2] + rhs[13] * lhs[6] + rhs[14] * lhs[10] + rhs[15] * lhs[14]; result[resultOffset + 15] = rhs[12] * lhs[3] + rhs[13] * lhs[7] + rhs[14] * lhs[11] + rhs[15] * lhs[15]; } public static float[] multiplyV(float[] transformationMatrix, float[] coordinates) { if (coordinates.length == 3) { float[] result = new float[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new float[]{coordinates[0], coordinates[1], coordinates[2], 0}, 0); return new float[]{result[0], result[1], result[2]}; } else if (coordinates.length == 4) { float[] result = new float[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new float[]{coordinates[0], coordinates[1], coordinates[2], coordinates[3]}, 0); return result; } return null; } public static double[] multiplyV(double[] transformationMatrix, double[] coordinates) { if (coordinates.length == 3) { double[] result = new double[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new double[]{coordinates[0], coordinates[1], coordinates[2], 0}, 0); return new double[]{result[0], result[1], result[2]}; } else if (coordinates.length == 4) { double[] result = new double[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new double[]{coordinates[0], coordinates[1], coordinates[2], coordinates[3]}, 0); return result; } return null; } public static void multiplyMV(float[] resultVec, int resultVecOffset, float[] lhsMat, int lhsMatOffset, float[] rhsVec, int rhsVecOffset) { resultVec[resultVecOffset + 0] = lhsMat[0] * rhsVec[0] + lhsMat[4] * rhsVec[1] + lhsMat[8] * rhsVec[2] + lhsMat[12] * rhsVec[3]; resultVec[resultVecOffset + 1] = lhsMat[1] * rhsVec[0] + lhsMat[5] * rhsVec[1] + lhsMat[9] * rhsVec[2] + lhsMat[13] * rhsVec[3]; resultVec[resultVecOffset + 2] = lhsMat[2] * rhsVec[0] + lhsMat[6] * rhsVec[1] + lhsMat[10] * rhsVec[2] + lhsMat[14] * rhsVec[3]; resultVec[resultVecOffset + 3] = lhsMat[3] * rhsVec[0] + lhsMat[7] * rhsVec[1] + lhsMat[11] * rhsVec[2] + lhsMat[15] * rhsVec[3]; } public static void multiplyMV(double[] resultVec, int resultVecOffset, double[] lhsMat, int lhsMatOffset, double[] rhsVec, int rhsVecOffset) { resultVec[resultVecOffset + 0] = lhsMat[0] * rhsVec[0] + lhsMat[4] * rhsVec[1] + lhsMat[8] * rhsVec[2] + lhsMat[12] * rhsVec[3]; resultVec[resultVecOffset + 1] = lhsMat[1] * rhsVec[0] + lhsMat[5] * rhsVec[1] + lhsMat[9] * rhsVec[2] + lhsMat[13] * rhsVec[3]; resultVec[resultVecOffset + 2] = lhsMat[2] * rhsVec[0] + lhsMat[6] * rhsVec[1] + lhsMat[10] * rhsVec[2] + lhsMat[14] * rhsVec[3]; resultVec[resultVecOffset + 3] = lhsMat[3] * rhsVec[0] + lhsMat[7] * rhsVec[1] + lhsMat[11] * rhsVec[2] + lhsMat[15] * rhsVec[3]; } /** * Transposes a 4 x 4 matrix. * * @param mTrans the array that holds the output inverted matrix * @param mTransOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. */ public static void transposeM(float[] mTrans, int mTransOffset, float[] m, int mOffset) { for (int i = 0; i < 4; i++) { int mBase = i * 4 + mOffset; mTrans[i + mTransOffset] = m[mBase]; mTrans[i + 4 + mTransOffset] = m[mBase + 1]; mTrans[i + 8 + mTransOffset] = m[mBase + 2]; mTrans[i + 12 + mTransOffset] = m[mBase + 3]; } } /** * Inverts a 4 x 4 matrix. * * @param mInv the array that holds the output inverted matrix * @param mInvOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. * @return true if the matrix could be inverted, false if it could not. */ public static boolean invertM(float[] mInv, int mInvOffset, float[] m, int mOffset) { // Invert a 4 x 4 matrix using Cramer's Rule // transpose matrix final float src0 = m[mOffset + 0]; final float src4 = m[mOffset + 1]; final float src8 = m[mOffset + 2]; final float src12 = m[mOffset + 3]; final float src1 = m[mOffset + 4]; final float src5 = m[mOffset + 5]; final float src9 = m[mOffset + 6]; final float src13 = m[mOffset + 7]; final float src2 = m[mOffset + 8]; final float src6 = m[mOffset + 9]; final float src10 = m[mOffset + 10]; final float src14 = m[mOffset + 11]; final float src3 = m[mOffset + 12]; final float src7 = m[mOffset + 13]; final float src11 = m[mOffset + 14]; final float src15 = m[mOffset + 15]; // calculate pairs for first 8 elements (cofactors) final float atmp0 = src10 * src15; final float atmp1 = src11 * src14; final float atmp2 = src9 * src15; final float atmp3 = src11 * src13; final float atmp4 = src9 * src14; final float atmp5 = src10 * src13; final float atmp6 = src8 * src15; final float atmp7 = src11 * src12; final float atmp8 = src8 * src14; final float atmp9 = src10 * src12; final float atmp10 = src8 * src13; final float atmp11 = src9 * src12; // calculate first 8 elements (cofactors) final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7) - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7); final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7) - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7); final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7) - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7); final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6) - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6); final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3) - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3); final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3) - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3); final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3) - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3); final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2) - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2); // calculate pairs for second 8 elements (cofactors) final float btmp0 = src2 * src7; final float btmp1 = src3 * src6; final float btmp2 = src1 * src7; final float btmp3 = src3 * src5; final float btmp4 = src1 * src6; final float btmp5 = src2 * src5; final float btmp6 = src0 * src7; final float btmp7 = src3 * src4; final float btmp8 = src0 * src6; final float btmp9 = src2 * src4; final float btmp10 = src0 * src5; final float btmp11 = src1 * src4; // calculate second 8 elements (cofactors) final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15) - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15); final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15) - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15); final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15) - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15); final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14) - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14); final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9 ) - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10); final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10) - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8 ); final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8 ) - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9 ); final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9 ) - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8 ); // calculate determinant final float det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3; if (det == 0.0f) { return false; } // calculate matrix inverse final float invdet = 1.0f / det; mInv[ mInvOffset] = dst0 * invdet; mInv[ 1 + mInvOffset] = dst1 * invdet; mInv[ 2 + mInvOffset] = dst2 * invdet; mInv[ 3 + mInvOffset] = dst3 * invdet; mInv[ 4 + mInvOffset] = dst4 * invdet; mInv[ 5 + mInvOffset] = dst5 * invdet; mInv[ 6 + mInvOffset] = dst6 * invdet; mInv[ 7 + mInvOffset] = dst7 * invdet; mInv[ 8 + mInvOffset] = dst8 * invdet; mInv[ 9 + mInvOffset] = dst9 * invdet; mInv[10 + mInvOffset] = dst10 * invdet; mInv[11 + mInvOffset] = dst11 * invdet; mInv[12 + mInvOffset] = dst12 * invdet; mInv[13 + mInvOffset] = dst13 * invdet; mInv[14 + mInvOffset] = dst14 * invdet; mInv[15 + mInvOffset] = dst15 * invdet; return true; } /** * Computes an orthographic projection matrix. * * @param m returns the result * @param mOffset * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void orthoM(float[] m, int mOffset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (bottom == top) { throw new IllegalArgumentException("bottom == top"); } if (near == far) { throw new IllegalArgumentException("near == far"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (far - near); final float x = 2.0f * (r_width); final float y = 2.0f * (r_height); final float z = -2.0f * (r_depth); final float tx = -(right + left) * r_width; final float ty = -(top + bottom) * r_height; final float tz = -(far + near) * r_depth; m[mOffset + 0] = x; m[mOffset + 5] = y; m[mOffset +10] = z; m[mOffset +12] = tx; m[mOffset +13] = ty; m[mOffset +14] = tz; m[mOffset +15] = 1.0f; m[mOffset + 1] = 0.0f; m[mOffset + 2] = 0.0f; m[mOffset + 3] = 0.0f; m[mOffset + 4] = 0.0f; m[mOffset + 6] = 0.0f; m[mOffset + 7] = 0.0f; m[mOffset + 8] = 0.0f; m[mOffset + 9] = 0.0f; m[mOffset + 11] = 0.0f; } /** * Define a projection matrix in terms of six clip planes * @param m the float array that holds the perspective matrix * @param offset the offset into float array m where the perspective * matrix data is written * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void frustumM(float[] m, int offset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (top == bottom) { throw new IllegalArgumentException("top == bottom"); } if (near == far) { throw new IllegalArgumentException("near == far"); } if (near <= 0.0f) { throw new IllegalArgumentException("near <= 0.0f"); } if (far <= 0.0f) { throw new IllegalArgumentException("far <= 0.0f"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (near - far); final float x = 2.0f * (near * r_width); final float y = 2.0f * (near * r_height); final float A = (right + left) * r_width; final float B = (top + bottom) * r_height; final float C = (far + near) * r_depth; final float D = 2.0f * (far * near * r_depth); m[offset + 0] = x; m[offset + 5] = y; m[offset + 8] = A; m[offset + 9] = B; m[offset + 10] = C; m[offset + 14] = D; m[offset + 11] = -1.0f; m[offset + 1] = 0.0f; m[offset + 2] = 0.0f; m[offset + 3] = 0.0f; m[offset + 4] = 0.0f; m[offset + 6] = 0.0f; m[offset + 7] = 0.0f; m[offset + 12] = 0.0f; m[offset + 13] = 0.0f; m[offset + 15] = 0.0f; } /** * Define a projection matrix in terms of a field of view angle, an * aspect ratio, and z clip planes * @param m the float array that holds the perspective matrix * @param offset the offset into float array m where the perspective * matrix data is written * @param fovy field of view in y direction, in degrees * @param aspect width to height aspect ratio of the viewport * @param zNear * @param zFar */ public static void perspectiveM(float[] m, int offset, float fovy, float aspect, float zNear, float zFar) { float f = 1.0f / (float) Math.tan(fovy * (Math.PI / 360.0)); float rangeReciprocal = 1.0f / (zNear - zFar); m[offset + 0] = f / aspect; m[offset + 1] = 0.0f; m[offset + 2] = 0.0f; m[offset + 3] = 0.0f; m[offset + 4] = 0.0f; m[offset + 5] = f; m[offset + 6] = 0.0f; m[offset + 7] = 0.0f; m[offset + 8] = 0.0f; m[offset + 9] = 0.0f; m[offset + 10] = (zFar + zNear) * rangeReciprocal; m[offset + 11] = -1.0f; m[offset + 12] = 0.0f; m[offset + 13] = 0.0f; m[offset + 14] = 2.0f * zFar * zNear * rangeReciprocal; m[offset + 15] = 0.0f; } /** * Computes the length of a vector * * @param x x coordinate of a vector * @param y y coordinate of a vector * @param z z coordinate of a vector * @return the length of a vector */ public static float length(float x, float y, float z) { return (float) Math.sqrt(x * x + y * y + z * z); } public static double length(double x, double y, double z) { return Math.sqrt(x * x + y * y + z * z); } /** * Sets matrix m to the identity matrix. * @param sm returns the result * @param smOffset index into sm where the result matrix starts */ public static void setIdentityM(float[] sm, int smOffset) { for (int i=0 ; i<16 ; i++) { sm[smOffset + i] = 0; } for(int i = 0; i < 16; i += 5) { sm[smOffset + i] = 1.0f; } } /** * Sets matrix m to the identity matrix. * @param sm returns the result * @param smOffset index into sm where the result matrix starts */ public static void setIdentityM(double[] sm, int smOffset) { for (int i=0 ; i<16 ; i++) { sm[smOffset + i] = 0; } for(int i = 0; i < 16; i += 5) { sm[smOffset + i] = 1.0; } } /** * Scales matrix m by x, y, and z, putting the result in sm * @param sm returns the result * @param smOffset index into sm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void scaleM(float[] sm, int smOffset, float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int smi = smOffset + i; int mi = mOffset + i; sm[ smi] = m[ mi] * x; sm[ 4 + smi] = m[ 4 + mi] * y; sm[ 8 + smi] = m[ 8 + mi] * z; sm[12 + smi] = m[12 + mi]; } } /** * Scales matrix m in place by sx, sy, and sz * @param m matrix to scale * @param mOffset index into m where the matrix starts * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void scaleM(float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int mi = mOffset + i; m[ mi] *= x; m[ 4 + mi] *= y; m[ 8 + mi] *= z; } } public static void scaleM(double[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int mi = mOffset + i; m[ mi] *= x; m[ 4 + mi] *= y; m[ 8 + mi] *= z; } } /** * Translates matrix m by x, y, and z, putting the result in tm * @param tm returns the result * @param tmOffset index into sm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param x translation factor x * @param y translation factor y * @param z translation factor z */ public static void translateM(float[] tm, int tmOffset, float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<12 ; i++) { tm[tmOffset + i] = m[mOffset + i]; } for (int i=0 ; i<4 ; i++) { int tmi = tmOffset + i; int mi = mOffset + i; tm[12 + tmi] = m[mi] * x + m[4 + mi] * y + m[8 + mi] * z + m[12 + mi]; } } /** * Translates matrix m by x, y, and z in place. * @param m matrix * @param mOffset index into m where the matrix starts * @param x translation factor x * @param y translation factor y * @param z translation factor z */ public static void translateM( float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int mi = mOffset + i; m[12 + mi] += m[mi] * x + m[4 + mi] * y + m[8 + mi] * z; } } /** * Rotates matrix m by angle a (in degrees) around the axis (x, y, z) * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void rotateM(float[] rm, int rmOffset, float[] m, int mOffset, float a, float x, float y, float z) { synchronized(sTemp) { setRotateM(sTemp, 0, a, x, y, z); multiplyMM(rm, rmOffset, m, mOffset, sTemp, 0); } } public static void rotateM(double[] rm, int rmOffset, double[] m, int mOffset, double a, double x, double y, double z) { synchronized(sTempD) { setRotateM(sTempD, 0, a, x, y, z); multiplyMM(rm, rmOffset, m, mOffset, sTempD, 0); } } /** * Rotates matrix m in place by angle a (in degrees) * around the axis (x, y, z) * @param m source matrix * @param mOffset index into m where the matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void rotateM(float[] m, int mOffset, float a, float x, float y, float z) { synchronized(sTemp) { setRotateM(sTemp, 0, a, x, y, z); multiplyMM(sTemp, 16, m, mOffset, sTemp, 0); System.arraycopy(sTemp, 16, m, mOffset, 16); } } public static void rotateM(double[] m, int mOffset, double a, double x, double y, double z) { synchronized(sTempD) { setRotateM(sTempD, 0, a, x, y, z); multiplyMM(sTempD, 16, m, mOffset, sTempD, 0); System.arraycopy(sTempD, 16, m, mOffset, 16); } } /** * Rotates matrix m by angle a (in degrees) around the axis (x, y, z) * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void setRotateM(float[] rm, int rmOffset, float a, float x, float y, float z) { rm[rmOffset + 3] = 0; rm[rmOffset + 7] = 0; rm[rmOffset + 11]= 0; rm[rmOffset + 12]= 0; rm[rmOffset + 13]= 0; rm[rmOffset + 14]= 0; rm[rmOffset + 15]= 1; a *= (float) (Math.PI / 180.0f); float s = (float) Math.sin(a); float c = (float) Math.cos(a); if (1.0f == x && 0.0f == y && 0.0f == z) { rm[rmOffset + 5] = c; rm[rmOffset + 10]= c; rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 0] = 1; } else if (0.0f == x && 1.0f == y && 0.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 10]= c; rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 5] = 1; } else if (0.0f == x && 0.0f == y && 1.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 5] = c; rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s; rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 10]= 1; } else { float len = length(x, y, z); if (1.0f != len) { float recipLen = 1.0f / len; x *= recipLen; y *= recipLen; z *= recipLen; } float nc = 1.0f - c; float xy = x * y; float yz = y * z; float zx = z * x; float xs = x * s; float ys = y * s; float zs = z * s; rm[rmOffset + 0] = x*x*nc + c; rm[rmOffset + 4] = xy*nc - zs; rm[rmOffset + 8] = zx*nc + ys; rm[rmOffset + 1] = xy*nc + zs; rm[rmOffset + 5] = y*y*nc + c; rm[rmOffset + 9] = yz*nc - xs; rm[rmOffset + 2] = zx*nc - ys; rm[rmOffset + 6] = yz*nc + xs; rm[rmOffset + 10] = z*z*nc + c; } } public static void setRotateM(double[] rm, int rmOffset, double a, double x, double y, double z) { rm[rmOffset + 3] = 0; rm[rmOffset + 7] = 0; rm[rmOffset + 11]= 0; rm[rmOffset + 12]= 0; rm[rmOffset + 13]= 0; rm[rmOffset + 14]= 0; rm[rmOffset + 15]= 1; a *= (double) (Math.PI / 180.0f); double s = (float) Math.sin(a); double c = (float) Math.cos(a); if (1.0f == x && 0.0f == y && 0.0f == z) { rm[rmOffset + 5] = c; rm[rmOffset + 10]= c; rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 0] = 1; } else if (0.0f == x && 1.0f == y && 0.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 10]= c; rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 5] = 1; } else if (0.0f == x && 0.0f == y && 1.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 5] = c; rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s; rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 10]= 1; } else { double len = length(x, y, z); if (1.0f != len) { double recipLen = 1.0f / len; x *= recipLen; y *= recipLen; z *= recipLen; } double nc = 1.0f - c; double xy = x * y; double yz = y * z; double zx = z * x; double xs = x * s; double ys = y * s; double zs = z * s; rm[rmOffset + 0] = x*x*nc + c; rm[rmOffset + 4] = xy*nc - zs; rm[rmOffset + 8] = zx*nc + ys; rm[rmOffset + 1] = xy*nc + zs; rm[rmOffset + 5] = y*y*nc + c; rm[rmOffset + 9] = yz*nc - xs; rm[rmOffset + 2] = zx*nc - ys; rm[rmOffset + 6] = yz*nc + xs; rm[rmOffset + 10] = z*z*nc + c; } } /** * Converts Euler angles to a rotation matrix * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param x angle of rotation, in degrees * @param y angle of rotation, in degrees * @param z angle of rotation, in degrees */ public static void setRotateEulerM(float[] rm, int rmOffset, float x, float y, float z) { x *= (float) (Math.PI / 180.0f); y *= (float) (Math.PI / 180.0f); z *= (float) (Math.PI / 180.0f); float cx = (float) Math.cos(x); float sx = (float) Math.sin(x); float cy = (float) Math.cos(y); float sy = (float) Math.sin(y); float cz = (float) Math.cos(z); float sz = (float) Math.sin(z); float cxsy = cx * sy; float sxsy = sx * sy; rm[rmOffset + 0] = cy * cz; rm[rmOffset + 1] = -cy * sz; rm[rmOffset + 2] = sy; rm[rmOffset + 3] = 0.0f; rm[rmOffset + 4] = cxsy * cz + cx * sz; rm[rmOffset + 5] = -cxsy * sz + cx * cz; rm[rmOffset + 6] = -sx * cy; rm[rmOffset + 7] = 0.0f; rm[rmOffset + 8] = -sxsy * cz + sx * sz; rm[rmOffset + 9] = sxsy * sz + sx * cz; rm[rmOffset + 10] = cx * cy; rm[rmOffset + 11] = 0.0f; rm[rmOffset + 12] = 0.0f; rm[rmOffset + 13] = 0.0f; rm[rmOffset + 14] = 0.0f; rm[rmOffset + 15] = 1.0f; } /** * Define a viewing transformation in terms of an eye point, a center of * view, and an up vector. * * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param eyeX eye point X * @param eyeY eye point Y * @param eyeZ eye point Z * @param centerX center of view X * @param centerY center of view Y * @param centerZ center of view Z * @param upX up vector X * @param upY up vector Y * @param upZ up vector Z */ public static void setLookAtM(float[] rm, int rmOffset, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // See the OpenGL GLUT documentation for gluLookAt for a description // of the algorithm. We implement it in a straightforward way: float fx = centerX - eyeX; float fy = centerY - eyeY; float fz = centerZ - eyeZ; // Normalize f float rlf = 1.0f / Matrix.length(fx, fy, fz); fx *= rlf; fy *= rlf; fz *= rlf; // compute s = f x up (x means "cross product") float sx = fy * upZ - fz * upY; float sy = fz * upX - fx * upZ; float sz = fx * upY - fy * upX; // and normalize s float rls = 1.0f / Matrix.length(sx, sy, sz); sx *= rls; sy *= rls; sz *= rls; // compute u = s x f float ux = sy * fz - sz * fy; float uy = sz * fx - sx * fz; float uz = sx * fy - sy * fx; rm[rmOffset + 0] = sx; rm[rmOffset + 1] = ux; rm[rmOffset + 2] = -fx; rm[rmOffset + 3] = 0.0f; rm[rmOffset + 4] = sy; rm[rmOffset + 5] = uy; rm[rmOffset + 6] = -fy; rm[rmOffset + 7] = 0.0f; rm[rmOffset + 8] = sz; rm[rmOffset + 9] = uz; rm[rmOffset + 10] = -fz; rm[rmOffset + 11] = 0.0f; rm[rmOffset + 12] = 0.0f; rm[rmOffset + 13] = 0.0f; rm[rmOffset + 14] = 0.0f; rm[rmOffset + 15] = 1.0f; translateM(rm, rmOffset, -eyeX, -eyeY, -eyeZ); } public static void dump(float[] result) { for (int c=0; c<4; c++) { for (int r=0; r<4; r++) { System.out.print(result[r * 4 + c] + (r == 3 ? "" : ", ")); } System.out.println(); } } public static void copy(float[] mModelMatrix, float[] mModelMatrix2) { System.arraycopy(mModelMatrix, 0, mModelMatrix2, 0, mModelMatrix.length); } public static float[] changeOrientation(float[] input) { float[] result = new float[16]; result[0] = input[0]; result[1] = input[4]; result[2] = input[8]; result[3] = input[12]; result[4] = input[1]; result[5] = input[5]; result[6] = input[9]; result[7] = input[13]; result[8] = input[2]; result[9] = input[6]; result[10] = input[10]; result[11] = input[14]; result[12] = input[3]; result[13] = input[7]; result[14] = input[11]; result[15] = input[15]; return result; } public static double[] changeOrientation(double[] input) { double[] result = new double[16]; result[0] = input[0]; result[1] = input[4]; result[2] = input[8]; result[3] = input[12]; result[4] = input[1]; result[5] = input[5]; result[6] = input[9]; result[7] = input[13]; result[8] = input[2]; result[9] = input[6]; result[10] = input[10]; result[11] = input[14]; result[12] = input[3]; result[13] = input[7]; result[14] = input[11]; result[15] = input[15]; return result; } }
package markehme.factionsplus.config; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.Scanner; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import com.massivecraft.factions.entity.Faction; import com.massivecraft.factions.entity.FactionColl; import com.massivecraft.factions.entity.FactionColls; import com.massivecraft.massivecore.ps.PS; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.Utilities; import markehme.factionsplus.MCore.FactionData; import markehme.factionsplus.MCore.FactionDataColls; /** * This entire class is related to migrating data from the old systems (0.6) to the new * systems used by FactionsPlus. This is the only class that ignores deprecation notices * as it is the only class that should be accessing OldConfig. * @author markhughes * */ @SuppressWarnings("deprecation") public class OldMigrate { /** * At the end of migration the config file moves to config.yml.migrated, so * if the old config exists then it hasn't been migrated. * @return */ public boolean shouldMigrate() { return(OldConfig.fileConfig.exists()); } private static void msg(String m) { FactionsPlus.tellConsole("[Migration] " + m); } /** * Migrates all the fData */ public void migrateDatabase() { // Load the old configuration OldConfig.init(); OldConfig.reload(); for(FactionColl fColl : FactionColls.get().getColls()) { for(String id : fColl.getIds()) { Faction faction = fColl.get(id); msg(""); msg("[Faction] " + faction.getName() + " (" + faction.getId() + ")"); msg("[Faction] Migration starting for this faction"); FactionData fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); if(fData == null) { FactionDataColls.get().getForUniverse(faction.getUniverse()).create(); msg("[Faction] [FData] FactionData file created."); fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); } else { msg("[Faction] [FData] FactionData file already exists, moving on."); } File fileAnnouncementFile = new File(OldConfig.folderAnnouncements, faction.getId()); if(fileAnnouncementFile.exists()) { try { fData.announcement = (Utilities.readFileAsString(fileAnnouncementFile)).trim(); msg("[Faction] [Announcement] Announcement Migrated: " + fData.announcement); } catch (Exception e) { msg("[Faction] [Announcement] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for this announcement in this Faction" ); e.printStackTrace(); } } else { msg("[Faction] [Announcement] No announcement data to migrate, moving on."); } File jailLocationFile = new File(OldConfig.folderJails, "loc." + faction.getId()); // Check for a jail location if(!jailLocationFile.exists()) { // If theres no jail location, then theres also no jailed players msg("[Faction] [Jail] No jail location set, moving on."); } else { // Read the old database information String locationData[] = Utilities.readFileAsString(jailLocationFile).split(":"); Location jailLocation = new Location(Bukkit.getWorld(locationData[4]), Double.valueOf(locationData[0]), Double.valueOf(locationData[1]), Double.valueOf(locationData[2])); // Create the PS version PS psJailLocation = PS.valueOf(jailLocation); // Store the location in our fData object fData.jailLocation = psJailLocation; msg("[Faction] [Jail] Jail location found and moved to x: " + locationData[0]+", y: " + locationData[1] + ", z: " + locationData[2] + ", in world: " + locationData[4]); // TODO: read jailed players (since a jail has been set there could potentially be jailed players) } File warpsFile = new File(OldConfig.folderWarps, faction.getId()); if(!warpsFile.exists()) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); } else { FileInputStream fis = null; try { fis = new FileInputStream(new File(OldConfig.folderWarps, faction.getId())); int b = fis.read(); if(b == -1) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); fis.close(); } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for the warps in this Faction"); fis = null; e.printStackTrace(); } finally { if(null != fis) { try { fis.close(); } catch(Exception e) { e.printStackTrace(); } } } Scanner scanner = null; FileReader fr = null; String warpData = ""; try { fr = new FileReader(warpsFile); scanner = new Scanner(fr); while(scanner.hasNextLine()) { warpData = scanner.nextLine(); if(!warpData.trim().isEmpty()) { String[] items = warpData.split(":"); if (items.length > 0) { // is warp data // TODO: convert } } else { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); } } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Error reading warp, last data: " + warpData); e.printStackTrace(); } finally { if(null != scanner) { scanner.close(); } if(null != fr) { try { fr.close(); } catch (Exception e) { e.printStackTrace(); } } } } } } // Migration finished - so we no longer need to use the database OldConfig.fileConfig.renameTo(new File( OldConfig.folderBase, "config_disabled.yml" )); OldConfig.deInit(); } public void deIntOld() { OldConfig.deInit(); } }
package net.lucenews.controller; import java.util.*; import java.io.*; import net.lucenews.*; import net.lucenews.model.*; import net.lucenews.model.exception.*; import net.lucenews.view.*; import net.lucenews.atom.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.*; import org.xml.sax.*; import org.apache.lucene.document.Field; import org.apache.lucene.index.*; import org.apache.lucene.search.*; public class IndexController extends Controller { /** * Deletes an index. * * @param c The context * @throws IndicesNotFoundException * @throws InvalidActionException * @throws IOException */ public static void doDelete (LuceneContext c) throws TransformerException, ParserConfigurationException, IndicesNotFoundException, IllegalActionException, IOException, InsufficientDataException { LuceneWebService service = c.service(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest req = c.req(); LuceneResponse res = c.res(); LuceneIndex[] indices = manager.getIndices( req.getIndexNames() ); StringBuffer indexNamesBuffer = new StringBuffer(); boolean deleted = false; // Delete each index for( int i = 0; i < indices.length; i++ ) { LuceneIndex index = indices[ i ]; if( !index.delete() ) throw new IOException( "Index '" + index.getName() + "' could not be deleted." ); deleted = true; if( i > 0 ) indexNamesBuffer.append( "," ); indexNamesBuffer.append( index.getName() ); } if( deleted ) res.addHeader( "Location", service.getIndexURL( req, indexNamesBuffer.toString() ) ); else throw new InsufficientDataException( "No indices to be deleted" ); XMLController.acknowledge( c ); } /** * Displays basic information regarding the index. * * @param c The context * @throws ParserConfigurationException * @throws InvalidIdentifierException * @throws DocumentNotFoundException * @throws IndicesNotFoundException * @throws ParserConfigurationException * @throws TransformerException * @throws IOException * @throws DocumentAlreadyExistsException */ public static void doGet (LuceneContext c) throws ParserConfigurationException, InvalidIdentifierException, DocumentNotFoundException, IndicesNotFoundException, ParserConfigurationException, TransformerException, IOException, DocumentAlreadyExistsException, InsufficientDataException { LuceneWebService service = c.service(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest req = c.req(); LuceneResponse res = c.res(); AtomView.process( c, asFeed( c ) ); } /** * Updates an index * * @param c The context * @throws IndicesNotFoundException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws LuceneException * @throws AtomParseException */ public static void doPut (LuceneContext c) throws IndicesNotFoundException, ParserConfigurationException, SAXException, IOException, LuceneException, TransformerException, ParserConfigurationException, AtomParseException { LuceneWebService service = c.service(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest req = c.req(); LuceneResponse res = c.res(); Entry[] entries = req.getEntries(); StringBuffer indexNamesBuffer = new StringBuffer(); boolean updated = false; // For each index... for( int i = 0; i < entries.length; i++ ) { Entry entry = entries[ i ]; String name = entry.getTitle(); if( !req.hasIndexName( name ) ) throw new LuceneException( "Index '" + name + "' not mentioned in URL" ); Properties properties = XOXOController.asProperties( entry ); LuceneIndex index = manager.getIndex( name ); index.setProperties( properties ); updated = true; if( i > 0 ) indexNamesBuffer.append( "," ); indexNamesBuffer.append( index.getName() ); } if( updated ) res.addHeader( "Location", service.getIndexURL( req, indexNamesBuffer.toString() ) ); XMLController.acknowledge( c ); } /** * Adds documents. * * @param c The context * @throws TransformerException * @throws DocumentsAlreadyExistException * @throws IndicesNotFoundException * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws LuceneException * @throws AtomParseException */ public static void doPost (LuceneContext c) throws IllegalActionException, TransformerException, DocumentsAlreadyExistException, IndicesNotFoundException, ParserConfigurationException, IOException, SAXException, LuceneException, AtomParseException { LuceneWebService service = c.service(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest req = c.req(); LuceneResponse res = c.res(); LuceneIndex[] indices = manager.getIndices( req.getIndexNames() ); LuceneDocument[] documents = req.getLuceneDocuments(); // Buffers for header location construction StringBuffer indexNamesBuffer = new StringBuffer(); StringBuffer documentIDsBuffer = new StringBuffer(); // For each index... for( int i = 0; i < indices.length; i++ ) { LuceneIndex index = indices[ i ]; if( i > 0 ) indexNamesBuffer.append( "," ); indexNamesBuffer.append( index.getName() ); // For each document... for( int j = 0; j < documents.length; j++ ) { LuceneDocument document = documents[ j ]; index.addDocument( document ); if( i == 0 ) { if( j > 0 ) documentIDsBuffer.append( "," ); documentIDsBuffer.append( index.getIdentifier( document ) ); } res.setStatus( res.SC_CREATED ); } } String indexNames = indexNamesBuffer.toString(); String documentIDs = documentIDsBuffer.toString(); if( res.getStatus() == res.SC_CREATED ) res.addHeader( "Location", service.getDocumentURL( req, indexNames, documentIDs ) ); else throw new InsufficientDataException( "No documents to be added" ); XMLController.acknowledge( c ); } /** * Transforms the currently selected index into an Atom feed. * Feed includes the most recently modified documents. * * * TO DO: This thing only tolerates one index, due to * performance/complexity issues. If anyone can * come up with an algorithm to efficiently display the * most recently modified documents across multiple * indices (WHILE BEING ABLE TO PROPERLY ASSOCIATE * EACH DOCUMENT WITH ITS RESPECTIVE INDEX), please * feel free to improve this. * * @param c The context * @return An Atom feed * @throws IndexNotFoundException * @throws ParserConfigurationException * @throws TransformerException * @throws IOException */ public static Feed asFeed (LuceneContext c) throws IndicesNotFoundException, IndexNotFoundException, ParserConfigurationException, TransformerException, IOException, InsufficientDataException { LuceneWebService service = c.service(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest req = c.req(); LuceneResponse res = c.res(); // We're not accepting multiple indices for this page // as of the time being. It causes too many performance // headaches. The following line will throw an exception // if many indices have been specified. Enjoy! //LuceneIndex index = manager.getIndex( req.getIndexName() ); LuceneIndex[] indices = manager.getIndices( req.getIndexNames() ); /** * Feed */ Feed feed = new Feed(); // Title //feed.setTitle( index.getTitle() ); //feed.setID( service.getIndexURL( req, index ) ); // Updated feed.setUpdated( Calendar.getInstance() ); // Author //if( index.hasAuthor() ) // feed.addAuthor( new Author( index.getAuthor() ) ); //else // feed.addAuthor( new Author( service.getTitle() ) ); // Link //feed.addLink( new Link( req.getLocation(), "self", "application/atom+xml" ) ); // This is critical //if( !index.hasUpdatedField() ) // return feed; //IndexReader reader = index.getIndexReader(); Limiter limiter = req.getLimiter(); //limiter.setTotalEntries( reader.numDocs() ); //if( limiter.getFirst() == null || limiter.getLast() == null ) // return feed; LuceneMultiSearcher searcher = null; IndexSearcher[] searchers = new IndexSearcher[ indices.length ]; for( int i = 0; i < indices.length; i++ ) searchers[ i ] = indices[ i ].getIndexSearcher(); searcher = new LuceneMultiSearcher( searchers, "searcherIndex" ); Query query = new MatchAllDocsQuery(); Hits hits = searcher.search( query, new Sort( new SortField( "updated", SortField.STRING, true ) ) ); feed.setTitle( hits.length() + " total hits" ); limiter.setTotalEntries( hits.length() ); HitsIterator iterator = new HitsIterator( hits, limiter ); while( iterator.hasNext() ) { LuceneDocument document = iterator.next(); feed.addEntry( DocumentController.asEntry( c, indices[ Integer.valueOf( document.get("searcherIndex") ) ], document ) ); } if( limiter instanceof Pager ) { Pager pager = (Pager) limiter; String qs = req.getQueryStringExcluding( "page" ); if( pager.getFirstPage() != null ) feed.addLink( new Link( req.getRequestURL() + LuceneRequest.getQueryStringWithParameter( qs, "page", pager.getFirstPage() ), "first", "application/atom+xml" ) ); if( pager.getPreviousPage() != null ) feed.addLink( new Link( req.getRequestURL() + LuceneRequest.getQueryStringWithParameter( qs, "page", pager.getPreviousPage() ), "previous", "application/atom+xml" ) ); if( pager.getNextPage() != null ) feed.addLink( new Link( req.getRequestURL() + LuceneRequest.getQueryStringWithParameter( qs, "page", pager.getNextPage() ), "next", "application/atom+xml" ) ); if( pager.getLastPage() != null ) feed.addLink( new Link( req.getRequestURL() + LuceneRequest.getQueryStringWithParameter( qs, "page", pager.getLastPage() ), "last", "application/atom+xml" ) ); } return feed; } }
package nonregressiontest.nfe.servicecrash; import nonregressiontest.descriptor.defaultnodes.TestNodes; import org.apache.log4j.Logger; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.exceptions.NonFunctionalException; import org.objectweb.proactive.core.mop.MethodCall; import testsuite.test.FunctionalTest; /** * @author agenoud * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class Test extends FunctionalTest { // logger for NFE mechanism public static Logger loggerNFE = Logger.getLogger("NFE"); /** An active object on the same VM */ A sameVM; /** An active object on a different but local VM */ A localVM; /** An active object on a remote VM */ A remoteVM; /** * Result from the remote method call */ Integer resultServeRequest = null; /** * Constructor for Test. */ public Test() { super("NFE Service Failed TEST", "Test that service exception are correctly signaled to caller and callee"); } /** * @see testsuite.test.AbstractTest#initTest() */ public void initTest() throws Exception { } /** * @see testsuite.test.AbstractTest#preConditions() */ public boolean preConditions() throws Exception { return true; } /** * @see testsuite.test.FunctionalTest#action() */ public void action() throws Exception { remoteVM = (A) ProActive.newActive(A.class.getName(), new Object[] { "remoteVM" }, TestNodes.getRemoteVMNode()); // Construct a fake method call to serveRequest to create a service exception Object[] param = {new Integer(0)}; MethodCall methodCall = new MethodCall(A.class.getMethod("serveRequestTest", null), param); try { resultServeRequest = (Integer) ((org.objectweb.proactive.core.mop.StubObject) remoteVM).getProxy().reify(methodCall); //remoteVM.serveRequestTest(); } catch (NonFunctionalException e) { resultServeRequest = remoteVM.serveRequestTest(); //System.out.println("ServeException"); } catch (Throwable t) { //System.out.println(t); loggerNFE.warn("*** ERROR when calling erroneous methodcall " + t.getMessage()); resultServeRequest = new Integer(-1); //System.out.println("Throwable"); } } /** * @see testsuite.test.AbstractTest#postConditions() */ public boolean postConditions() throws Exception { return (resultServeRequest.intValue() == 0); } /** * @see testsuite.test.AbstractTest#endTest() */ public void endTest() throws Exception { } }
// This file is part of the "OPeNDAP Web Coverage Service Project." // Authors: // Haibo Liu <haibo@iri.columbia.edu> // Nathan David Potter <ndp@opendap.org> // M. Benno Blumenthal <benno@iri.columbia.edu> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. package opendap.semantics.IRISail; import org.openrdf.model.*; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.rio.ntriples.NTriplesWriter; import org.openrdf.rio.trig.TriGWriter; import org.openrdf.rio.trix.TriXWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class RepositoryOps { private static Logger log = LoggerFactory.getLogger(RepositoryOps.class); public static boolean flushRepositoryOnDrop = true; /** * Remove the startingpoint statement from the repository. * @param repo * @param startingPointUrls */ public static void dropStartingPoints(Repository repo, Vector<String> startingPointUrls) { RepositoryConnection con = null; ValueFactory valueFactory; try { con = repo.getConnection(); valueFactory = repo.getValueFactory(); RepositoryOps.dropStartingPoints(con, valueFactory, startingPointUrls); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } } /** * Remove the startingpoint statement from the repository. * @param con-An open connection to the repository from which the staring points will be dropped. * @param valueFactory-A ValueFactory object for making URI and Name valued objects. * @param startingPointUrls-A list of starting point URLs to drop from the repository. */ public static void dropStartingPoints(RepositoryConnection con, ValueFactory valueFactory, Vector<String> startingPointUrls) { URI startingPointValue; URI isa = valueFactory.createURI(Terms.rdfType); URI startingPointsContext = valueFactory.createURI(Terms.startingPointsContextUri); URI startingPointType = valueFactory.createURI(Terms.startingPointContextUri); try { for (String startingPoint : startingPointUrls) { startingPointValue = valueFactory.createURI(startingPoint); con.remove(startingPointValue, isa, startingPointType, startingPointsContext); log.info("Removed starting point " + startingPoint + " from the repository. (N-Triple: <" + startingPointValue + "> <" + isa + "> " + "<" + startingPointType + "> " + "<" + startingPointsContext + "> )"); } con.commit(); } catch (RepositoryException e) { log.error("In addStartingPoints, caught an RepositoryException! Msg: " + e.getMessage()); } } /** * Add startingpoint statements into the repository. * @param repo * @param startingPointUrls */ public static void addStartingPoints(Repository repo, Vector<String> startingPointUrls) { RepositoryConnection con = null; ValueFactory valueFactory; try { con = repo.getConnection(); valueFactory = repo.getValueFactory(); addStartingPoints(con, valueFactory, startingPointUrls); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } } /** * Adds the passed list of starting points to the repository. * * * * @param con * @param valueFactory * @param startingPointUrls */ public static void addStartingPoints(RepositoryConnection con, ValueFactory valueFactory, Vector<String> startingPointUrls) { log.debug("Adding StartingPoints..."); for (String importURL : startingPointUrls) { addStartingPoint(con, valueFactory, importURL); } } /** * Test if a startingpoint is alread in the repository. Return true if it is already in. * @param con * @param startingPointUrl * @return * @throws RepositoryException * @throws MalformedQueryException * @throws QueryEvaluationException */ public static boolean startingPointExists( RepositoryConnection con, String startingPointUrl) throws RepositoryException, MalformedQueryException, QueryEvaluationException{ TupleQueryResult result; boolean hasInternalStaringPoint = false; String queryString = "SELECT doc " + "FROM {doc} rdf:type {rdfcache:"+Terms.startingPointType +"} " + "WHERE doc = <" + startingPointUrl + "> " + "USING NAMESPACE " + "rdfcache = <"+ Terms.rdfCacheNamespace+">"; log.debug("queryStartingPoints: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,queryString); result = tupleQuery.evaluate(); if (result.hasNext()){ //has internal starting point hasInternalStaringPoint = true; } return hasInternalStaringPoint; } /** * Add startingPoint statement into the repository. * @param repo * @param startingPointUrl */ public static void addStartingPoint(Repository repo, String startingPointUrl) { RepositoryConnection con = null; ValueFactory valueFactory; try { con = repo.getConnection(); valueFactory = repo.getValueFactory(); addStartingPoint(con, valueFactory, startingPointUrl); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } } /** * Adds the passed starting point to the repository. * * * @param con * @param valueFactory * @param startingPoint */ public static void addStartingPoint(RepositoryConnection con, ValueFactory valueFactory, String startingPoint) { URI startingPointUri; URI isa = valueFactory.createURI(Terms.rdfType); URI startingPointsContext = valueFactory.createURI(Terms.startingPointsContextUri); URI startingPointContext = valueFactory.createURI(Terms.startingPointContextUri); try { if (startingPoint.startsWith("http://")) { //make sure it's a url and read it in startingPointUri = valueFactory.createURI(startingPoint); con.add(startingPointUri, isa, startingPointContext, startingPointsContext); log.info("addStartingPoint(): Added StartingPoint to the repository <" + startingPointUri + "> <" + isa + "> " + "<" + startingPointContext + "> " + "<" + startingPointsContext + "> "); } else { log.error("addStartingPoint() - The startingPoint '"+startingPoint+"' does not appear to by a URL, skipping."); } } catch (RepositoryException e) { log.error("addStartingPoint(): Caught an RepositoryException! Msg: " + e.getMessage()); } } /** * * @param repo * @param startingPointUrls * @return */ public static Vector<String> findChangedStartingPoints(Repository repo, Vector<String> startingPointUrls) { RepositoryConnection con = null; try { con = repo.getConnection(); return findChangedStartingPoints(con, startingPointUrls); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } return new Vector<String>(); } /** * Return a list of old StartingPoint that is no longer a StartingPoint. * * @param con * @param startingPointsUrls * @return */ public static Vector<String> findChangedStartingPoints(RepositoryConnection con, Vector<String> startingPointsUrls) { Vector<String> result; Vector<String> changedStartingPoints = new Vector<String> (); log.debug("Checking if the old StartingPoint is still a StartingPoint ..."); try { result = findAllStartingPoints(con); for (String startpoint : result) { //log.debug("StartingPoints: " + startpoint); if (!startingPointsUrls.contains(startpoint) && !startpoint.equals(Terms.internalStartingPoint)) { changedStartingPoints.add(startpoint); log.debug("Adding to droplist: " + startpoint); } } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } log.info("Located " + changedStartingPoints.size()+" starting points that have been changed."); return changedStartingPoints; } /** * Return a list of startingPoint which is not in the repository yet. * @param repo * @param startingPointUrls * @return */ public static Vector<String> findNewStartingPoints(Repository repo, Vector<String> startingPointUrls) { RepositoryConnection con = null; try { con = repo.getConnection(); return findNewStartingPoints(con, startingPointUrls); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } return new Vector<String>(); } /** * Find new StartingPoints in the input file but not in the repository yet. If the internal starting point is not * present in the repository, then it will be added to the returned list of new starting points. * * @param con A connection to the repository to search. * @param startingPointUrls A list of candidate starting points * @return All of the starting points in the passed startingPointUrls that are not already present in the repository. * If the internalStartingPoint is not present in the repository it will be returned too. */ public static Vector<String> findNewStartingPoints(RepositoryConnection con, Vector<String> startingPointUrls) { Vector<String> result; Vector<String> newStartingPoints = new Vector<String> (); log.debug("Checking for new starting points..."); try { result = findAllStartingPoints(con); if(!result.contains(Terms.internalStartingPoint)){ log.debug("Internal StartingPoint not present in repository, adding to list."); newStartingPoints.add(Terms.internalStartingPoint); } for (String startingPoint : startingPointUrls) { if (!result.contains(startingPoint) && !startingPoint.equals(Terms.internalStartingPoint)) { newStartingPoints.add(startingPoint); log.debug("Found New StartingPoint: " + startingPoint); } } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } log.info("Number of new StartingPoints: " + newStartingPoints.size()); return newStartingPoints; } /** * Return all startingPoints in the repository. * @param repo * @return * @throws MalformedQueryException * @throws QueryEvaluationException */ public static Vector<String> findAllStartingPoints(Repository repo) throws MalformedQueryException, QueryEvaluationException { RepositoryConnection con = null; try { con = repo.getConnection(); return findAllStartingPoints(con); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to open repository connection. Msg: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName()+": Failed to close repository connection. Msg: " + e.getMessage()); } } } return new Vector<String>(); } /* * Find all starting points in the repository * */ public static Vector<String> findAllStartingPoints(RepositoryConnection con) throws RepositoryException, MalformedQueryException, QueryEvaluationException { Vector<String> startingPoints = new Vector <String> (); TupleQueryResult result = queryForStartingPoints(con); if (result != null) { if (!result.hasNext()) { log.debug("NEW repository!"); } while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("doc"); String startpoint = firstValue.stringValue(); //log.debug("StartingPoints: " + startpoint); startingPoints.add(startpoint); } } else { log.debug("No query result!"); } return startingPoints; } /** * Return all startingPoints as TupleQueryResult. * @param con * @return TupleQueryResult * @throws QueryEvaluationException * @throws MalformedQueryException * @throws RepositoryException */ private static TupleQueryResult queryForStartingPoints(RepositoryConnection con) throws QueryEvaluationException, MalformedQueryException, RepositoryException { TupleQueryResult result; log.debug("Finding StartingPoints in the repository ..."); String queryString = "SELECT doc " + "FROM {doc} rdf:type {rdfcache:"+Terms.startingPointType +"} " + "USING NAMESPACE " + "rdfcache = <"+ Terms.rdfCacheNamespace+">"; log.debug("queryStartingPoints: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,queryString); result = tupleQuery.evaluate(); return result; } /** * Wipe out the whole repository. * @param owlse2 */ public static void clearRepository(Repository owlse2) { RepositoryConnection con = null; try { con = owlse2.getConnection(); con.clear(); } catch (RepositoryException e) { log.error("Failed to open repository connection. Msg: "+e.getMessage()); } finally { log.debug("Closing repository connection."); if(con!=null){ try { con.close(); //close connection first } catch(RepositoryException e){ log.error("Failed to close repository connection. Msg: "+e.getMessage()); } } } } /** * Write the repository content to a plain ASCII file in N-triples, Trix or trig format depending the file name sufix. * @param con * @param filename */ public static void dumpRepository(RepositoryConnection con, String filename) { // export repository to an n-triple file File outrps = new File(filename); // hard copy of repository try { log.info("Dumping repository to: '"+filename+"'"); FileOutputStream myFileOutputStream = new FileOutputStream(outrps); if (filename.endsWith(".nt")) { NTriplesWriter myNTRiplesWriter = new NTriplesWriter( myFileOutputStream); con.export(myNTRiplesWriter); myNTRiplesWriter.startRDF(); myNTRiplesWriter.endRDF(); } if (filename.endsWith(".trix")) { TriXWriter myTriXWriter = new TriXWriter(myFileOutputStream); con.export(myTriXWriter); myTriXWriter.startRDF(); myTriXWriter.endRDF(); } if (filename.endsWith(".trig")) { TriGWriter myTriGWriter = new TriGWriter(myFileOutputStream); con.export(myTriGWriter); myTriGWriter.startRDF(); myTriGWriter.endRDF(); } log.info("Completed dumping explicit statements"); } catch (Exception e) { log.error("Failed to dump repository! msg: "+e.getMessage()); } } /** * Write the repository content to a plain ASCII file in N-triples, Trix or trig format depending the file name sufix. * @param owlse2 * @param filename */ public static void dumpRepository(Repository owlse2, String filename) { RepositoryConnection con = null; try { con = owlse2.getConnection(); dumpRepository(con, filename); } catch (RepositoryException e) { log.error("Failed to open repository connection. Msg: "+e.getMessage()); } finally { log.debug("Closing repository connection."); if(con!=null){ try { con.close(); //close connection first } catch(RepositoryException e){ log.error("Failed to close repository connection. Msg: "+e.getMessage()); } } } } /** * Return all contexts in the repository as a space separated string. * @param repository * @return */ public static String showContexts(Repository repository){ RepositoryConnection con = null; String msg; try { con = repository.getConnection(); msg = showContexts(con); } catch (RepositoryException e) { msg = "Failed to open repository connection. Msg: "+e.getMessage(); log.error(msg); } finally { log.debug("Closing repository connection."); if(con!=null){ try { con.close(); //close connection first } catch(RepositoryException e){ log.error("Failed to close repository connection. Msg: "+e.getMessage()); } } } return msg; } /** * Return all contexts in the repository as a separated string. * @param con * @return */ public static String showContexts(RepositoryConnection con){ String msg = "\nRepository ContextIDs:\n"; try { RepositoryResult<Resource> contextIds = con.getContextIDs(); for(Resource contextId : contextIds.asList()){ msg += " "+contextId+"\n"; } } catch (RepositoryException e) { msg = "Failed to open repository connection. Msg: "+e.getMessage(); log.error(msg); } return msg; } /** * Return true if import context is newer. * * @param con * @param importURL * @return Boolean */ public static Boolean olderContext(RepositoryConnection con, String importURL) { Boolean oldLMT = false; String oldltmod = getLastModifiedTime(con, importURL); // LMT from repository if (oldltmod.isEmpty()) { oldLMT = true; return oldLMT; } String oltd = oldltmod.substring(0, 10) + " " + oldltmod.substring(11, 19); String ltmod = getLTMODContext(importURL); String ltd = ltmod.substring(0, 10) + " " + ltmod.substring(11, 19); SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss"); Date ltdparseDate; try { ltdparseDate = dateFormat.parse(ltd); log.debug("In olderContext ..."); log.debug("URI " + importURL); log.debug("lastmodified " + ltdparseDate.toString()); Date oldltdparseDate = dateFormat.parse(oltd); log.debug("oldlastmodified " + oldltdparseDate.toString()); if (ltdparseDate.compareTo(oldltdparseDate) > 0) {// if newer // context log.info("Import context is newer: " + importURL); oldLMT = true; } } catch (ParseException e) { log.error("Caught an ParseException! Msg: " + e.getMessage()); } return oldLMT; } /** * Check and return last modified time of a context (URI) via querying * against the repository on contexts. * * * @param con * @param urlstring * @return */ public static String getLastModifiedTime(RepositoryConnection con, String urlstring) { TupleQueryResult result = null; String ltmodstr = ""; URI uriaddress = new URIImpl(urlstring); String queryString = "SELECT doc,lastmod FROM CONTEXT " + "rdfcache:"+Terms.cacheContext+" {doc} rdfcache:"+Terms.lastModifiedContext+" {lastmod} " + "where doc=<" + uriaddress + ">" + "USING NAMESPACE " + "rdfcache = <"+ Terms.rdfCacheNamespace+">"; try { TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); BindingSet bindingSet; Value valueOfY; while (result.hasNext()) { // should have only one value bindingSet = result.next(); //Set<String> names = bindingSet.getBindingNames(); // for (String name : names) { // log.debug("BindingNames: " + name); valueOfY = bindingSet.getValue("lastmod"); ltmodstr = valueOfY.stringValue(); // log.debug("Y:" + valueOfY.stringValue()); } } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught a MalformedQueryException! Msg: " + e.getMessage()); } finally { try { result.close(); } catch (Exception e) { log.error("Caught an Exception! Msg: " + e.getMessage()); } } return ltmodstr; } /** * Set last_modified_time of a context. * @param urlstring * @return */ public static String getLTMODContext(String urlstring) { String ltmodstr = ""; try { URL myurl = new URL(urlstring); HttpURLConnection hc = (HttpURLConnection) myurl.openConnection(); long ltmod = hc.getLastModified(); // log.debug("lastModified: "+ltmod); ltmodstr = getLastModifiedTimeString(ltmod); } catch (MalformedURLException e) { log.error("Caught a MalformedQueryException! Msg: " + e.getLocalizedMessage()); } catch (IOException e) { log.error("Caught an IOException! Msg: " + e.getMessage(), e); } return ltmodstr; } /** * Convert Date to last_modified_time * @param date * @return */ public static String getLastModifiedTimeString(Date date) { return getLastModifiedTimeString(date.getTime()); } /** * Convert time in long to last_modified_time * @param epochTime * @return */ public static String getLastModifiedTimeString(long epochTime) { String ltmodstr; Timestamp ltmodsql = new Timestamp(epochTime); String ltmodstrraw = ltmodsql.toString(); ltmodstr = ltmodstrraw.substring(0, 10) + "T" + ltmodstrraw.substring(11, 19) + "Z"; return ltmodstr; } /** * Returns a Hash containing last modified times of each context (URI) in the * repository, keyed by the context name. * @param repository The repository from which to harvest the contexts and their associated last * modified times. * @return */ public static HashMap<String, String> getLastModifiedTimesForContexts(Repository repository) { RepositoryConnection con = null; try{ con = repository.getConnection(); return getLastModifiedTimesForContexts(con); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } finally { if(con!=null){ try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } } } return new HashMap<String, String>(); } /** * Returns a Hash containing last modified times of each context (URI) in the * repository, keyed by the context name. * @param con A connection to the repoistory from which to harvest the contexts and their associated last * modified times. * @return */ public static HashMap<String, String> getLastModifiedTimesForContexts(RepositoryConnection con) { TupleQueryResult result = null; String ltmodstr = ""; String idstr = ""; HashMap<String, String> idltm = new HashMap<String, String>(); String queryString = "SELECT DISTINCT id, lmt " + "FROM " + "{cd} wcs:Identifier {id}; " + "rdfs:isDefinedBy {doc} rdfcache:"+Terms.lastModifiedContext+" {lmt} " + "using namespace " + "rdfcache = <"+ Terms.rdfCacheNamespace+">, " + "wcs= <http://www.opengis.net/wcs/1.1 try { TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); BindingSet bindingSet; Value valueOfID = null; Value valueOfLMT; while (result.hasNext()) { bindingSet = (BindingSet) result.next(); valueOfLMT = (Value) bindingSet.getValue("lmt"); ltmodstr = valueOfLMT.stringValue(); valueOfID = (Value) bindingSet.getValue("id"); idstr = valueOfID.stringValue(); idltm.put(idstr, ltmodstr); // log.debug("ID:" + valueOfID.stringValue()); // log.debug("LMT:" + valueOfLMT.stringValue()); } } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught a MalformedQueryException! Msg: " + e.getMessage()); } finally { try { if(result!=null) result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } return idltm; } /** * Insert a statement declaring the content type of the document. * * * @param importURL * @param contentType * @param con * @param valueFactory */ public static void setContentTypeContext(String importURL, String contentType, RepositoryConnection con, ValueFactory valueFactory) { URI s = valueFactory.createURI(importURL); URI contentTypeContext = valueFactory.createURI(Terms.contentTypeContextUri); URI cacheContext = valueFactory.createURI(Terms.cacheContextUri); Literal o = valueFactory.createLiteral(contentType); try { con.add((Resource) s, contentTypeContext, (Value) o, (Resource) cacheContext); } catch (RepositoryException e) { log.error("Caught an RepositoryException! Msg: " + e.getMessage()); } } /** * Set last_modified_time of the URI in the repository. * * @param importURL * @param con * @param valueFactory */ public static void setLTMODContext(String importURL, RepositoryConnection con,ValueFactory valueFactory) { String ltmod = getLTMODContext(importURL); setLTMODContext(importURL, ltmod, con, valueFactory); } /** * Set last_modified_time of the URI in the repository. * * * @param importURL * @param ltmod * @param con * @param valueFactory */ public static void setLTMODContext(String importURL, String ltmod, RepositoryConnection con, ValueFactory valueFactory) { // log.debug(importURL); // log.debug("lastmodified " + ltmod); URI s = valueFactory.createURI(importURL); URI p = valueFactory.createURI(Terms.lastModifiedContextUri); URI cont = valueFactory.createURI(Terms.cacheContextUri); URI sxd = valueFactory.createURI("http://www.w3.org/2001/XMLSchema#dateTime"); Literal o = valueFactory.createLiteral(ltmod, sxd); try { con.add((Resource) s, p, (Value) o, (Resource) cont); } catch (RepositoryException e) { log.error("Caught an RepositoryException! Msg: " + e.getMessage()); } } /** * Update the repository. Drop outdated files, add new files and run construct rules. * @param repository The repository on which to operate. * @param startingPointUrls The list of starting point URLs from the configuration file (aka "THE starting point") * @param doNotImportTheseUrls A list of URL's that should not be loaded into the repository, even if they are * encountered in the tree of dependencies. * @param resourceDir The local system directory in which to find crucial files (for example XSL transforms) used * by the semantic processing. * @return Returns true if the update results in changes to the repository. * @throws InterruptedException If the thread of execution is interrupted. * @throws RepositoryException When there are problems working with the repository. */ public static boolean updateSemanticRepository(Repository repository, Vector<String> startingPointUrls, Vector<String> doNotImportTheseUrls, String resourceDir) throws InterruptedException, RepositoryException { Vector<String> dropList = new Vector<String>(); Vector<String> newStartingPoints = new Vector<String>(); Vector<String> startingPointsToDrop = null; boolean repositoryHasBeenChanged = false; RdfImporter rdfImporter = new RdfImporter(resourceDir); Date startTime = new Date(); log.info(" log.info("updateSemanticRepository() Start."); log.debug(showContexts(repository)); RepositoryConnection con = null; try { try { con = repository.getConnection(); if (con.isOpen()) { log.info("Connection is OPEN!"); newStartingPoints = findNewStartingPoints(con, startingPointUrls); dropList.addAll(findUnneededRDFDocuments(con)); startingPointsToDrop = findChangedStartingPoints(con, startingPointUrls); dropList.addAll(startingPointsToDrop); dropList.addAll(findChangedRDFDocuments(con)); } } catch (RepositoryException e) { log.error("Caught RepositoryException updateSemanticRepository(Vector<String> startingPointUrls)" + e.getMessage()); } finally { if (con != null) con.close(); log.info("Connection is Closed!"); } ProcessingState.checkState(); log.debug(showContexts(repository)); boolean modelChanged = false; if (!dropList.isEmpty()) { if(flushRepositoryOnDrop){ log.warn("Repository content has been changed! Flushing Repository!"); clearRepository(repository); String filename = "PostRepositoryClear.trig"; log.debug("Dumping Semantic Repository to: " + filename); dumpRepository(repository, filename); newStartingPoints = findNewStartingPoints(repository, startingPointUrls); } else { log.debug("Add external inferencing contexts to dropList"); dropList.addAll(findExternalInferencingContexts(repository)); String filename = "PriorToDropStartingPointsRepository.trig"; log.debug("Dumping Semantic Repository to: " + filename); dumpRepository(repository, filename); log.debug("Dropping starting points ..."); dropStartingPoints(repository, startingPointsToDrop); log.debug("Finished dropping starting points."); ProcessingState.checkState(); filename = "PostDropStartingPointsRepository.trig"; log.debug("Dumping Semantic Repository to: " + filename); dumpRepository(repository, filename); log.debug(showContexts(repository)); log.debug("Dropping contexts."); dropContexts(repository, dropList); log.debug(showContexts(repository)); filename = "PostDropContextsRepository.trig"; log.debug("Dumping Semantic Repository to: " + filename); dumpRepository(repository, filename); } modelChanged = true; } ProcessingState.checkState(); if (!newStartingPoints.isEmpty()) { log.debug("Adding new starting points ..."); addStartingPoints(repository, newStartingPoints); log.debug("Finished adding new starting points."); log.debug(showContexts(repository)); modelChanged = true; } ProcessingState.checkState(); log.debug("Checking for referenced documents that are not already in the repository."); boolean foundNewDocuments = rdfImporter.importReferencedRdfDocs(repository, doNotImportTheseUrls); if(foundNewDocuments){ modelChanged = true; } ProcessingState.checkState(); if (modelChanged) { log.debug("Updating repository ..."); ConstructRuleEvaluator constructRuleEvaluator = new ConstructRuleEvaluator(); while (modelChanged) { log.debug("Repository changes detected."); log.debug(showContexts(repository)); log.debug("Running construct rules ..."); constructRuleEvaluator.runConstruct(repository); log.debug("Finished running construct rules."); ProcessingState.checkState(); log.debug(showContexts(repository)); modelChanged = rdfImporter.importReferencedRdfDocs(repository, doNotImportTheseUrls); ProcessingState.checkState(); } repositoryHasBeenChanged = true; } else { log.debug("Repository update complete. No changes detected, rules not rerun.."); log.debug(showContexts(repository)); } } catch (RepositoryException e) { log.error("Caught RepositoryException in main(): " + e.getMessage()); } long elapsedTime = new Date().getTime() - startTime.getTime(); log.info("Imports Evaluated. Elapsed time: " + elapsedTime + "ms"); log.info("updateSemanticRepository() End."); log.info(" return repositoryHasBeenChanged; } /** * Remove contexts from the repository. * @param repository * @param dropList * @throws InterruptedException */ public static void dropContexts(Repository repository, Vector<String> dropList) throws InterruptedException { RepositoryConnection con = null; log.debug("Dropping changed RDFDocuments and external inferencing contexts..."); try { con = repository.getConnection(); log.info("Deleting contexts in drop list ..."); ValueFactory valueFactory = repository.getValueFactory(); for (String drop : dropList) { log.info("Dropping context URI: " + drop); URI contextToDrop = valueFactory.createURI(drop); URI cacheContext = valueFactory.createURI(Terms.cacheContextUri); log.info("Removing context: " + contextToDrop); con.clear(contextToDrop); log.info("Removing last_modified: " + contextToDrop); con.remove(contextToDrop, null, null, cacheContext); // remove last_modified log.info("Finished removing context: " + contextToDrop); ProcessingState.checkState(); } } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } finally { try { if (con != null) con.close(); } catch (RepositoryException e) { log.error("Caught RepositoryException! while closing connection: " + e.getMessage()); } } log.debug("Finished dropping changed RDFDocuments and external inferencing contexts."); } /** * Locate all of the of the contexts generated by externbal inferencing (construct rule) activities. * * @param repository The repository to operate on. * @return A lists of contexts that were generated by construct rules (i.e. external inferencing) */ static Vector<String> findExternalInferencingContexts(Repository repository) { RepositoryConnection con = null; TupleQueryResult result = null; //List<String> bindingNames; Vector<String> externalInferencing = new Vector<String>(); log.debug("Finding ExternalInferencing ..."); try { con = repository.getConnection(); String queryString = "select distinct crule from context crule {} prop {} " + "WHERE crule != rdfcache:"+Terms.cacheContext+" " + "AND crule != rdfcache:"+Terms.startingPointsContext+" " + "AND NOT EXISTS (SELECT time FROM CONTEXT rdfcache:"+Terms.cacheContext+" " + "{crule} rdfcache:"+Terms.lastModifiedContext+" {time}) " + "using namespace " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("queryString: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); if (result != null) { //bindingNames = result.getBindingNames(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("crule"); if (!externalInferencing.contains(firstValue.stringValue())) { externalInferencing.add(firstValue.stringValue()); log.debug("Adding to external inferencing list: " + firstValue.toString()); } } } else { log.debug("No construct rule found!"); } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } try { con.close(); } catch (RepositoryException e) { log .error("Caught RepositoryException! in dropExternalInferencing() Msg: " + e.getMessage()); } } log.info("Located " + externalInferencing.size() + " context generated by external inferencing (construct rules)."); return externalInferencing; } /** * Return a list of files not needed any more in the repository. * @param con * @return */ static Vector<String> findUnneededRDFDocuments(RepositoryConnection con) { TupleQueryResult result = null; //List<String> bindingNames; Vector<String> unneededRdfDocs = new Vector<String>(); log.debug("Locating unneeded RDF files left over from last update ..."); try { String queryString = "(SELECT doc " + "FROM CONTEXT rdfcache:"+Terms.cacheContext+" " + "{doc} rdfcache:"+Terms.lastModifiedContext+" {lmt} " //+ "WHERE doc != <" + Terms.externalInferencingUri+"> " + "MINUS " + "SELECT doc " + "FROM {doc} rdf:type {rdfcache:"+Terms.startingPointType +"}) " + "MINUS " + "SELECT doc " + "FROM {tp} rdf:type {rdfcache:"+Terms.startingPointType +"}; rdfcache:"+Terms.dependsOnContext+" {doc} " + "USING NAMESPACE " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("queryUnneededRDFDocuments: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); if (result != null) { //bindingNames = result.getBindingNames(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("doc"); if (!unneededRdfDocs.contains(firstValue.stringValue())) { unneededRdfDocs.add(firstValue.stringValue()); log.debug("Found unneeded RDF Document: " + firstValue.toString()); } } } else { log.debug("No query result!"); } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } } log.info("Identified " + unneededRdfDocs.size() + " unneeded RDF documents."); return unneededRdfDocs; } /** * Return a list of files changed in the repository since last update. * @param con * @return */ static Vector<String> findChangedRDFDocuments(RepositoryConnection con) { TupleQueryResult result = null; //List<String> bindingNames; Vector<String> changedRdfDocuments = new Vector<String>(); log.debug("Locating changeded files ..."); try { String queryString = "SELECT doc,lastmod " + "FROM CONTEXT rdfcache:"+Terms.cacheContext+" " + "{doc} rdfcache:"+Terms.lastModifiedContext+" {lastmod} " + "USING NAMESPACE " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("queryChangedRDFDocuments: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); if (result != null) { //bindingNames = result.getBindingNames(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("doc"); String importURL = firstValue.stringValue(); // Value secondtValue = bindingSet.getValue("lastmod"); // log.debug("DOC: " + importURL); // log.debug("LASTMOD: " + secondtValue.stringValue()); if (olderContext(con, importURL) && !changedRdfDocuments.contains(importURL)) { changedRdfDocuments.add(importURL); log.debug("Found changed RDF document: " + importURL); } } } else { log.debug("No query result!"); } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } } log.info("Number of changed RDF documents detected: " + changedRdfDocuments.size()); return changedRdfDocuments; } /** * Return URL of the transformation file. * @param importUrl-the file to transform * @param repository-the repository instance * @return xsltTransformationFileUrl-Url of the transformation stylesheet */ public static String getUrlForTransformToRdf(Repository repository, String importUrl){ RepositoryConnection con = null; String xsltTransformationFileUrl = null; ValueFactory valueFactory; RepositoryResult<Statement> statements = null; try { con = repository.getConnection(); valueFactory = repository.getValueFactory(); // Get all of the statements in the repository that statements = con.getStatements( valueFactory.createURI(importUrl), valueFactory.createURI(Terms.hasXslTransformToRdfUri), null, true); while (statements.hasNext()){ if(xsltTransformationFileUrl!=null){ log.error("getUrlForTransformToRdf(): Error!!! Found multiple XSL transforms associated with url: "+importUrl+" Lacking further instructions. DISCARDING: "+xsltTransformationFileUrl); } Statement s = statements.next(); xsltTransformationFileUrl= s.getObject().stringValue(); log.debug("Found Transformation file= " + xsltTransformationFileUrl); } } catch (RepositoryException e) { log.error("Caught a RepositoryException in getXsltTransformation Msg: " +e.getMessage()); }finally { try { if(statements!=null) statements.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException while closing statements! in getXsltTransformation Msg: " +e.getMessage()); } try { if(con!=null) con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! in getXsltTransformation Msg: " + e.getMessage()); } } return xsltTransformationFileUrl; } }
package org.appwork.utils.net.ftpserver; /** * @author thomas * */ public class FtpFile { protected String name; private final long size; protected long lastModified; private final boolean isDirectory; private String owner = "unknown"; private String group = "unknown"; /** * @param name * @param length * @param directory */ public FtpFile(final String name, final long length, final boolean directory, final long lastMod) { this.name = name; this.size = length; this.isDirectory = directory; this.lastModified = lastMod; } /** * @return the group */ public String getGroup() { return this.group; } public long getLastModified() { return this.lastModified; } public String getName() { return this.name; } public String getOwner() { return this.owner; } public long getSize() { return this.size; } public boolean isDirectory() { return this.isDirectory; } /** * @param group * the group to set */ public void setGroup(final String group) { this.group = group; } /** * @param owner * the owner to set */ public void setOwner(final String owner) { this.owner = owner; } }
/* * CollectionStore.java - Jun 19, 2003 * * @author wolf */ package org.exist.storage.index; import org.exist.collections.Collection; import org.exist.dom.DocumentImpl; import org.exist.storage.BrokerPool; import org.exist.storage.btree.DBException; import org.exist.storage.btree.Value; import org.exist.storage.lock.Lock; import org.exist.util.ByteConversion; import org.exist.util.Configuration; import org.exist.util.LockException; import org.exist.util.UTF8; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.Stack; /** * Handles access to the central collection storage file (collections.dbx). * * @author wolf */ public class CollectionStore extends BFile { public static final String FILE_NAME = "collections.dbx"; public static final String FILE_KEY_IN_CONFIG = "db-connection.collections"; public final static String FREE_DOC_ID_KEY = "__free_doc_id"; public final static String NEXT_DOC_ID_KEY = "__next_doc_id"; public final static String FREE_COLLECTION_ID_KEY = "__free_collection_id"; public final static String NEXT_COLLECTION_ID_KEY = "__next_collection_id"; public final static byte KEY_TYPE_COLLECTION = 0; public final static byte KEY_TYPE_DOCUMENT = 1; private Stack<Integer> freeResourceIds = new Stack<>(); private Stack<Integer> freeCollectionIds = new Stack<>(); /** * @param pool * @param id * @param dataDir * @param config * @throws DBException */ public CollectionStore(BrokerPool pool, byte id, String dataDir, Configuration config) throws DBException { super(pool, id, true, new File(dataDir + File.separatorChar + getFileName()), pool.getCacheManager(), 1.25, 0.01, 0.03); config.setProperty(getConfigKeyForFile(), this); } public static String getFileName() { return FILE_NAME; } public static String getConfigKeyForFile() { return FILE_KEY_IN_CONFIG; } /* (non-Javadoc) * @see org.exist.storage.store.BFile#getDataSyncPeriod() */ @Override protected long getDataSyncPeriod() { return 1000; } @Override public boolean flush() throws DBException { boolean flushed = false; if (!BrokerPool.FORCE_CORRUPTION) { flushed = flushed | dataCache.flush(); flushed = flushed | super.flush(); } return flushed; } public void freeResourceId(int id) { final Lock lock = getLock(); try { lock.acquire(Lock.WRITE_LOCK); freeResourceIds.push(id); } catch (LockException e) { LOG.warn("Failed to acquire lock on " + getFile().getName(), e); } finally { lock.release(Lock.WRITE_LOCK); } } public int getFreeResourceId() { int freeDocId = DocumentImpl.UNKNOWN_DOCUMENT_ID; final Lock lock = getLock(); try { lock.acquire(Lock.WRITE_LOCK); if (!freeResourceIds.isEmpty()) { freeDocId = freeResourceIds.pop(); } } catch (final LockException e) { LOG.warn("Failed to acquire lock on " + getFile().getName(), e); return DocumentImpl.UNKNOWN_DOCUMENT_ID; //TODO : rethrow ? -pb } finally { lock.release(Lock.WRITE_LOCK); } return freeDocId; } public void freeCollectionId(int id) { final Lock lock = getLock(); try { lock.acquire(Lock.WRITE_LOCK); freeCollectionIds.push(id); } catch (LockException e) { LOG.warn("Failed to acquire lock on " + getFile().getName(), e); } finally { lock.release(Lock.WRITE_LOCK); } } public int getFreeCollectionId() { int freeCollectionId = Collection.UNKNOWN_COLLECTION_ID; final Lock lock = getLock(); try { lock.acquire(Lock.WRITE_LOCK); if (!freeCollectionIds.isEmpty()) { freeCollectionId = freeCollectionIds.pop(); } } catch (final LockException e) { LOG.warn("Failed to acquire lock on " + getFile().getName(), e); return Collection.UNKNOWN_COLLECTION_ID; //TODO : rethrow ? -pb } finally { lock.release(Lock.WRITE_LOCK); } return freeCollectionId; } protected void dumpValue(Writer writer, Value value) throws IOException { //TODO : what does this 5 stand for ? if (value.getLength() == 5 + Collection.LENGTH_COLLECTION_ID) { final short collectionId = ByteConversion.byteToShort(value.data(), value.start()); //TODO : what does this 1 stand for ? final int docId = ByteConversion.byteToInt(value.data(), value.start() + 1 + Collection.LENGTH_COLLECTION_ID); writer.write('['); writer.write("Document: collection = "); writer.write(collectionId); writer.write(", docId = "); writer.write(docId); writer.write(']'); } else { writer.write('['); writer.write("Collection: "); writer.write(new String(value.data(), value.start(), value.getLength(), "UTF-8")); writer.write(']'); } } public static class DocumentKey extends Value { public static int OFFSET_TYPE = 0; public static int LENGTH_TYPE = 1; //sizeof byte public static int OFFSET_COLLECTION_ID = OFFSET_TYPE + LENGTH_TYPE; public static int LENGTH_TYPE_DOCUMENT = 2; //sizeof short public static int OFFSET_DOCUMENT_TYPE = OFFSET_COLLECTION_ID + Collection.LENGTH_COLLECTION_ID; public static int LENGTH_DOCUMENT_TYPE = 1; //sizeof byte public static int OFFSET_DOCUMENT_ID = OFFSET_DOCUMENT_TYPE + LENGTH_DOCUMENT_TYPE; public DocumentKey() { data = new byte[LENGTH_TYPE]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; len = LENGTH_TYPE; } public DocumentKey(int collectionId) { data = new byte[LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; ByteConversion.intToByte(collectionId, data, OFFSET_COLLECTION_ID); len = LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID; pos = OFFSET_TYPE; } public DocumentKey(int collectionId, byte type, int docId) { data = new byte[LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID + LENGTH_DOCUMENT_TYPE + DocumentImpl.LENGTH_DOCUMENT_ID]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; ByteConversion.intToByte(collectionId, data, OFFSET_COLLECTION_ID); data[OFFSET_DOCUMENT_TYPE] = type; ByteConversion.intToByte(docId, data, OFFSET_DOCUMENT_ID); len = LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID + LENGTH_DOCUMENT_TYPE + DocumentImpl.LENGTH_DOCUMENT_ID; pos = OFFSET_TYPE; } public static int getCollectionId(Value key) { return ByteConversion.byteToInt(key.data(), key.start() + OFFSET_COLLECTION_ID); } public static int getDocumentId(Value key) { return ByteConversion.byteToInt(key.data(), key.start() + OFFSET_DOCUMENT_ID); } } public static class CollectionKey extends Value { public static int OFFSET_TYPE = 0; public static int LENGTH_TYPE = 1; //sizeof byte public static int OFFSET_VALUE = OFFSET_TYPE + LENGTH_TYPE; public CollectionKey() { data = new byte[LENGTH_TYPE]; data[OFFSET_TYPE] = KEY_TYPE_COLLECTION; len = LENGTH_TYPE; } public CollectionKey(String name) { len = LENGTH_TYPE + UTF8.encoded(name); data = new byte[len]; data[OFFSET_TYPE] = KEY_TYPE_COLLECTION; UTF8.encode(name, data, OFFSET_VALUE); pos = OFFSET_TYPE; } } }
package org.helioviewer.jhv.view.fits; import java.net.URI; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import nom.tam.fits.BasicHDU; import nom.tam.fits.Fits; import nom.tam.fits.Header; import nom.tam.fits.HeaderCard; import nom.tam.fits.ImageHDU; import nom.tam.image.compression.hdu.CompressedImageHDU; import nom.tam.util.Cursor; import org.helioviewer.jhv.io.NetClient; import org.helioviewer.jhv.imagedata.ImageBuffer; import org.helioviewer.jhv.imagedata.ImageData; import org.helioviewer.jhv.math.MathUtils; import org.helioviewer.jhv.log.Log; class FITSImage { private static final double GAMMA = 1 / 2.2; private static final long BLANK = 0; // in case it doesn't exist, very unlikely value String xml; ImageData imageData; FITSImage(URI uri) throws Exception { try (NetClient nc = NetClient.of(uri); Fits f = new Fits(nc.getStream())) { BasicHDU<?>[] hdus = f.read(); // this is cumbersome for (BasicHDU<?> hdu : hdus) { if (hdu instanceof CompressedImageHDU) { xml = getHeaderAsXML(hdu.getHeader()); readHDU(((CompressedImageHDU) hdu).asImageHDU()); return; } } for (BasicHDU<?> hdu : hdus) { if (hdu instanceof ImageHDU) { xml = getHeaderAsXML(hdu.getHeader()); readHDU(hdu); return; } } } } private static float getValue(int bpp, Object lineData, int i, long blank, double bzero, double bscale) { double v = ImageData.BAD_PIXEL; switch (bpp) { case BasicHDU.BITPIX_SHORT: v = ((short[]) lineData)[i]; break; case BasicHDU.BITPIX_INT: v = ((int[]) lineData)[i]; break; case BasicHDU.BITPIX_LONG: v = ((long[]) lineData)[i]; break; case BasicHDU.BITPIX_FLOAT: v = ((float[]) lineData)[i]; break; case BasicHDU.BITPIX_DOUBLE: v = ((double[]) lineData)[i]; break; } return (blank != BLANK && v == blank) || !Double.isFinite(v) ? ImageData.BAD_PIXEL : (float) (bzero + v * bscale); } private static float[] sampleImage(int bpp, int width, int height, Object[] pixelData, long blank, double bzero, double bscale, int[] npix) { int stepW = 4 * width / 1024; int stepH = 4 * height / 1024; float[] sampleData = new float[(width / stepW) * (height / stepH)]; int k = 0; for (int j = 0; j < height; j += stepH) { Object lineData = pixelData[j]; for (int i = 0; i < width; i += stepW) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); if (v != ImageData.BAD_PIXEL) sampleData[k++] = v; } } npix[0] = k; return sampleData; } private static float[] getMinMax(int bpp, int width, int height, Object[] pixelData, long blank, double bzero, double bscale) { float min = Float.MAX_VALUE; float max = -Float.MAX_VALUE; for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, pixelData, i, blank, bzero, bscale); if (v != ImageData.BAD_PIXEL) { if (v > max) max = v; if (v < min) min = v; } } } return new float[]{min, max}; } private void readHDU(BasicHDU<?> hdu) throws Exception { int[] axes = hdu.getAxes(); if (axes == null || axes.length != 2) throw new Exception("Only 2D FITS files supported"); int height = axes[0]; int width = axes[1]; int bpp = hdu.getBitPix(); Object kernel = hdu.getKernel(); if (!(kernel instanceof Object[])) throw new Exception("Cannot retrieve pixel data"); Object[] pixelData = (Object[]) kernel; long blank = BLANK; try { blank = hdu.getBlankValue(); } catch (Exception ignore) { } if (bpp == BasicHDU.BITPIX_BYTE) { byte[][] inData = (byte[][]) pixelData; byte[] outData = new byte[width * height]; for (int j = 0; j < height; j++) { System.arraycopy(inData[j], 0, outData, width * (height - 1 - j), width); } imageData = new ImageData(new ImageBuffer(width, height, ImageBuffer.Format.Gray8, ByteBuffer.wrap(outData))); return; } double bzero = hdu.getBZero(); double bscale = hdu.getBScale(); int[] npix = {0}; float[] sampleData = sampleImage(bpp, width, height, pixelData, blank, bzero, bscale, npix); float[] zLow = {0}; float[] zHigh = {0}; float[] zMax = {0}; ZScale.zscale(sampleData, npix[0], zLow, zHigh, zMax); // System.out.println(">>> " + npix[0] + " " + zLow[0] + " " + zMax[0]); float[] minmax = {zLow[0], zMax[0]}; //float[] minmax = getMinMax(bpp, width, height, pixelData, blank, bzero, bscale); if (minmax[0] >= minmax[1]) { Log.debug("min >= max :" + minmax[0] + ' ' + minmax[1]); minmax[1] = minmax[0] + 1; } double range = minmax[1] - minmax[0]; // System.out.println(">>> " + minmax[0] + ' ' + minmax[1]); short[] outData = new short[width * height]; float[] lut = new float[65536]; switch (bpp) { case BasicHDU.BITPIX_SHORT: case BasicHDU.BITPIX_INT: case BasicHDU.BITPIX_LONG: case BasicHDU.BITPIX_FLOAT: { double scale = 65535. / Math.pow(range, GAMMA); for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); int p = (int) MathUtils.clip(scale * Math.pow(v - minmax[0], GAMMA) + .5, 0, 65535); lut[p] = v; outData[width * (height - 1 - j) + i] = v == ImageData.BAD_PIXEL ? 0 : (short) p; } } break; } case BasicHDU.BITPIX_DOUBLE: { double scale = 65535. / Math.log1p(range); for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); int p = (int) MathUtils.clip(scale * Math.log1p(v - minmax[0]) + .5, 0, 65535); lut[p] = v; outData[width * (height - 1 - j) + i] = v == ImageData.BAD_PIXEL ? 0 : (short) p; } } break; } } imageData = new ImageData(new ImageBuffer(width, height, ImageBuffer.Format.Gray16, ShortBuffer.wrap(outData))); imageData.setPhysicalLUT(lut); } private static String getHeaderAsXML(Header header) { String nl = System.getProperty("line.separator"); StringBuilder builder = new StringBuilder("<meta>").append(nl).append("<fits>").append(nl); for (Cursor<String, HeaderCard> iter = header.iterator(); iter.hasNext(); ) { HeaderCard headerCard = iter.next(); if (headerCard.getValue() != null) { builder.append('<').append(headerCard.getKey()).append('>').append(headerCard.getValue()).append("</").append(headerCard.getKey()).append('>').append(nl); } } builder.append("</fits>").append(nl).append("</meta>"); return builder.toString().replace("&", "&amp;"); } }
package org.phoenix.assetdatabase; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * Represents a Phoenix Asset Database, which is a file database/container * format that uses a triplet of numbers to type, group, and identify asset * files. Each {@link TypeGroupInstance} triplet is unique within a database and * should be kept universally unique within an application. Duplicate entries * should result in the last loaded entry overriding any previous entries. Files * can be compressed and have validation hashes (currently MD5, support for others * in the future possibly) * <p> * * @version 0.0.0.3 * @since 2013-11-23 * @author Vince */ public interface AssetDatabase { public static final int MAGIC_NUMBER = 0x50414442; // 'PADB' /** * Saves the database to file. * * @throws IOException If the database could not be saved. */ public void save() throws IOException; /** * Loads the database from file. * * @throws IOException If the database could not be loaded. */ public void load() throws IOException; /** * Checks whether or not this database contains a certain TGI. * * @param tgi The TGI to check for. * @return True if the database contains the specified TGI or false * otherwise. */ public boolean contains(TypeGroupInstance tgi); /** * Reads a subfile from the database. * * @param tgi The TGI of the subfile to get. * @return A {@link Subfile} containing the result. * @throws FileNotFoundException If no subfile with the specified TGI was * found in the database. * @throws IOException If there was an issue reading the subfile from the * file. */ public Subfile loadSubfile(TypeGroupInstance tgi) throws FileNotFoundException, IOException; /** * Reads multiple subfiles from the database (bulk operation). * * @see AssetDatabase#loadSubfile(TypeGroupInstance) * @param tgis A collection of TGIs to load. Repeated elements are ignored * but discouraged for potential performance reasons (<i>varies on * implementation</i>). * @return A Map of results. * @throws FileNotFoundException If no subfile(s) could be found with a * given TGI in the collection. * @throws IOException If there was an issue reading any subfile from the * file. */ public Map<TypeGroupInstance, Subfile> loadSubfiles(Collection<TypeGroupInstance> tgis) throws FileNotFoundException, IOException; /** * Adds a subfile to the database for writing. * <p> * Note that depending on implementation the subfile may not be visible * through other methods until the database is saved. * * @param ie An IndexEntry with the TGI field set. All other fields will be * updated on save. * @param sf A Subfile with the data and compression information set. All * other fields will be updated on save. */ public void putSubfile(IndexEntry ie, Subfile sf); /** * Adds subfiles to the database for writing. * * @see AssetDatabase#putSubfile(IndexEntry, Subfile) * @param files A map of IndexEntry, Subfile pairs of the subfiles to add * with the specified index entry information. */ public void putSubfiles(Map<IndexEntry, Subfile> files); /** * Removes a subfile, if present, from the database. * <p> * Note that depending on implementation the change may not be visible * through other methods until the database is saved. * * @param tgi The TGI of the subfile to remove. */ public void removeSubfile(TypeGroupInstance tgi); /** * Returns the database index that reflects the database on disk. * <p> * Depending on implementation the returned index may or may not reflect any * unsaved changes made to the database. * * @return */ public Index getIndex(); /** * Returns the database metadata. * <p> * Changes made to the metadata tables are immediately visible, but are not * permanent until the database is saved. * * @return */ public MetadataList getMetadata(); /** * Clears the database. * <p> * Note that depending on implementation the change may not be visible * through other methods until the database is saved. */ public void clear(); }
package org.shaman.terrain.sketch; import Jama.Matrix; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.*; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.*; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.*; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.shape.Cylinder; import com.jme3.scene.shape.Quad; import com.jme3.scene.shape.Sphere; import com.jme3.shadow.DirectionalLightShadowRenderer; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image; import com.jme3.util.BufferUtils; import de.lessvoid.nifty.Nifty; import java.awt.Graphics; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.*; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.shaman.terrain.AbstractTerrainStep; import org.shaman.terrain.TerrainHeighmapCreator; import org.shaman.terrain.Heightmap; /** * * @author Sebastian Weiss */ public class SketchTerrain extends AbstractTerrainStep implements ActionListener, AnalogListener { private static final Logger LOG = Logger.getLogger(SketchTerrain.class.getName()); private static final float PLANE_QUAD_SIZE = 200 * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float INITIAL_PLANE_DISTANCE = 150f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float PLANE_MOVE_SPEED = 0.005f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float CURVE_SIZE = 0.5f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final int CURVE_RESOLUTION = 8; private static final int CURVE_SAMPLES = 128; private static final boolean DEBUG_DIFFUSION_SOLVER = false; private static final int DIFFUSION_SOLVER_ITERATIONS = 100; private Heightmap map; private Heightmap originalMap; private Spatial waterPlane; private float planeDistance = INITIAL_PLANE_DISTANCE; private Spatial sketchPlane; private SketchTerrainScreenController screenController; private final ArrayList<ControlCurve> featureCurves; private final ArrayList<Node> featureCurveNodes; private final ArrayList<ControlCurveMesh> featureCurveMesh; private boolean addNewCurves = true; private int selectedCurveIndex; private int selectedPointIndex; private ControlCurve newCurve; private Node newCurveNode; private ControlCurveMesh newCurveMesh; private long lastTime; private final CurvePreset[] presets; private int selectedPreset; public SketchTerrain() { this.featureCurves = new ArrayList<>(); this.featureCurveNodes = new ArrayList<>(); this.featureCurveMesh = new ArrayList<>(); this.presets = DefaultCurvePresets.DEFAULT_PRESETS; } @Override protected void enable() { this.map = (Heightmap) properties.get(AbstractTerrainStep.KEY_HEIGHTMAP); if (this.map == null) { throw new IllegalStateException("SketchTerrain requires a heightmap"); } this.originalMap = this.map.clone(); selectedPreset = 0; init(); } @Override protected void disable() { app.getInputManager().removeListener(this); } @Override public void update(float tpf) { } private void init() { //init nodes guiNode.detachAllChildren(); sceneNode.detachAllChildren(); //initial terrain app.setTerrain(originalMap); //init water plane initWaterPlane(); //init sketch plane initSketchPlane(); //init actions // app.getInputManager().addMapping("SolveDiffusion", new KeyTrigger(KeyInput.KEY_RETURN)); app.getInputManager().addMapping("MouseClicked", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); app.getInputManager().addListener(this, "SolveDiffusion", "MouseClicked"); //init light for shadow DirectionalLight light = new DirectionalLight(new Vector3f(0, -1, 0)); light.setColor(ColorRGBA.White); sceneNode.addLight(light); DirectionalLightShadowRenderer shadowRenderer = new DirectionalLightShadowRenderer(app.getAssetManager(), 512, 1); shadowRenderer.setLight(light); app.getHeightmapSpatial().setShadowMode(RenderQueue.ShadowMode.Receive); app.getViewPort().addProcessor(shadowRenderer); //TODO: add pseudo water at height 0 initNifty(); } private void initNifty() { Nifty nifty = app.getNifty(); screenController = new SketchTerrainScreenController(this); nifty.registerScreenController(screenController); nifty.addXml("org/shaman/terrain/sketch/SketchTerrainScreen.xml"); nifty.gotoScreen("SketchTerrain"); sendAvailablePresets(); // nifty.setDebugOptionPanelColors(true); } private void initWaterPlane() { float size = map.getSize() * TerrainHeighmapCreator.TERRAIN_SCALE; Quad quad = new Quad(size, size); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(0, 0, 0.5f, 0.5f)); mat.setTransparent(true); mat.getAdditionalRenderState().setAlphaTest(true); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); mat.getAdditionalRenderState().setDepthWrite(false); Geometry geom = new Geometry("water", quad); geom.setMaterial(mat); geom.setQueueBucket(RenderQueue.Bucket.Transparent); geom.rotate(FastMath.HALF_PI, 0, 0); geom.move(-size/2, 0, -size/2); waterPlane = geom; sceneNode.attachChild(geom); } private void initSketchPlane() { Quad quad = new Quad(PLANE_QUAD_SIZE*2, PLANE_QUAD_SIZE*2); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(0.5f, 0, 0, 0.5f)); mat.setTransparent(true); mat.getAdditionalRenderState().setAlphaTest(true); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); Geometry geom = new Geometry("SketchPlaneQuad", quad); geom.setMaterial(mat); geom.setQueueBucket(RenderQueue.Bucket.Translucent); geom.setLocalTranslation(-PLANE_QUAD_SIZE, -PLANE_QUAD_SIZE, 0); sketchPlane = new Node("SketchPlane"); ((Node) sketchPlane).attachChild(geom); sceneNode.attachChild(sketchPlane); sketchPlane.addControl(new AbstractControl() { @Override protected void controlUpdate(float tpf) { //place the plane at the given distance from the camera Vector3f pos = app.getCamera().getLocation().clone(); pos.addLocal(app.getCamera().getDirection().mult(planeDistance)); sketchPlane.setLocalTranslation(pos); //face the camera Quaternion q = sketchPlane.getLocalRotation(); q.lookAt(app.getCamera().getDirection().negate(), Vector3f.UNIT_Y); sketchPlane.setLocalRotation(q); } @Override protected void controlRender(RenderManager rm, ViewPort vp) {} }); app.getInputManager().addMapping("SketchPlaneDist-", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); app.getInputManager().addMapping("SketchPlaneDist+", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); app.getInputManager().addListener(this, "SketchPlaneDist-", "SketchPlaneDist+"); } private void addFeatureCurve(ControlCurve curve) { int index = featureCurveNodes.size(); Node node = new Node("feature"+index); featureCurves.add(curve); addControlPointsToNode(curve.getPoints(), node, index); ControlCurveMesh mesh = new ControlCurveMesh(curve, "Curve"+index, app); node.attachChild(mesh.getTubeGeometry()); node.attachChild(mesh.getSlopeGeometry()); node.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); mesh.getSlopeGeometry().setShadowMode(RenderQueue.ShadowMode.Off); featureCurveNodes.add(node); featureCurveMesh.add(mesh); sceneNode.attachChild(node); } private void addControlPointsToNode(ControlPoint[] points, Node node, int index) { Material sphereMat = new Material(app.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md"); sphereMat.setBoolean("UseMaterialColors", true); sphereMat.setColor("Diffuse", ColorRGBA.Gray); sphereMat.setColor("Ambient", ColorRGBA.White); for (int i=0; i<points.length; ++i) { Sphere s = new Sphere(CURVE_RESOLUTION, CURVE_RESOLUTION, CURVE_SIZE*3f); Geometry g = new Geometry(index<0 ? "dummy" : ("ControlPoint"+index+":"+i), s); g.setMaterial(sphereMat); g.setLocalTranslation(app.mapHeightmapToWorld(points[i].x, points[i].y, points[i].height)); node.attachChild(g); } } private void solveDiffusion() { LOG.info("Solve diffusion"); //create solver DiffusionSolver solver = new DiffusionSolver(map.getSize(), featureCurves.toArray(new ControlCurve[featureCurves.size()])); Matrix mat = new Matrix(map.getSize(), map.getSize()); //Save if (DEBUG_DIFFUSION_SOLVER) { solver.saveFloatMatrix(mat, "diffusion/Iter0.png",1); } //run solver for (int i=1; i<=DIFFUSION_SOLVER_ITERATIONS; ++i) { if (i%10 == 0) System.out.println("iteration "+i); mat = solver.oneIteration(mat, i); if (DEBUG_DIFFUSION_SOLVER) { //if (i%10 == 0) { solver.saveFloatMatrix(mat, "diffusion/Iter"+i+".png",1); } } LOG.info("solved"); //fill heighmap for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { map.setHeightAt(x, y, (float) mat.get(x, y) + originalMap.getHeightAt(x, y)); } } app.setTerrain(map); LOG.info("terrain updated"); } @Override public void onAction(String name, boolean isPressed, float tpf) { if ("SolveDiffusion".equals(name) && isPressed) { solveDiffusion(); } else if ("MouseClicked".equals(name) && isPressed) { Vector3f dir = app.getCamera().getWorldCoordinates(app.getInputManager().getCursorPosition(), 1); dir.subtractLocal(app.getCamera().getLocation()); dir.normalizeLocal(); Ray ray = new Ray(app.getCamera().getLocation(), dir); if (addNewCurves) { addNewPoint(ray); } else { pickCurve(ray); } } } @Override public void onAnalog(String name, float value, float tpf) { switch (name) { case "SketchPlaneDist-": planeDistance *= 1+PLANE_MOVE_SPEED; break; case "SketchPlaneDist+": planeDistance /= 1+PLANE_MOVE_SPEED; break; } } //Edit private void addNewPoint(Ray ray) { long time = System.currentTimeMillis(); if (time < lastTime+500) { //finish current curve if (newCurve==null) { return; } newCurveMesh = null; sceneNode.detachChild(newCurveNode); newCurveNode = null; if (newCurve.getPoints().length>=2) { addFeatureCurve(newCurve); } newCurve = null; LOG.info("new feature added"); screenController.setMessage(""); return; } lastTime = time; //create new point CollisionResults results = new CollisionResults(); sketchPlane.collideWith(ray, results); if (results.size()==0) { return; } Vector3f point = results.getClosestCollision().getContactPoint(); point = app.mapWorldToHeightmap(point); ControlPoint p = createNewControlPoint(point.x, point.y, point.z); //add to curve if (newCurve==null) { LOG.info("start a new feature"); newCurve = new ControlCurve(new ControlPoint[]{p}); newCurveNode = new Node(); addControlPointsToNode(newCurve.getPoints(), newCurveNode, -1); newCurveMesh = new ControlCurveMesh(newCurve, "dummy", app); newCurveNode.attachChild(newCurveMesh.getSlopeGeometry()); newCurveNode.attachChild(newCurveMesh.getTubeGeometry()); sceneNode.attachChild(newCurveNode); screenController.setMessage("ADDING A NEW FEATURE"); } else { newCurve.setPoints(ArrayUtils.add(newCurve.getPoints(), p)); newCurveNode.detachAllChildren(); addControlPointsToNode(newCurve.getPoints(), newCurveNode, -1); newCurveMesh.updateMesh(); newCurveNode.attachChild(newCurveMesh.getSlopeGeometry()); newCurveNode.attachChild(newCurveMesh.getTubeGeometry()); } newCurveNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); newCurveMesh.getSlopeGeometry().setShadowMode(RenderQueue.ShadowMode.Off); } private ControlPoint createNewControlPoint(float x, float y, float h) { ControlPoint[] points = newCurve==null ? new ControlPoint[0] : newCurve.getPoints(); return presets[selectedPreset].createControlPoint(x, y, h, points, map); } private void pickCurve(Ray ray) { CollisionResults results = new CollisionResults(); sceneNode.collideWith(ray, results); if (results.size()==0) { selectedCurveIndex = -1; selectedPointIndex = -1; selectCurve(-1, null); } else { CollisionResult result = results.getClosestCollision(); Geometry geom = result.getGeometry(); if (geom.getName().startsWith("Curve")) { int index = Integer.parseInt(geom.getName().substring("Curve".length())); selectedCurveIndex = index; selectedPointIndex = -1; selectCurve(index, null); } else if (geom.getName().startsWith("ControlPoint")) { String n = geom.getName().substring("ControlPoint".length()); String[] parts = n.split(":"); selectedCurveIndex = Integer.parseInt(parts[0]); selectedPointIndex = Integer.parseInt(parts[1]); selectCurve(selectedCurveIndex, featureCurves.get(selectedCurveIndex).getPoints()[selectedPointIndex]); } else { selectedCurveIndex = -1; selectedPointIndex = -1; selectCurve(-1, null); } } } //GUI-Interface public void guiAddCurves() { addNewCurves = true; } public void guiEditCurves() { addNewCurves = false; if (newCurve != null) { newCurveMesh = null; sceneNode.detachChild(newCurveNode); newCurveNode = null; newCurve = null; screenController.setMessage(""); } } private void selectCurve(int curveIndex, ControlPoint point) { screenController.selectCurve(curveIndex, point); } public void guiDeleteCurve() { if (selectedCurveIndex==-1) { return; } Node n = featureCurveNodes.remove(selectedCurveIndex); featureCurves.remove(selectedCurveIndex); sceneNode.detachChild(n); selectCurve(-1, null); } public void guiDeleteControlPoint() { if (selectedCurveIndex==-1 || selectedPointIndex==-1) { return; } ControlCurve c = featureCurves.get(selectedCurveIndex); if (c.getPoints().length<=2) { LOG.warning("Cannot delete control point, at least 2 points are required"); return; } featureCurves.remove(selectedCurveIndex); Node n = featureCurveNodes.remove(selectedCurveIndex); sceneNode.detachChild(n); c = new ControlCurve(ArrayUtils.remove(c.getPoints(), selectedPointIndex)); addFeatureCurve(c); } public void guiControlPointChanged() { if (selectedCurveIndex==-1 || selectedPointIndex==-1) { return; } System.out.println("control point changed: "+featureCurves.get(selectedCurveIndex).getPoints()[selectedPointIndex]); ControlCurveMesh mesh = featureCurveMesh.get(selectedCurveIndex); mesh.updateMesh(); } private void sendAvailablePresets() { String[] names = new String[presets.length]; for (int i=0; i<presets.length; ++i) { names[i] = presets[i].getName(); } screenController.setAvailablePresets(names); } public void guiPresetChanged(int index) { selectedPreset = index; } public void guiSolve() { solveDiffusion(); } private class DiffusionSolver { //settings private final double BETA_SCALE = 0.9; private final double ALPHA_SCALE = 0.5; private final double GRADIENT_SCALE = 0.01; private final float SLOPE_ALPHA_FACTOR = 0f; //input private final int size; private final ControlCurve[] curves; //matrices private Matrix elevation; //target elevation private Matrix alpha, beta; //factors specifying the influence of the gradient, smootheness and elevation private Matrix gradX, gradY; //the normalized direction of the gradient at this point private Matrix gradH; //the target gradient / height difference from the reference point specified by gradX, gradY private DiffusionSolver(int size, ControlCurve[] curves) { this.size = size; this.curves = curves; rasterize(); } /** * Rasterizes the control curves in the matrices */ private void rasterize() { elevation = new Matrix(size, size); alpha = new Matrix(size, size); beta = new Matrix(size, size); gradX = new Matrix(size, size); gradY = new Matrix(size, size); gradH = new Matrix(size, size); //render meshes Material vertexColorMat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); vertexColorMat.setBoolean("VertexColor", true); vertexColorMat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); vertexColorMat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); vertexColorMat.getAdditionalRenderState().setDepthTest(true); vertexColorMat.getAdditionalRenderState().setDepthWrite(true); Node elevationNode = new Node(); Node gradientNode = new Node(); for (ControlCurve curve : curves) { //sample curve int samples = 32; ControlPoint[] points = new ControlPoint[samples+1]; for (int i=0; i<=samples; ++i) { points[i] = curve.interpolate(i / (float) samples); } Geometry lineGeom = new Geometry("line", createLineMesh(points)); lineGeom.setMaterial(vertexColorMat); lineGeom.setQueueBucket(RenderQueue.Bucket.Gui); Geometry plateauGeom = new Geometry("plateau", createPlateauMesh(points)); plateauGeom.setMaterial(vertexColorMat); plateauGeom.setQueueBucket(RenderQueue.Bucket.Gui); elevationNode.attachChild(lineGeom); elevationNode.attachChild(plateauGeom); Geometry slopeGeom = new Geometry("slope", createSlopeMesh(points)); slopeGeom.setMaterial(vertexColorMat); slopeGeom.setQueueBucket(RenderQueue.Bucket.Gui); gradientNode.attachChild(slopeGeom); } elevationNode.setCullHint(Spatial.CullHint.Never); gradientNode.setCullHint(Spatial.CullHint.Never); for (Spatial s : elevationNode.getChildren()) { fillMatrix(elevation, s, true); } fillSlopeMatrix(gradientNode); vertexColorMat.setBoolean("VertexColor", false); vertexColorMat.setColor("Color", ColorRGBA.White); fillMatrix(beta, elevationNode, false); //copy existing heightmap data for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { elevation.set(x, y, elevation.get(x, y) - originalMap.getHeightAt(x, y)); } } alpha.timesEquals(ALPHA_SCALE); beta.timesEquals(BETA_SCALE); gradH.timesEquals(GRADIENT_SCALE); //save for debugging if (DEBUG_DIFFUSION_SOLVER) { saveMatrix(elevation, "diffusion/Elevation.png"); saveMatrix(beta, "diffusion/Beta.png"); saveMatrix(alpha, "diffusion/Alpha.png"); saveFloatMatrix(gradX, "diffusion/GradX.png",1); saveFloatMatrix(gradY, "diffusion/GradY.png",1); saveFloatMatrix(gradH, "diffusion/GradH.png",50); } LOG.info("curves rasterized"); } public Matrix oneIteration(Matrix last, int iteration) { Matrix mat = new Matrix(size, size); //add elevation constraint mat.plusEquals(elevation.arrayTimes(beta)); //add laplace constraint Matrix laplace = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; v += last.get(Math.max(0, x-1), y); v += last.get(Math.min(size-1, x+1), y); v += last.get(x, Math.max(0, y-1)); v += last.get(x, Math.min(size-1, y+1)); v /= 4.0; v *= 1 - alpha.get(x, y) - beta.get(x, y); laplace.set(x, y, v); } } mat.plusEquals(laplace); //add gradient constraint Matrix gradient = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; //v = gradH.get(x, y); double gx = gradX.get(x, y); double gy = gradY.get(x, y); if (gx==0 && gy==0) { v = 0; //no gradient } else { v += gx*gx*last.get(clamp(x-(int) Math.signum(gx)), y); v += gy*gy*last.get(x, clamp(y-(int) Math.signum(gy))); } gradient.set(x, y, v); } } Matrix oldGradient; if (DEBUG_DIFFUSION_SOLVER) { oldGradient = gradient.copy(); //Test } if (DEBUG_DIFFUSION_SOLVER) { saveFloatMatrix(gradient, "diffusion/Gradient"+iteration+".png",1); } Matrix gradChange = gradH.plus(gradient); gradChange.arrayTimesEquals(alpha); if (DEBUG_DIFFUSION_SOLVER) { saveFloatMatrix(gradChange, "diffusion/GradChange"+iteration+".png",1); } mat.plusEquals(gradChange); //Test if (DEBUG_DIFFUSION_SOLVER) { Matrix newGradient = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; v += gradX.get(x, y)*gradX.get(x, y) *mat.get(clamp(x-(int) Math.signum(gradX.get(x, y))), y); v += gradY.get(x, y)*gradY.get(x, y) *mat.get(x, clamp(y-(int) Math.signum(gradY.get(x, y)))); v -= mat.get(x, y); newGradient.set(x, y, -v); } } Matrix diff = oldGradient.minus(newGradient); saveFloatMatrix(diff, "diffusion/Diff"+iteration+".png",1); } return mat; } private int clamp(int i) { return Math.max(0, Math.min(size-1, i)); } private Mesh createLineMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length]; ColorRGBA[] col = new ColorRGBA[points.length]; for (int i=0; i<points.length; ++i) { pos[i] = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float height = points[i].hasElevation ? points[i].height : 0; col[i] = new ColorRGBA(height, height, height, 1); } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); mesh.setMode(Mesh.Mode.LineStrip); mesh.setLineWidth(1); return mesh; } private Mesh createPlateauMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*3]; ColorRGBA[] col = new ColorRGBA[points.length*3]; for (int i=0; i<points.length; ++i) { pos[3*i] = new Vector3f(points[i].x, points[i].y, points[i].height*100-100); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; pos[3*i + 1] = pos[3*i].add(points[i].plateau * -dy, points[i].plateau * dx, points[i].height*100-100); pos[3*i + 2] = pos[3*i].add(points[i].plateau * dy, points[i].plateau * -dx, points[i].height*100-100); float height = points[i].hasElevation ? points[i].height : 0; col[3*i] = new ColorRGBA(height, height, height, 1); col[3*i+1] = col[3*i]; col[3*i+2] = col[3*i]; } int[] index = new int[(points.length-1) * 12]; for (int i=0; i<points.length-1; ++i) { index[12*i] = 3*i; index[12*i + 1] = 3*i + 3; index[12*i + 2] = 3*i + 1; index[12*i + 3] = 3*i + 3; index[12*i + 4] = 3*i + 4; index[12*i + 5] = 3*i + 1; index[12*i + 6] = 3*i; index[12*i + 7] = 3*i + 2; index[12*i + 8] = 3*i + 3; index[12*i + 9] = 3*i + 3; index[12*i + 10] = 3*i + 2; index[12*i + 11] = 3*i + 5; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } private Mesh createSlopeMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*4]; ColorRGBA[] col = new ColorRGBA[points.length*4]; for (int i=0; i<points.length; ++i) { Vector3f p = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; pos[4*i + 0] = p.add(points[i].plateau * -dy, points[i].plateau * dx, 0); pos[4*i + 1] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * dx, 0); pos[4*i + 2] = p.add(points[i].plateau * dy, points[i].plateau * -dx, 0); pos[4*i + 3] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * -dx, 0); ColorRGBA c1, c2, c3, c4; c1 = new ColorRGBA(-dy/2 + 0.5f, dx/2 + 0.5f, -FastMath.sin(points[i].angle1) + 0.5f, 1); c2 = new ColorRGBA(c1.r, c1.g, c1.b, 0); c3 = new ColorRGBA(dy/2 + 0.5f, -dx/2 + 0.5f, -FastMath.sin(points[i].angle2) + 0.5f, 1); c4 = new ColorRGBA(c3.r, c3.g, c3.b, 0); col[4*i + 0] = c1; col[4*i + 1] = c2; col[4*i + 2] = c3; col[4*i + 3] = c4; } int[] index = new int[(points.length-1) * 12]; for (int i=0; i<points.length-1; ++i) { index[12*i] = 4*i; index[12*i + 1] = 4*i + 4; index[12*i + 2] = 4*i + 1; index[12*i + 3] = 4*i + 4; index[12*i + 4] = 4*i + 5; index[12*i + 5] = 4*i + 1; index[12*i + 6] = 4*i + 2; index[12*i + 7] = 4*i + 3; index[12*i + 8] = 4*i + 6; index[12*i + 9] = 4*i + 6; index[12*i + 10] = 4*i + 3; index[12*i + 11] = 4*i + 7; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } @Deprecated private Mesh createSlopeAlphaMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*6]; ColorRGBA[] col = new ColorRGBA[points.length*6]; for (int i=0; i<points.length; ++i) { Vector3f p = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; float factor = SLOPE_ALPHA_FACTOR; pos[6*i + 0] = p.add(points[i].plateau * -dy, points[i].plateau * dx, 0); pos[6*i + 1] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1*factor) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1*factor) * dx, 0); pos[6*i + 2] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * dx, 0); pos[6*i + 3] = p.add(points[i].plateau * dy, points[i].plateau * -dx, 0); pos[6*i + 4] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2*factor) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2*factor) * -dx, 0); pos[6*i + 5] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * -dx, 0); ColorRGBA c1 = new ColorRGBA(0, 0, 0, 1); ColorRGBA c2 = new ColorRGBA(1, 1, 1, 1); col[6*i + 0] = c1; col[6*i + 1] = c2; col[6*i + 2] = c1; col[6*i + 3] = c1; col[6*i + 4] = c2; col[6*i + 5] = c1; } int[] index = new int[(points.length-1) * 24]; for (int i=0; i<points.length-1; ++i) { index[24*i + 0] = 6*i; index[24*i + 1] = 6*i + 6; index[24*i + 2] = 6*i + 1; index[24*i + 3] = 6*i + 6; index[24*i + 4] = 6*i + 7; index[24*i + 5] = 6*i + 1; index[24*i + 6] = 6*i + 1; index[24*i + 7] = 6*i + 7; index[24*i + 8] = 6*i + 2; index[24*i + 9] = 6*i + 7; index[24*i + 10] = 6*i + 8; index[24*i + 11] = 6*i + 2; index[24*i + 12] = 6*i + 3; index[24*i + 13] = 6*i + 9; index[24*i + 14] = 6*i + 4; index[24*i + 15] = 6*i + 9; index[24*i + 16] = 6*i + 10; index[24*i + 17] = 6*i + 4; index[24*i + 18] = 6*i + 4; index[24*i + 19] = 6*i + 10; index[24*i + 20] = 6*i + 5; index[24*i + 21] = 6*i + 10; index[24*i + 22] = 6*i + 11; index[24*i + 23] = 6*i + 5; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } /** * Renders the given scene in a top-down manner in the given matrix * @param matrix * @param scene */ private void fillMatrix(Matrix matrix, Spatial scene, boolean max) { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); ViewPort view = new ViewPort("Off", cam); view.setClearFlags(true, true, true); FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); //retrive data ByteBuffer data = BufferUtils.createByteBuffer(size*size*4*4); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); data.rewind(); for (int y=0; y<size; ++y) { for (int x=0; x<size; ++x) { // byte d = data.get(); // matrix.set(x, y, (d & 0xff) / 255.0); // data.get(); data.get(); data.get(); double v = data.getFloat(); double old = matrix.get(x, y); if (max) { v = Math.max(v, old); } else { v += old; } matrix.set(x, y, v); data.getFloat(); data.getFloat(); data.getFloat(); } } } /** * Renders the given scene in a top-down manner in the given matrix * @param matrix * @param scene */ private void fillSlopeMatrix(Spatial scene) { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); ViewPort view = new ViewPort("Off", cam); view.setClearFlags(true, true, true); view.setBackgroundColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0f)); FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); //retrive data ByteBuffer data = BufferUtils.createByteBuffer(size*size*4*4); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); data.rewind(); for (int y=0; y<size; ++y) { for (int x=0; x<size; ++x) { // double gx = (((data.get() & 0xff) / 256.0) - 0.5) * 2; // double gy = (((data.get() & 0xff) / 256.0) - 0.5) * 2; double gx = (data.getFloat() - 0.5) * 2; double gy = (data.getFloat() - 0.5) * 2; double s = Math.sqrt(gx*gx + gy*gy); if (s==0) { gx=0; gy=0; s=1; } gradX.set(x, y, (gx / s) + gradX.get(x, y)); gradY.set(x, y, (gy / s) + gradY.get(x, y)); // double v = (((data.get() & 0xff) / 255.0) - 0.5); double v = (data.getFloat() - 0.5); if (Math.abs(v)<0.002) { v=0; } gradH.set(x, y, v + gradH.get(x, y)); // data.get(); double a = data.getFloat(); alpha.set(x, y, a); } } } private void saveMatrix(Matrix matrix, String filename) { byte[] buffer = new byte[size*size]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) (matrix.get(x, y) * 255); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } private void saveFloatMatrix(Matrix matrix, String filename, double scale) { byte[] buffer = new byte[size*size]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) ((matrix.get(x, y)*scale/2 + 0.5) * 255); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } } }
package org.usfirst.frc.team3414.logger; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; public class LogData { private final String logFile = "/home/lvuser/logger3414.log"; private static LogData logData = null; private String cr = System.getProperty("line.separator"); private SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss - "); public static LogData getInstance() { if (logData == null) { logData = new LogData(); } return logData; } /** * Record text to Log located in "/home/lvuser/logger3414.log" * @param buffer is a string of text to be logged */ public synchronized void record(String buffer) { try { write(buffer); } catch (IOException e) { System.err.println("Error writing to log " + e.getMessage()); } } /** * write to logfile on roborio * * @param buffer * @throws IOException */ protected void write(String buffer) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(new File(this.logFile))); out.append(getTimeStamp()).append(buffer).append(cr); out.close(); } private String getTimeStamp() { return this.dateFormater.format(new GregorianCalendar().getTime()); } }
package protocolsupport.injector; import java.lang.reflect.Field; import java.util.Iterator; import java.util.Map; import org.bukkit.Bukkit; import net.minecraft.server.v1_11_R1.Block; import net.minecraft.server.v1_11_R1.Blocks; import net.minecraft.server.v1_11_R1.IBlockData; import net.minecraft.server.v1_11_R1.Item; import net.minecraft.server.v1_11_R1.ItemAnvil; import net.minecraft.server.v1_11_R1.ItemBlock; import net.minecraft.server.v1_11_R1.ItemWaterLily; import net.minecraft.server.v1_11_R1.MinecraftKey; import net.minecraft.server.v1_11_R1.RegistryMaterials; import net.minecraft.server.v1_11_R1.TileEntity; import protocolsupport.server.block.BlockAnvil; import protocolsupport.server.block.BlockEnchantTable; import protocolsupport.server.block.BlockWaterLily; import protocolsupport.server.tileentity.TileEntityEnchantTable; import protocolsupport.utils.ReflectionUtils; public class ServerInjector { public static void inject() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { registerTileEntity(TileEntityEnchantTable.class, "EnchantTable"); registerBlock(116, "enchanting_table", new BlockEnchantTable()); ItemBlock itemanvil = new ItemAnvil(new BlockAnvil()); itemanvil.c("anvil"); registerBlock(145, "anvil", itemanvil); registerBlock(111, "waterlily", new ItemWaterLily(new BlockWaterLily())); fixBlocksRefs(); Bukkit.resetRecipes(); } @SuppressWarnings("unchecked") private static void registerTileEntity(Class<? extends TileEntity> entityClass, String name) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { RegistryMaterials<MinecraftKey, Class<? extends TileEntity>> registry = (RegistryMaterials<MinecraftKey, Class<? extends TileEntity>>) ReflectionUtils.getField(TileEntity.class, "f").get(null); registry.a(new MinecraftKey(name), entityClass); } private static void registerBlock(int id, String name, Block block) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { registerBlock(id, name, new ItemBlock(block)); } @SuppressWarnings("unchecked") private static void registerBlock(int id, String name, ItemBlock itemblock) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { MinecraftKey stringkey = new MinecraftKey(name); Block block = itemblock.getBlock(); Block.REGISTRY.a(id, stringkey, block); Iterator<IBlockData> blockdataiterator = block.s().a().iterator(); while (blockdataiterator.hasNext()) { IBlockData blockdata = blockdataiterator.next(); final int stateId = (id << 4) | block.toLegacyData(blockdata); Block.REGISTRY_ID.a(blockdata, stateId); } Item.REGISTRY.a(id, stringkey, itemblock); ((Map<Block, Item>) ReflectionUtils.setAccessible(Item.class.getDeclaredField("a")).get(null)).put(block, itemblock); } private static void fixBlocksRefs() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { for (Field field : Blocks.class.getDeclaredFields()) { field.setAccessible(true); if (Block.class.isAssignableFrom(field.getType())) { Block block = (Block) field.get(null); Block newblock = Block.getById(Block.getId(block)); if (block != newblock) { Iterator<IBlockData> blockdataiterator = block.s().a().iterator(); while (blockdataiterator.hasNext()) { IBlockData blockdata = blockdataiterator.next(); ReflectionUtils.getField(blockdata.getClass(), "a").set(blockdata, block); } ReflectionUtils.setStaticFinalField(field, newblock); } } } } }
package com.yox89.ld32.actors; import java.util.ArrayList; import box2dLight.ConeLight; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.RotateToAction; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.yox89.ld32.Physics; import com.yox89.ld32.particles.ParticleEffect; import com.yox89.ld32.particles.ParticlePool; import com.yox89.ld32.raytracing.RayDispatcher.Dispatcher; import com.yox89.ld32.raytracing.RayDispatcher.Ray; import com.yox89.ld32.raytracing.RayDispatcher.RayRequest; import com.yox89.ld32.raytracing.RayDispatcher.RayTarget; import com.yox89.ld32.screens.TiledLevelScreen; import com.yox89.ld32.util.Assets; import com.yox89.ld32.util.Collision; import com.yox89.ld32.util.PhysicsUtil; import com.yox89.ld32.util.PhysicsUtil.BodyParams; public class GhostActor extends PhysicsActor implements Disposable, RayTarget, GamePositioned { private static final float SPEED = 3f; private final Texture mTexture; private final boolean isNotMoving; private float angleDegree; private final TiledLevelScreen mOwner; private ConeLight mLightVision; public GhostActor(TiledLevelScreen owner, Physics physicsWorld, ArrayList<Vector2> positions, float angleDegree) { isNotMoving = positions.size() <= 1; this.angleDegree = angleDegree; mOwner = owner; final Texture img = new Texture("ghost_pixelart.png"); this.mTexture = img; mLightVision = new ConeLight(physicsWorld.rayHandler, 10, new Color(1, 0, 1, .75f), 4f, 0f, 0f, 0f, 30f); mLightVision.setXray(true); final Vector2[] polygonShape = this.getShapeVertices(); this.initPhysicsBody(PhysicsUtil.createBody(new BodyParams( physicsWorld.world) { @Override public BodyType getBodyType() { return BodyType.DynamicBody; } @Override public short getCollisionType() { return Collision.GHOST_VISION; } @Override public short getCollisionMask() { return Collision.PLAYER; } @Override public void setShape(PolygonShape ps) { ps.set(polygonShape); } @Override public boolean isSensor() { return true; } })); this.setSize(1f, 1f); assert (positions.size() > 0) : "The ghost must have at least one position"; Vector2 initialPosition = positions.get(0); this.setPosition(initialPosition.x, initialPosition.y); this.setupActions(positions); final FixtureDef ghostBody = new FixtureDef(); ghostBody.filter.categoryBits = Collision.GHOST_BODY; ghostBody.filter.maskBits = Collision.NONE; ghostBody.isSensor = true; final CircleShape cs = new CircleShape(); if (isNotMoving) { final Vector2 off = new Vector2(0.5f, 0.5f); if (angleDegree < 90) { off.set(.5f, .5f); } else if (angleDegree < 180) { off.set(.5f, -.5f); } else if (angleDegree < 270) { off.set(-.5f, -.5f); } else { off.set(-.5f, .5f); } cs.setPosition(off); } cs.setRadius(.45f); ghostBody.shape = cs; getPhysicsBody().createFixture(ghostBody).setUserData(this); cs.dispose(); } @Override public void act(float delta) { super.act(delta); mLightVision.setDirection(getRotation()); if (isNotMoving) { mLightVision.setPosition(getX() + getWidth() / 2, getY() + getHeight() / 2); } else { mLightVision.setPosition(getX(), getY()); } } private final Vector2 gamePosition = new Vector2(-1, -1); @Override public Vector2 getGamePosition() { return gamePosition; } @Override public void setPosition(float x, float y) { gamePosition.set(x, y); super.setPosition(x, y); } private Vector2[] getShapeVertices() { Vector2[] vertices = new Vector2[3]; float offset = 0f; if (isNotMoving) { offset = 0.5f; } if (angleDegree < 90) { vertices[0] = new Vector2(0f + offset, 0f + offset); vertices[1] = new Vector2(4f + offset, -2f + offset); vertices[2] = new Vector2(4f + offset, 2f + offset); } else if (angleDegree < 180) { vertices[0] = new Vector2(0f + offset, 0f - offset); vertices[1] = new Vector2(4f + offset, -2f - offset); vertices[2] = new Vector2(4f + offset, 2f - offset); } else if (angleDegree < 270) { vertices[0] = new Vector2(0f - offset, 0f - offset); vertices[1] = new Vector2(4f - offset, -2f - offset); vertices[2] = new Vector2(4f - offset, 2f - offset); } else { vertices[0] = new Vector2(0f - offset, 0f + offset); vertices[1] = new Vector2(4f - offset, -2f + offset); vertices[2] = new Vector2(4f - offset, 2f + offset); } return vertices; } private void setupActions(ArrayList<Vector2> positions) { if (positions.size() > 1) { Vector2 startPosition = positions.get(0); Vector2 currentPosition = startPosition; Action[] actions = new Action[positions.size()]; for (int i = 1; i < positions.size(); i++) { Vector2 newPosition = positions.get(i); final Vector2 diff = new Vector2(newPosition.x - currentPosition.x, newPosition.y - currentPosition.y); float length = diff.len(); final float duration = length / SPEED; actions[i - 1] = Actions.sequence(Actions.parallel( Actions.run(new Runnable() { @Override public void run() { RotateToAction rotateToAction = getRotateActionUsingClosestDirection( diff.angle(), duration / 4); addAction(rotateToAction); } }), Actions.moveTo(newPosition.x, newPosition.y, duration))); diff.angle(); currentPosition = newPosition; } final Vector2 diff = new Vector2(startPosition.x - currentPosition.x, startPosition.y - currentPosition.y); float length = diff.len(); final float duration = length / SPEED; actions[actions.length - 1] = Actions.parallel( Actions.run(new Runnable() { @Override public void run() { RotateToAction rotateToAction = getRotateActionUsingClosestDirection( diff.angle(), duration / 4); addAction(rotateToAction); } }), Actions.moveTo(startPosition.x, startPosition.y, duration)); SequenceAction moveActions = Actions.sequence(actions); RotateToAction rotateToAction = getRotateActionUsingClosestDirection( diff.angle(), 0f); addAction(rotateToAction); this.addAction(Actions.forever(moveActions)); } } public RotateToAction getRotateActionUsingClosestDirection( float targetAngle, float duration) { float curr = getRotation(); if (curr >= 360f) { curr %= 360f; } else if (curr <= -360f) { curr = 360f + (curr % -360f); } setRotation(curr); final float diff = targetAngle - curr; if (Math.abs(diff) > 180f) { setRotation(curr - 360f); } return Actions.rotateTo(targetAngle, duration); } boolean mIsHit = false; @Override public void onHitWithRay(Ray ray, Dispatcher dispatcher) { mIsHit = true; addAction(Actions.removeActor()); ParticleEffect pe = ParticlePool.get(); float ang = getRotation(); Vector2 sides = new Vector2(getWidth(), getHeight()); sides.rotate(ang); if (isNotMoving) { pe.setPosition(getX(), getY()); } else { pe.setPosition(getX() - getWidth() / 2, getY() - getHeight() / 2); } pe.setSize(getWidth(), getHeight()); pe.init(Assets.blood, 200.0f, 25, .5f); getParent().addActor(pe); Assets.beaver_death.play(); if (mLightVision.isActive()) { mLightVision.setActive(false); mLightVision.remove(); } Array<RayRequest> reqs = new Array<RayRequest>(); reqs.add(new RayRequest(ray.color, ray.dst, ray.direction)); dispatcher.dispatch(reqs); for (Actor a : getStage().getActors()) { if (a instanceof GhostActor && !((GhostActor) a).mIsHit) { return; } } mOwner.onAllGhostsDead(); } @Override public void draw(Batch batch, float parentAlpha) { float x, y, originX, originY; if (isNotMoving) { x = getX(); y = getY(); originX = getOriginX() + getWidth() / 2; originY = getOriginY() + getHeight() / 2; } else { x = getX() - getWidth() / 2; y = getY() - getHeight() / 2; originX = getOriginX() + getWidth() / 2; originY = getOriginY() + getHeight() / 2; } batch.draw(mTexture, x, y, originX, originY, getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation() + 180f, 0, 0, mTexture.getWidth(), mTexture.getHeight(), false, false); } @Override public void dispose() { mTexture.dispose(); mLightVision.dispose(); } }
package server; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import server.query.Query; import server.query.QueryType; import server.query.SubscriberQuery; enum ConnectionHandlerType{ UNKNOWN, SENDER, // client sends message through this socket, server only listens RECEIVER // client receives message through this socket, server only sends } public class ConnectionHandler implements Runnable{ private static final Logger logger = Logger.getLogger( Server.class.getName() ); private int id; private Server server; private Socket socket; private ObjectOutputStream outputStream; private ObjectInputStream inputStream; private boolean running; private ConnectionHandlerType type; private LinkedBlockingQueue<Object> toSend; public ConnectionHandler(int id, Socket socket, Server server) throws IOException{ this.id = id; this.socket = socket; this.server = server; this.outputStream = new ObjectOutputStream(socket.getOutputStream()); this.inputStream = new ObjectInputStream(socket.getInputStream()); this.running = true; this.type = ConnectionHandlerType.UNKNOWN; this.toSend = new LinkedBlockingQueue<Object>(); } @Override public void run() { // Register this socket as a CONSUMER or PRODUCER try { this.handleRegister(); } catch (Exception e) { this.running = false; } // Execute different actions based on the type of this socket while(running){ try { if(this.type == ConnectionHandlerType.SENDER){ handleReceivedMessages(); }else if(this.type == ConnectionHandlerType.RECEIVER){ sendMessages(); } } catch (Exception e) { this.running = false; } } try { this.outputStream.close(); this.inputStream.close(); this.socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Main method for executing a consumer action. * Receives a message, handles it and then sends the ACK. * @throws ClassNotFoundException * @throws IOException */ private void handleReceivedMessages() throws ClassNotFoundException, IOException{ Query query = (Query) this.inputStream.readObject(); switch(query.getType()){ case SUBSCRIBE: this.handleSubscribe(query); break; case UNSUBSCRIBE: this.handleUnsubscribe(query); break; case CREATE_TOPIC: this.handleCreateTopic(query); break; case DELETE_TOPIC: this.handleDeleteTopic(query); break; } // Send ACK Query ack = new Query(query.getClientId(), QueryType.ACK); this.server.getReceivers().get(query.getClientId()).getToSend().add(ack); } /** * Main method for executing a producer action. * Waits until a message is available in the queue and then sends the message. * @throws InterruptedException * @throws IOException */ private void sendMessages() throws InterruptedException, IOException{ Object obj = this.toSend.take(); this.outputStream.writeObject(obj); } /** * Handle the socket registration * @throws Exception */ private void handleRegister() throws Exception { Query query = (Query) this.inputStream.readObject(); switch(query.getType()){ case REGISTER_SENDER: this.handleRegisterSender(query); break; case REGISTER_RECEIVER: this.handleRegisterReceiver(query); break; default: throw new Exception("Expecting REGISTER_CONSUMER or REGISTER_PRODUCER query."); } } /** * Register this socket as a RECEIVER * @param query * @throws IOException */ private void handleRegisterReceiver(Query query) throws IOException { logger.log(Level.INFO, "Producer registered ({0})", this.id); this.type = ConnectionHandlerType.RECEIVER; // Send ACK Query ack = new Query(query.getClientId(), QueryType.REGISTER_RECEIVER_ACK); this.outputStream.writeObject(ack); // Register this socket in the server this.server.handleRegisterReceiver(query, this.id); } /** * Register this socket as a SENDER * @param query * @throws IOException */ private void handleRegisterSender(Query query) throws IOException { logger.log(Level.INFO, "Consumer registered ({0})", this.id); this.type = ConnectionHandlerType.SENDER; // Send ACK Query ack = new Query(query.getClientId(), QueryType.REGISTER_SENDER_ACK); this.outputStream.writeObject(ack); // Register this socket in the server this.server.handleRegisterSender(query, this.id); } private void handleDeleteTopic(Query query) { // TODO Auto-generated method stub } private void handleCreateTopic(Query query) { // TODO Auto-generated method stub } private void handleUnsubscribe(Query query) { // TODO Auto-generated method stub } private void handleSubscribe(Query query) { // TODO Auto-generated method stub } public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public ObjectOutputStream getOutputStream() { return outputStream; } public void setOutputStream(ObjectOutputStream outputStream) { this.outputStream = outputStream; } public ObjectInputStream getInputStream() { return inputStream; } public void setInputStream(ObjectInputStream inputStream) { this.inputStream = inputStream; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } public int getId() { return id; } public void setId(int id) { this.id = id; } public ConnectionHandlerType getType() { return type; } public void setType(ConnectionHandlerType type) { this.type = type; } public LinkedBlockingQueue<Object> getToSend() { return toSend; } public void setToSend(LinkedBlockingQueue<Object> toSend) { this.toSend = toSend; } }
/* * $Log: JtaUtil.java,v $ * Revision 1.16 2008-01-11 09:59:33 europe\L190409 * changed attributed definitions to Spring's * removed some functions * * Revision 1.15 2007/12/10 10:23:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed some functions * * Revision 1.14 2007/11/21 13:18:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added setRollBackOnly * * Revision 1.13 2007/08/10 11:22:29 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added non-argument inTransaction() * * Revision 1.12 2007/06/08 12:18:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * do not rollback after exception on commit if status is already final * * Revision 1.11 2007/05/08 16:01:21 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed stacktrace from debug-logging while obtaining user-transaction * * Revision 1.10 2007/02/12 14:12:03 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.9 2006/09/18 11:46:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * lookup UserTransaction only when necessary * * Revision 1.8 2006/09/14 11:47:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * optimized transactionStateCompatible() * * Revision 1.7 2006/08/21 15:14:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of transaction attribute handling * configuration of user transaction url in appconstants.properties * * Revision 1.6 2005/09/08 15:58:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added logging * * Revision 1.5 2004/10/05 09:57:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made version public * * Revision 1.4 2004/03/31 15:03:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed javadoc * * Revision 1.3 2004/03/26 10:42:38 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.2 2004/03/26 09:50:52 Johan Verrips <johan.verrips@ibissource.org> * Updated javadoc * * Revision 1.1 2004/03/23 17:14:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.util; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.apache.log4j.Logger; import org.springframework.transaction.TransactionDefinition; /** * Utility functions for JTA * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class JtaUtil { public static final String version="$RCSfile: JtaUtil.java,v $ $Revision: 1.16 $ $Date: 2008-01-11 09:59:33 $"; private static Logger log = LogUtil.getLogger(JtaUtil.class); private static final String USERTRANSACTION_URL1_KEY="jta.userTransactionUrl1"; private static final String USERTRANSACTION_URL2_KEY="jta.userTransactionUrl2"; public static final int TRANSACTION_ATTRIBUTE_DEFAULT=TransactionDefinition.PROPAGATION_SUPPORTS; public static final String TRANSACTION_ATTRIBUTE_REQUIRED_STR="Required"; public static final String TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR="RequiresNew"; public static final String TRANSACTION_ATTRIBUTE_MANDATORY_STR="Mandatory"; public static final String TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR="NotSupported"; public static final String TRANSACTION_ATTRIBUTE_SUPPORTS_STR="Supports"; public static final String TRANSACTION_ATTRIBUTE_NEVER_STR="Never"; public static final String transactionAttributes[]= { TRANSACTION_ATTRIBUTE_REQUIRED_STR, TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR, TRANSACTION_ATTRIBUTE_MANDATORY_STR, TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR, TRANSACTION_ATTRIBUTE_SUPPORTS_STR, TRANSACTION_ATTRIBUTE_NEVER_STR }; public static final int transactionAttributeNums[]= { TransactionDefinition.PROPAGATION_REQUIRED, TransactionDefinition.PROPAGATION_REQUIRES_NEW, TransactionDefinition.PROPAGATION_MANDATORY, TransactionDefinition.PROPAGATION_NOT_SUPPORTED, TransactionDefinition.PROPAGATION_SUPPORTS, TransactionDefinition.PROPAGATION_NEVER }; private static UserTransaction utx; /** * returns a meaningful string describing the transaction status. */ public static String displayTransactionStatus(int status) { switch (status) { case Status.STATUS_ACTIVE : return status+"=STATUS_ACTIVE:"+ " A transaction is associated with the target object and it is in the active state."; case Status.STATUS_COMMITTED : return status+"=STATUS_COMMITTED:"+ " A transaction is associated with the target object and it has been committed."; case Status.STATUS_COMMITTING : return status+"=STATUS_COMMITTING:"+ " A transaction is associated with the target object and it is in the process of committing."; case Status.STATUS_MARKED_ROLLBACK : return status+"=STATUS_MARKED_ROLLBACK:"+" A transaction is associated with the target object and it has been marked for rollback, perhaps as a result of a setRollbackOnly operation."; case Status.STATUS_NO_TRANSACTION : return status+"=STATUS_NO_TRANSACTION:"+ " No transaction is currently associated with the target object."; case Status.STATUS_PREPARED : return status+"=STATUS_PREPARED:"+ " A transaction is associated with the target object and it has been prepared."; case Status.STATUS_PREPARING : return status+"=STATUS_PREPARING:"+ " A transaction is associated with the target object and it is in the process of preparing."; case Status.STATUS_ROLLEDBACK : return status+"=STATUS_ROLLEDBACK:"+ " A transaction is associated with the target object and the outcome has been determined to be rollback."; case Status.STATUS_ROLLING_BACK : return status+"=STATUS_ROLLING_BACK:"+ " A transaction is associated with the target object and it is in the process of rolling back."; case Status.STATUS_UNKNOWN : return status+"=STATUS_UNKNOWN:"+ " A transaction is associated with the target object but its current status cannot be determined."; default : return "unknown transaction status"; } } // /** // * Convenience function for {@link #displayTransactionStatus(int status)} // */ // public static String displayTransactionStatus(Transaction tx) { // try { // return displayTransactionStatus(tx.getStatus()); // } catch (Exception e) { // return "exception obtaining transaction status from transaction ["+tx+"]: "+e.getMessage(); /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus(UserTransaction utx) { try { return displayTransactionStatus(utx.getStatus()); } catch (Exception e) { return "exception obtaining transaction status from transaction ["+utx+"]: "+e.getMessage(); } } // /** // * Convenience function for {@link #displayTransactionStatus(int status)} // */ // public static String displayTransactionStatus(TransactionManager tm) { // try { // return displayTransactionStatus(tm.getStatus()); // } catch (Exception e) { // return "exception obtaining transaction status from transactionmanager ["+tm+"]: "+e.getMessage(); // /** // * Convenience function for {@link #displayTransactionStatus(int status)} // */ // public static String displayTransactionStatus(TransactionStatus txStatus) { // String result=""; // if (txStatus instanceof DefaultTransactionStatus) { // Object tr = ((DefaultTransactionStatus)txStatus).getTransaction(); // if (tr instanceof JtaTransactionObject) { // JtaTransactionObject jto=(JtaTransactionObject)tr; // UserTransaction utr=jto.getUserTransaction(); // result= "transaction: "+ToStringBuilder.reflectionToString(utr, ToStringStyle.MULTI_LINE_STYLE);; // } else { // result= "transaction: "+ToStringBuilder.reflectionToString(tr, ToStringStyle.MULTI_LINE_STYLE);; // } else { // result= "txStatus: "+ToStringBuilder.reflectionToString(txStatus, ToStringStyle.MULTI_LINE_STYLE); // return result; /** * Convenience function for {@link #displayTransactionStatus(int status)} */ public static String displayTransactionStatus() { UserTransaction utx; try { utx = getUserTransaction(); } catch (Exception e) { return "exception obtaining user transaction: "+e.getMessage(); } return displayTransactionStatus(utx); } /** * returns true if the current thread is associated with a transaction */ private static boolean inTransaction(UserTransaction utx) throws SystemException { return utx != null && utx.getStatus() != Status.STATUS_NO_TRANSACTION; } public static boolean inTransaction() throws SystemException, NamingException { return inTransaction(getUserTransaction()); } /** * Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions. */ // public static UserTransaction getUserTransaction(Context ctx, String userTransactionUrl) throws NamingException { // if (utx == null) { // log.debug("looking up UserTransaction ["+userTransactionUrl+"] in context ["+ctx.toString()+"]"); // utx = (UserTransaction)ctx.lookup(userTransactionUrl); // return utx; /** * Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions. */ public static UserTransaction getUserTransaction() throws NamingException { if (utx == null) { Context ctx= (Context) new InitialContext(); String url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL1_KEY,null); log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]"); try { utx = (UserTransaction)ctx.lookup(url); } catch (Exception e) { log.debug("Could not lookup UserTransaction from url ["+url+"], will try alternative uri: "+e.getMessage()); url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL2_KEY,null); log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]"); utx = (UserTransaction)ctx.lookup(url); } } return utx; } public static int getTransactionAttributeNum(String transactionAttribute) { int i=transactionAttributes.length-1; while (i>=0 && !transactionAttributes[i].equalsIgnoreCase(transactionAttribute)) i--; // try next return transactionAttributeNums[i]; } public static String getTransactionAttributeString(int transactionAttribute) { if (transactionAttribute<0 || transactionAttribute>=transactionAttributes.length) { return "UnknownTransactionAttribute:"+transactionAttribute; } switch (transactionAttribute) { case TransactionDefinition.PROPAGATION_MANDATORY: return TRANSACTION_ATTRIBUTE_MANDATORY_STR; case TransactionDefinition.PROPAGATION_NEVER: return TRANSACTION_ATTRIBUTE_NEVER_STR; case TransactionDefinition.PROPAGATION_NOT_SUPPORTED: return TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR; case TransactionDefinition.PROPAGATION_SUPPORTS: return TRANSACTION_ATTRIBUTE_SUPPORTS_STR; case TransactionDefinition.PROPAGATION_REQUIRED: return TRANSACTION_ATTRIBUTE_REQUIRED_STR; case TransactionDefinition.PROPAGATION_REQUIRES_NEW: return TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR; default: return null; } } public static boolean transactionStateCompatible(int transactionAttribute) throws SystemException, NamingException { if (transactionAttribute==TransactionDefinition.PROPAGATION_NEVER) { return !inTransaction(getUserTransaction()); } else if (transactionAttribute==TransactionDefinition.PROPAGATION_MANDATORY) { return inTransaction(getUserTransaction()); } return true; } // public static boolean isolationRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException { // if (transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW && // transactionAttribute!=TRANSACTION_ATTRIBUTE_NOT_SUPPORTED) { // return false; // if (!transactionStateCompatible(transactionAttribute)) { // throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]"); // UserTransaction utx = getUserTransaction(); // return inTransaction(utx) && // (transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW || // transactionAttribute==TRANSACTION_ATTRIBUTE_NOT_SUPPORTED); // public static boolean newTransactionRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException { // if (!transactionStateCompatible(transactionAttribute)) { // throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]"); // if (transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRED) { // UserTransaction utx = getUserTransaction(); // return !inTransaction(utx); // return transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW; // private static boolean stateEvaluationRequired(int transactionAttribute) { // return transactionAttribute>=0 && // transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW && // transactionAttribute!=TRANSACTION_ATTRIBUTE_SUPPORTS; // public static void startTransaction() throws NamingException, NotSupportedException, SystemException { // log.debug("starting new transaction"); // utx=getUserTransaction(); // utx.begin(); // finishTransaction(false); // UserTransaction utx=JtaUtil.getUserTransaction(); // if (inTransaction(utx)) { // log.debug("marking transaction for rollback"); // utx.setRollbackOnly(); // utx=getUserTransaction(); // try { // if (inTransaction(utx) && !rollbackonly) { // log.debug("committing transaction"); // utx.commit(); // } else { // log.debug("rolling back transaction"); // utx.rollback(); // } catch (Throwable t1) { // try { // int currentStatus=-1; // try { // currentStatus=utx.getStatus(); // } catch (Throwable t) { // log.debug("caught exception obtaining transaction status: "+ t.getMessage()); // if (currentStatus != Status.STATUS_COMMITTED && // currentStatus != Status.STATUS_NO_TRANSACTION && // currentStatus != Status.STATUS_ROLLEDBACK && // currentStatus != Status.STATUS_ROLLING_BACK) { // log.warn("current status ["+displayTransactionStatus(currentStatus)+"], trying to roll back transaction after exception ",t1); // utx.rollback(); // } else { // log.info("current status ["+displayTransactionStatus(currentStatus)+"], will not issue rollback command"); // } catch (Throwable t2) { // log.warn("exception rolling back transaction",t2); }
package com.parc.ccn.data.security; import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import javax.xml.stream.XMLStreamException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.params.KeyParameter; import com.parc.ccn.Library; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.util.CCNEncodableObject; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.security.crypto.CCNDigestHelper; import com.parc.ccn.security.crypto.jce.AESWrapWithPad; import com.parc.ccn.security.crypto.jce.AESWrapWithPadEngine; public class WrappedKey extends GenericXMLEncodable implements XMLEncodable { protected static final String WRAPPED_KEY_ELEMENT = "WrappedKey"; protected static final String WRAPPING_KEY_IDENTIFIER_ELEMENT = "WrappingKeyIdentifier"; protected static final String WRAPPING_KEY_NAME_ELEMENT = "WrappingKeyName"; protected static final String WRAP_ALGORITHM_ELEMENT = "WrapAlgorithm"; protected static final String KEY_ALGORITHM_ELEMENT = "KeyAlgorithm"; protected static final String LABEL_ELEMENT = "Label"; protected static final String ENCRYPTED_NONCE_KEY_ELEMENT = "EncryptedNonceKey"; protected static final String ENCRYPTED_KEY_ELEMENT = "EncryptedKey"; protected static final String NONCE_KEY_ALGORITHM = "AES"; protected static final int NONCE_KEY_LENGTH = 128; public class WrappingKeyName extends ContentName { public WrappingKeyName(ContentName name) { super(name); } public WrappingKeyName() {} @Override public String contentNameElement() { return WRAPPING_KEY_NAME_ELEMENT; } } public static class WrappedKeyObject extends CCNEncodableObject<WrappedKey> { public WrappedKeyObject() throws ConfigurationException, IOException { super(WrappedKey.class); } public WrappedKeyObject(ContentName name, CCNLibrary library) throws XMLStreamException, IOException { super(WrappedKey.class, name, library); } public WrappedKeyObject(ContentName name) throws XMLStreamException, IOException, ConfigurationException { super(WrappedKey.class, name); } public WrappedKeyObject(ContentName name, WrappedKey wrappedKey, CCNLibrary library) { super(WrappedKey.class, name, wrappedKey, library); } public WrappedKeyObject(ContentName name, WrappedKey wrappedKey) throws ConfigurationException, IOException { super(WrappedKey.class, name, wrappedKey); } public WrappedKeyObject(ContentObject block, CCNLibrary library) throws XMLStreamException, IOException { super(WrappedKey.class, block, library); } public WrappedKey wrappedKey() { return data(); } } private static final Map<String,String> _WrapAlgorithmMap = new HashMap<String,String>(); byte [] _wrappingKeyIdentifier; WrappingKeyName _wrappingKeyName; String _wrapAlgorithm; String _keyAlgorithm; String _label; byte [] _encryptedNonceKey; byte [] _encryptedKey; static { // In Java 1.5, many of these require BouncyCastle. They are typically built in in 1.6. _WrapAlgorithmMap.put("AES", "AESWRAPWITHPAD"); _WrapAlgorithmMap.put("RSA", "RSA/NONE/OAEPWithSHA256AndMGF1Padding"); } /** * Factory methods to build wrapped keys out of their components, wrapping * in the process. For the moment, these use only the default wrapping algorithms. */ public static WrappedKey wrapKey(Key keyToBeWrapped, String keyAlgorithm, String keyLabel, Key wrappingKey) throws InvalidKeyException { String wrappingAlgorithm = wrapAlgorithmForKey(wrappingKey.getAlgorithm()); byte [] wrappedNonceKey = null; byte [] wrappedKey = null; if (wrappingAlgorithm.equalsIgnoreCase("AESWrapWithPad")) { byte [] encodedKeyToBeWrapped = keyToBeWrapped.getEncoded(); wrappedKey = AESWrapWithPad(wrappingKey, encodedKeyToBeWrapped, 0, encodedKeyToBeWrapped.length); } else { Cipher wrapCipher = null; try { wrapCipher = Cipher.getInstance(wrappingAlgorithm); } catch (NoSuchAlgorithmException e) { Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm."); throw new InvalidKeyException("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm."); } catch (NoSuchPaddingException e) { Library.logger().warning("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm."); throw new InvalidKeyException("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm"); } wrapCipher.init(Cipher.WRAP_MODE, wrappingKey); // If we are dealing with a short-block cipher, like RSA, we need to // interpose a nonce key. Key nonceKey = null; try { int wrappedKeyType = getCipherType(keyToBeWrapped.getAlgorithm()); // If we're wrapping a private key in a public key, need to handle multi-block // keys. Probably don't want to do that with ECB mode. ECIES already acts // as a hybrid cipher, so we don't need to do this for that. if (((Cipher.PRIVATE_KEY == wrappedKeyType) || (Cipher.PUBLIC_KEY == wrappedKeyType)) && (wrappingKey instanceof PublicKey) && (!wrappingKey.getAlgorithm().equals("ECIES"))) { nonceKey = generateNonceKey(); //try { // We know the nonce key is an AES key. Use standard wrap algorithm. // DKS -- fix when have provider. //Cipher nonceCipher = Cipher.getInstance(wrapAlgorithmForKey(nonceKey.getAlgorithm())); //nonceCipher.init(Cipher.WRAP_MODE, nonceKey); //wrappedKey = nonceCipher.wrap(keyToBeWrapped); byte [] encodedKeyToBeWrapped = keyToBeWrapped.getEncoded(); wrappedKey = AESWrapWithPad(nonceKey, encodedKeyToBeWrapped, 0, encodedKeyToBeWrapped.length); //} catch (NoSuchAlgorithmException nsex) { // Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); // Library.warningStackTrace(nsex); // throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); wrappedNonceKey = wrapCipher.wrap(nonceKey); } else { wrappedKey = wrapCipher.wrap(keyToBeWrapped); } } catch (IllegalBlockSizeException ex) { Library.logger().warning("IllegalBlockSizeException " + ex.getMessage() + " in wrap key -- unexpected, we should have compensated for this. Key to be wrapped algorithm? " + keyToBeWrapped.getAlgorithm() + ". Using nonce key? " + (null == nonceKey)); throw new InvalidKeyException("IllegalBlockSizeException " + ex.getMessage() + " in wrap key -- unexpected, we should have compensated for this. Key to be wrapped algorithm? " + keyToBeWrapped.getAlgorithm() + ". Using nonce key? " + (null == nonceKey)); } } // Default wrapping algorithm is being used, don't need to include it. return new WrappedKey(null, null, ((null == keyAlgorithm) ? keyToBeWrapped.getAlgorithm() : keyAlgorithm), keyLabel, wrappedNonceKey, wrappedKey); } /** * For now, we have a very loose definition of default -- the default wrap algorithm * depends on the type of key being used to wrap; similarly the default key algorithm * depends on the type of the key being wrapped. We assume that the wrapper and unwrapper * usually know the type of the wrapping key, and can derive the wrapAlgorithm. The * keyAlgorithm is more often necessary to determine how to decode the key once unwrapped * so it is more frequently present. Both are optional. * * If the caller specifies values they will be encoded on the wire and decoded on * the other end; defaults will not currently be enforced automatically. This means * equals behavior should be watched closely. * @param wrappingKeyIdentifier * @param wrapAlgorithm * @param keyAlgorithm * @param label * @param encryptedKey */ public WrappedKey(byte [] wrappingKeyIdentifier, String wrapAlgorithm, String keyAlgorithm, String label, byte [] encryptedKey) { this(wrappingKeyIdentifier, wrapAlgorithm, keyAlgorithm, label, null, encryptedKey); } public WrappedKey(byte [] wrappingKeyIdentifier, String wrapAlgorithm, String keyAlgorithm, String label, byte [] encryptedNonceKey, byte [] encryptedKey) { _wrappingKeyIdentifier = wrappingKeyIdentifier; _wrapAlgorithm = wrapAlgorithm; _keyAlgorithm = keyAlgorithm; _label = label; _encryptedNonceKey = encryptedNonceKey; _encryptedKey = encryptedKey; } public WrappedKey(byte [] wrappingKeyIdentifier, byte [] encryptedKey) { this(wrappingKeyIdentifier, null, null, null, null, encryptedKey); } public WrappedKey(byte [] wrappingKeyIdentifier, String label, byte [] encryptedKey) { this(wrappingKeyIdentifier, null, null, label, null, encryptedKey); } /** * Empty constructor for decoding. */ public WrappedKey() { } public Key unwrapKey(Key unwrapKey) throws InvalidKeyException, InvalidCipherTextException { if (null == keyAlgorithm()) { throw new InvalidCipherTextException("No algorithm specified for key to be unwrapped!"); } try { return unwrapKey(unwrapKey, keyAlgorithm()); } catch (NoSuchAlgorithmException e) { Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to unwrap key with specified algorithm : " + keyAlgorithm()); throw new InvalidCipherTextException("Unexpected NoSuchAlgorithmException attempting to unwrap key with specified algorithm : " + keyAlgorithm()); } } public Key unwrapKey(Key unwrapKey, String wrappedKeyAlgorithm) throws InvalidKeyException, NoSuchAlgorithmException, InvalidCipherTextException { Key unwrappedKey = null; Library.logger().info("wrap algorithm: " + wrapAlgorithm() + " wa for key " + wrapAlgorithmForKey(unwrapKey.getAlgorithm())); if (((null != wrapAlgorithm()) && (wrapAlgorithm().equalsIgnoreCase("AESWrapWithPad"))) || wrapAlgorithmForKey(unwrapKey.getAlgorithm()).equalsIgnoreCase("AESWrapWithPad")) { unwrappedKey = AESUnwrapWithPad(unwrapKey, wrappedKeyAlgorithm, encryptedKey(), 0, encryptedKey().length); } else { Cipher unwrapCipher = null; try { if (null != wrapAlgorithm()) { unwrapCipher = Cipher.getInstance(wrapAlgorithm()); } else { unwrapCipher = Cipher.getInstance(wrapAlgorithmForKey(unwrapKey.getAlgorithm())); } } catch (NoSuchAlgorithmException e) { Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm."); throw new InvalidKeyException("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm."); } catch (NoSuchPaddingException e) { Library.logger().warning("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm."); throw new InvalidKeyException("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm"); } unwrapCipher.init(Cipher.UNWRAP_MODE, unwrapKey); int keyType = getCipherType(wrappedKeyAlgorithm); if (null != encryptedNonceKey()) { try { Key nonceKey = unwrapCipher.unwrap(encryptedNonceKey(), NONCE_KEY_ALGORITHM, Cipher.SECRET_KEY); //Cipher nonceKeyCipher = Cipher.getInstance(wrapAlgorithmForKey(NONCE_KEY_ALGORITHM)); //nonceKeyCipher.init(Cipher.UNWRAP_MODE, nonceKey); //unwrappedKey = nonceKeyCipher.unwrap(encryptedKey(), wrappedKeyAlgorithm, keyType); unwrappedKey = AESUnwrapWithPad(nonceKey, wrappedKeyAlgorithm, encryptedKey(), 0, encryptedKey().length); } catch(NoSuchAlgorithmException nsex) { Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); Library.warningStackTrace(nsex); throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); } } else { unwrappedKey = unwrapCipher.unwrap(encryptedKey(), wrappedKeyAlgorithm, keyType); } } return unwrappedKey; } public byte [] wrappingKeyIdentifier() { return _wrappingKeyIdentifier; } public void setWrappingKeyIdentifier(byte [] wrappingKeyIdentifier) { _wrappingKeyIdentifier = wrappingKeyIdentifier; } public void setWrappingKeyIdentifier(PublicKey wrappingKey) { setWrappingKeyIdentifier(PublisherID.generatePublicKeyDigest(wrappingKey)); } public void setWrappingKeyIdentifier(SecretKeySpec wrappingKey) { setWrappingKeyIdentifier(CCNDigestHelper.digest(wrappingKey.getEncoded())); } public ContentName wrappingKeyName() { return _wrappingKeyName; } public void setWrappingKeyName(ContentName keyName) { _wrappingKeyName = new WrappingKeyName(keyName); } public String wrapAlgorithm() { return _wrapAlgorithm; } public String keyAlgorithm() { return _keyAlgorithm; } public String label() { return _label; } public byte [] encryptedNonceKey() { return _encryptedNonceKey; } public byte [] encryptedKey() { return _encryptedKey; } @Override public void decode(XMLDecoder decoder) throws XMLStreamException { decoder.readStartElement(WRAPPED_KEY_ELEMENT); if (decoder.peekStartElement(WRAPPING_KEY_IDENTIFIER_ELEMENT)) { _wrappingKeyIdentifier = decoder.readBinaryElement(WRAPPING_KEY_IDENTIFIER_ELEMENT); } if (decoder.peekStartElement(WRAPPING_KEY_NAME_ELEMENT)) { _wrappingKeyName = new WrappingKeyName(); _wrappingKeyName.decode(decoder); } if (decoder.peekStartElement(WRAP_ALGORITHM_ELEMENT)) { _wrapAlgorithm = decoder.readUTF8Element(WRAP_ALGORITHM_ELEMENT); } if (decoder.peekStartElement(KEY_ALGORITHM_ELEMENT)) { _keyAlgorithm = decoder.readUTF8Element(KEY_ALGORITHM_ELEMENT); } if (decoder.peekStartElement(LABEL_ELEMENT)) { _label = decoder.readUTF8Element(LABEL_ELEMENT); } if (decoder.peekStartElement(ENCRYPTED_NONCE_KEY_ELEMENT)) { _encryptedNonceKey = decoder.readBinaryElement(ENCRYPTED_NONCE_KEY_ELEMENT); } _encryptedKey = decoder.readBinaryElement(ENCRYPTED_KEY_ELEMENT); decoder.readEndElement(); } @Override public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(WRAPPED_KEY_ELEMENT); if (null != wrappingKeyIdentifier()) { // needs to handle null WKI encoder.writeElement(WRAPPING_KEY_IDENTIFIER_ELEMENT, wrappingKeyIdentifier()); } if (null != wrappingKeyName()) { wrappingKeyName().encode(encoder); } if (null != wrapAlgorithm()) { //String wrapOID = OIDLookup.getCipherOID(wrapAlgorithm()); encoder.writeElement(WRAP_ALGORITHM_ELEMENT, wrapAlgorithm()); } if (null != keyAlgorithm()) { //String keyOID = OIDLookup.getCipherOID(keyAlgorithm()); encoder.writeElement(KEY_ALGORITHM_ELEMENT, keyAlgorithm()); } if (null != label()) { encoder.writeElement(LABEL_ELEMENT, label()); } if (null != encryptedNonceKey()) { encoder.writeElement(ENCRYPTED_NONCE_KEY_ELEMENT, encryptedNonceKey()); } encoder.writeElement(ENCRYPTED_KEY_ELEMENT, encryptedKey()); encoder.writeEndElement(); } @Override public boolean validate() { // Only mandatory component is the encrypted key. return ((null != _encryptedKey) && (_encryptedKey.length > 0)); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(_encryptedKey); result = prime * result + Arrays.hashCode(_encryptedNonceKey); result = prime * result + ((_keyAlgorithm == null) ? 0 : _keyAlgorithm.hashCode()); result = prime * result + ((_label == null) ? 0 : _label.hashCode()); result = prime * result + ((_wrapAlgorithm == null) ? 0 : _wrapAlgorithm.hashCode()); result = prime * result + Arrays.hashCode(_wrappingKeyIdentifier); result = prime * result + ((_wrappingKeyName == null) ? 0 : _wrappingKeyName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WrappedKey other = (WrappedKey) obj; if (!Arrays.equals(_encryptedKey, other._encryptedKey)) return false; if (!Arrays.equals(_encryptedNonceKey, other._encryptedNonceKey)) return false; if (_keyAlgorithm == null) { if (other._keyAlgorithm != null) return false; } else if (!_keyAlgorithm.equals(other._keyAlgorithm)) return false; if (_label == null) { if (other._label != null) return false; } else if (!_label.equals(other._label)) return false; if (_wrapAlgorithm == null) { if (other._wrapAlgorithm != null) return false; } else if (!_wrapAlgorithm.equals(other._wrapAlgorithm)) return false; if (!Arrays .equals(_wrappingKeyIdentifier, other._wrappingKeyIdentifier)) return false; if (_wrappingKeyName == null) { if (other._wrappingKeyName != null) return false; } else if (!_wrappingKeyName.equals(other._wrappingKeyName)) return false; return true; } public static int getCipherType(String cipherAlgorithm) { if (cipherAlgorithm.equalsIgnoreCase("ECIES") || cipherAlgorithm.equalsIgnoreCase("RSA") || cipherAlgorithm.equalsIgnoreCase("ElGamal")) { return Cipher.PRIVATE_KEY; // right now assume we don't wrap public keys } return Cipher.SECRET_KEY; } /** * Convert a given wrapping key algorithm to the default wrap algorithm for * using that key. * @param keyAlgorithm * @return */ public static String wrapAlgorithmForKey(String keyAlgorithm) { String wrapAlgorithm = _WrapAlgorithmMap.get(keyAlgorithm); if (null == wrapAlgorithm) { // punt return keyAlgorithm; } return wrapAlgorithm; } public static Key generateNonceKey() { KeyGenerator kg; try { kg = KeyGenerator.getInstance(NONCE_KEY_ALGORITHM); kg.init(NONCE_KEY_LENGTH); Key nk = kg.generateKey(); return nk; } catch (NoSuchAlgorithmException e) { Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); Library.warningStackTrace(e); throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM); } } /** * Until we can sign a provider, we need to reach directly in to wrap public keys in AES keys. * @param input * @param offset * @param length * @return */ protected static byte [] AESWrapWithPad(Key wrappingKey, byte[] input, int offset, int length) { if (wrappingKey.getAlgorithm() != "AES") { throw new IllegalArgumentException("AES wrap must wrap with with an AES key."); } AESWrapWithPadEngine engine = new AESWrapWithPadEngine(); engine.init(true, new KeyParameter(wrappingKey.getEncoded())); return engine.wrap(input, offset, length); } protected static Key AESUnwrapWithPad(Key unwrappingKey, String wrappedKeyAlgorithm, byte [] input, int offset, int length) throws InvalidCipherTextException, InvalidKeyException { if (unwrappingKey.getAlgorithm() != "AES") { throw new IllegalArgumentException("AES wrap must unwrap with with an AES key."); } AESWrapWithPad engine = new AESWrapWithPad(); if ((offset != 0) || (length != input.length)) { byte [] tmpbuf = new byte[length]; System.arraycopy(input, offset, tmpbuf, 0, length); input = tmpbuf; } return engine.unwrap(unwrappingKey, input, wrappedKeyAlgorithm); } }
package com.intellij.openapi.actionSystem.impl; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.HelpTooltip; import com.intellij.internal.statistic.collectors.fus.ui.persistence.ToolbarClicksCollector; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionButtonLook; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.AccessibleContextUtil; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import static java.awt.event.KeyEvent.VK_SPACE; public class ActionButton extends JComponent implements ActionButtonComponent, AnActionHolder, Accessible { private JBDimension myMinimumButtonSize; private PropertyChangeListener myPresentationListener; private Icon myDisabledIcon; private Icon myIcon; protected final Presentation myPresentation; protected final AnAction myAction; protected final String myPlace; private ActionButtonLook myLook = ActionButtonLook.SYSTEM_LOOK; private boolean myMouseDown; private boolean myRollover; private static boolean ourGlobalMouseDown = false; private boolean myNoIconsInPopup = false; private Insets myInsets; public ActionButton(AnAction action, Presentation presentation, String place, @NotNull Dimension minimumSize) { setMinimumButtonSize(minimumSize); setIconInsets(null); myRollover = false; myMouseDown = false; myAction = action; myPresentation = presentation; myPlace = place; // Button should be focusable if screen reader is active setFocusable(ScreenReader.isActive()); enableEvents(AWTEvent.MOUSE_EVENT_MASK); // Pressing the SPACE key is the same as clicking the button addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getModifiers() == 0 && e.getKeyCode() == VK_SPACE) { click(); } } }); addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { repaint(); } @Override public void focusLost(FocusEvent e) { repaint(); } }); putClientProperty(UIUtil.CENTER_TOOLTIP_DEFAULT, Boolean.TRUE); } public void setNoIconsInPopup(boolean noIconsInPopup) { myNoIconsInPopup = noIconsInPopup; } public void setMinimumButtonSize(@NotNull Dimension size) { myMinimumButtonSize = JBDimension.create(size); } public void paintChildren(Graphics g) {} public int getPopState() { if (myAction instanceof Toggleable) { Boolean selected = (Boolean)myPresentation.getClientProperty(Toggleable.SELECTED_PROPERTY); boolean flag1 = selected != null && selected.booleanValue(); return getPopState(flag1); } else { return getPopState(false); } } @Override public boolean isEnabled() { return super.isEnabled() && myPresentation.isEnabled(); } protected boolean isButtonEnabled() { return isEnabled(); } private void onMousePresenceChanged(boolean setInfo) { ActionMenu.showDescriptionInStatusBar(setInfo, this, myPresentation.getDescription()); } public void click() { performAction(new MouseEvent(this, MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, 0, 0, 1, false)); } private void performAction(MouseEvent e) { AnActionEvent event = AnActionEvent.createFromInputEvent(e, myPlace, myPresentation, getDataContext(), false, true); if (!ActionUtil.lastUpdateAndCheckDumb(myAction, event, false)) { return; } if (isButtonEnabled()) { final ActionManagerEx manager = ActionManagerEx.getInstanceEx(); final DataContext dataContext = event.getDataContext(); manager.fireBeforeActionPerformed(myAction, dataContext, event); Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); if (component != null && !component.isShowing()) { return; } actionPerformed(event); manager.queueActionPerformedEvent(myAction, dataContext, event); if (event.getInputEvent() instanceof MouseEvent) { ToolbarClicksCollector.record(myAction, myPlace); } } } protected DataContext getDataContext() { ActionToolbar actionToolbar = UIUtil.getParentOfType(ActionToolbar.class, this); return actionToolbar != null ? actionToolbar.getToolbarDataContext() : DataManager.getInstance().getDataContext(); } private void actionPerformed(final AnActionEvent event) { HelpTooltip.hide(this); if (myAction instanceof ActionGroup && !(myAction instanceof CustomComponentAction) && ((ActionGroup)myAction).isPopup() && !((ActionGroup)myAction).canBePerformed(event.getDataContext())) { final ActionManagerImpl am = (ActionManagerImpl)ActionManager.getInstance(); ActionPopupMenuImpl popupMenu = (ActionPopupMenuImpl)am.createActionPopupMenu(event.getPlace(), (ActionGroup)myAction, new MenuItemPresentationFactory() { @Override protected void processPresentation(Presentation presentation) { if (myNoIconsInPopup) { presentation.setIcon(null); presentation.setHoveredIcon(null); } } }); popupMenu.setDataContextProvider(() -> this.getDataContext()); if (event.isFromActionToolbar()) { popupMenu.getComponent().show(this, 0, getHeight()); } else { popupMenu.getComponent().show(this, getWidth(), 0); } } else { ActionUtil.performActionDumbAware(myAction, event); } } public void removeNotify() { if (myRollover) { onMousePresenceChanged(false); } if (myPresentationListener != null) { myPresentation.removePropertyChangeListener(myPresentationListener); myPresentationListener = null; } super.removeNotify(); } public void addNotify() { super.addNotify(); if (myPresentationListener == null) { myPresentation.addPropertyChangeListener(myPresentationListener = this::presentationPropertyChanded); } AnActionEvent e = AnActionEvent.createFromInputEvent(null, myPlace, myPresentation, getDataContext(), false, true); ActionUtil.performDumbAwareUpdate(LaterInvocator.isInModalContext(), myAction, e, false); updateToolTipText(); updateIcon(); } public void setToolTipText(String s) { if (!Registry.is("ide.helptooltip.enabled")) { String tooltipText = KeymapUtil.createTooltipText(s, myAction); super.setToolTipText(tooltipText.length() > 0 ? tooltipText : null); } } @Override public Insets getInsets() { ActionToolbarImpl owner = UIUtil.getParentOfType(ActionToolbarImpl.class, this); return owner != null && owner.getOrientation() == SwingConstants.VERTICAL ? JBUI.insets(2, 1) : JBUI.insets(1, 2); } @Override public void updateUI() { if (myLook != null) { myLook.updateUI(); } updateToolTipText(); } @Override public Dimension getPreferredSize() { if (myMinimumButtonSize != null) myMinimumButtonSize.update(); Icon icon = getIcon(); if (icon.getIconWidth() < myMinimumButtonSize.width && icon.getIconHeight() < myMinimumButtonSize.height) { Dimension size = new Dimension(myMinimumButtonSize); JBInsets.addTo(size, getInsets()); return size; } else { Dimension size = new Dimension( Math.max(myMinimumButtonSize.width, icon.getIconWidth() + myInsets.left + myInsets.right), Math.max(myMinimumButtonSize.height, icon.getIconHeight() + myInsets.top + myInsets.bottom)); JBInsets.addTo(size, getInsets()); return size; } } public void setIconInsets(@Nullable Insets insets) { myInsets = insets != null ? JBUI.insets(insets) : JBUI.emptyInsets(); } public Dimension getMinimumSize() { return getPreferredSize(); } /** * @return button's icon. Icon depends on action's state. It means that the method returns * disabled icon if action is disabled. If the action's icon is {@code null} then it returns * an empty icon. */ public Icon getIcon() { Icon icon = isButtonEnabled() ? myIcon : myDisabledIcon; return icon == null ? EmptyIcon.ICON_18 : icon; } public void updateIcon() { myIcon = myPresentation.getIcon(); if (myPresentation.getDisabledIcon() != null) { // set disabled icon if it is specified myDisabledIcon = myPresentation.getDisabledIcon(); } else if (myIcon == null || IconLoader.isGoodSize(myIcon)) { myDisabledIcon = IconLoader.getDisabledIcon(myIcon); } else { myDisabledIcon = null; Logger.getInstance(ActionButton.class).error("invalid icon for action " + myAction); } } void updateToolTipText() { String text = myPresentation.getText(); String description = myPresentation.getDescription(); if (Registry.is("ide.helptooltip.enabled")) { HelpTooltip.dispose(this); String shortcut = KeymapUtil.getFirstKeyboardShortcutText(myAction); if (StringUtil.isNotEmpty(text) || StringUtil.isNotEmpty(description)) { HelpTooltip ht = new HelpTooltip().setTitle(text).setShortcut(shortcut).setLocation(getTooltipLocation()); if (!StringUtil.equals(text, description)) { ht.setDescription(description); } ht.installOn(this); } } else { setToolTipText(text == null ? description : text); } } protected HelpTooltip.Alignment getTooltipLocation() { return HelpTooltip.Alignment.BOTTOM; } public void paintComponent(Graphics g) { super.paintComponent(g); paintButtonLook(g); if (myAction instanceof ActionGroup && ((ActionGroup)myAction).isPopup()) { AllIcons.General.Dropdown.paintIcon(this, g, JBUI.scale(5), JBUI.scale(4)); } } protected void paintButtonLook(Graphics g) { ActionButtonLook look = getButtonLook(); if (isEnabled() || !UIUtil.isUnderDarcula()) { look.paintBackground(g, this); } look.paintIcon(g, this, getIcon()); look.paintBorder(g, this); } protected ActionButtonLook getButtonLook() { return myLook; } public void setLook(ActionButtonLook look) { if (look != null) { myLook = look; } else { myLook = ActionButtonLook.SYSTEM_LOOK; } repaint(); } protected void processMouseEvent(MouseEvent e) { super.processMouseEvent(e); if (e.isConsumed()) return; boolean skipPress = checkSkipPressForEvent(e); switch (e.getID()) { case MouseEvent.MOUSE_PRESSED: if (skipPress || !isButtonEnabled()) return; myMouseDown = true; ourGlobalMouseDown = true; repaint(); break; case MouseEvent.MOUSE_RELEASED: if (skipPress || !isButtonEnabled()) return; myMouseDown = false; ourGlobalMouseDown = false; if (myRollover) { performAction(e); } repaint(); break; case MouseEvent.MOUSE_ENTERED: if (!myMouseDown && ourGlobalMouseDown) break; myRollover = true; repaint(); onMousePresenceChanged(true); break; case MouseEvent.MOUSE_EXITED: myRollover = false; if (!myMouseDown && ourGlobalMouseDown) break; repaint(); onMousePresenceChanged(false); break; } } protected boolean checkSkipPressForEvent(@NotNull MouseEvent e) { return e.isMetaDown() || e.getButton() != MouseEvent.BUTTON1; } private int getPopState(boolean isPushed) { if (isPushed || myRollover && myMouseDown && isButtonEnabled()) { return PUSHED; } else if (myRollover && isButtonEnabled()) { return POPPED; } else if (isFocusOwner()) { return SELECTED; } else { return NORMAL; } } public AnAction getAction() { return myAction; } protected void presentationPropertyChanded(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (Presentation.PROP_TEXT.equals(propertyName)) { updateToolTipText(); } else if (Presentation.PROP_ENABLED.equals(propertyName) || Presentation.PROP_ICON.equals(propertyName)) { updateIcon(); repaint(); } else if (Presentation.PROP_DISABLED_ICON.equals(propertyName)) { myDisabledIcon = myPresentation.getDisabledIcon(); repaint(); } else if ("selected".equals(propertyName)) { repaint(); } } // Accessibility @Override public AccessibleContext getAccessibleContext() { if(this.accessibleContext == null) { this.accessibleContext = new AccessibleActionButton(); } return this.accessibleContext; } protected class AccessibleActionButton extends JComponent.AccessibleJComponent implements AccessibleAction { public AccessibleActionButton() { } @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.PUSH_BUTTON; } @Override public String getAccessibleName() { String name = accessibleName; if (name == null) { name = (String)ActionButton.this.getClientProperty(ACCESSIBLE_NAME_PROPERTY); if (name == null) { name = ActionButton.this.getToolTipText(); if (name == null) { name = ActionButton.this.myPresentation.getText(); if (name == null) { name = super.getAccessibleName(); } } } } return name; } @Override public String getAccessibleDescription() { return AccessibleContextUtil.getUniqueDescription(this, super.getAccessibleDescription()); } @Override public AccessibleIcon[] getAccessibleIcon() { Icon icon = ActionButton.this.getIcon(); if (icon instanceof Accessible) { AccessibleContext context = ((Accessible)icon).getAccessibleContext(); if (context instanceof AccessibleIcon) { return new AccessibleIcon[]{(AccessibleIcon)context}; } } return null; } @Override public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet var1 = super.getAccessibleStateSet(); int state = ActionButton.this.getPopState(); // TODO: Not sure what the "POPPED" state represents //if (state == POPPED) { // var1.add(AccessibleState.?); if (state == ActionButtonComponent.PUSHED) { var1.add(AccessibleState.PRESSED); } if (state == ActionButtonComponent.SELECTED) { var1.add(AccessibleState.CHECKED); } if (ActionButton.this.isFocusOwner()) { var1.add(AccessibleState.FOCUSED); } return var1; } @Override public AccessibleAction getAccessibleAction() { return this; } // Implements AccessibleAction @Override public int getAccessibleActionCount() { return 1; } @Override public String getAccessibleActionDescription(int index) { return index == 0 ? UIManager.getString("AbstractButton.clickText") : null; } @Override public boolean doAccessibleAction(int index) { if (index == 0) { ActionButton.this.click(); return true; } else { return false; } } } }
package com.intellij.openapi.application; import com.intellij.diagnostic.VMOptions; import com.intellij.ide.actions.ImportSettingsFilenameFilter; import com.intellij.ide.cloudConfig.CloudConfigProvider; import com.intellij.ide.highlighter.ArchiveFileType; import com.intellij.ide.startup.StartupActionScriptManager; import com.intellij.idea.Main; import com.intellij.idea.SplashManager; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.AppUIUtil; import com.intellij.util.PlatformUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.Restarter; import com.intellij.util.SystemProperties; import com.intellij.util.io.Decompressor; import com.intellij.util.text.VersionComparatorUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.DosFileAttributes; import java.nio.file.attribute.FileTime; import java.util.List; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipFile; import static com.intellij.ide.GeneralSettings.IDE_GENERAL_XML; import static com.intellij.openapi.application.PathManager.OPTIONS_DIRECTORY; import static com.intellij.openapi.util.Pair.pair; public final class ConfigImportHelper { private static final String FIRST_SESSION_KEY = "intellij.first.ide.session"; private static final String CONFIG_IMPORTED_IN_CURRENT_SESSION_KEY = "intellij.config.imported.in.current.session"; private static final String CONFIG = "config"; private static final String[] OPTIONS = { OPTIONS_DIRECTORY + '/' + StoragePathMacros.NON_ROAMABLE_FILE, OPTIONS_DIRECTORY + '/' + IDE_GENERAL_XML, OPTIONS_DIRECTORY + "/options.xml"}; private static final String BIN = "bin"; private static final String CONTENTS = "Contents"; private static final String PLIST = "Info.plist"; private static final String PLUGINS = "plugins"; private static final String SYSTEM = "system"; private static final Pattern SELECTOR_PATTERN = Pattern.compile("\\.?([^\\d]+)(\\d+(?:\\.\\d+)?)"); private static final String SHOW_IMPORT_CONFIG_DIALOG_PROPERTY = "idea.initially.ask.config"; private ConfigImportHelper() { } public static void importConfigsTo(boolean veryFirstStartOnThisComputer, @NotNull Path newConfigDir, @NotNull Logger log) { System.setProperty(FIRST_SESSION_KEY, Boolean.TRUE.toString()); ConfigImportSettings settings = null; try { String customProviderName = "com.intellij.openapi.application." + PlatformUtils.getPlatformPrefix() + "ConfigImportSettings"; @SuppressWarnings("unchecked") Class<ConfigImportSettings> customProviderClass = (Class<ConfigImportSettings>)Class.forName(customProviderName); if (ConfigImportSettings.class.isAssignableFrom(customProviderClass)) { settings = ReflectionUtil.newInstance(customProviderClass); } } catch (Exception ignored) { } List<Path> guessedOldConfigDirs = findConfigDirectories(newConfigDir); Pair<Path, Path> oldConfigDirAndOldIdePath = null; if (shouldAskForConfig(log)) { oldConfigDirAndOldIdePath = showDialogAndGetOldConfigPath(guessedOldConfigDirs); } else if (guessedOldConfigDirs.isEmpty()) { boolean importedFromCloud = false; CloudConfigProvider configProvider = CloudConfigProvider.getProvider(); if (configProvider != null) { importedFromCloud = configProvider.importSettingsSilently(newConfigDir); } if (!importedFromCloud && !veryFirstStartOnThisComputer) { oldConfigDirAndOldIdePath = showDialogAndGetOldConfigPath(guessedOldConfigDirs); } } else { Path bestConfigGuess = guessedOldConfigDirs.get(0); oldConfigDirAndOldIdePath = pair(bestConfigGuess, null); } if (oldConfigDirAndOldIdePath != null) { doImport(oldConfigDirAndOldIdePath.first, newConfigDir, oldConfigDirAndOldIdePath.second, log); if (settings != null) { settings.importFinished(newConfigDir); } if (Files.isRegularFile(newConfigDir.resolve(VMOptions.getCustomVMOptionsFileName()))) { if (Restarter.isSupported()) { try { Restarter.scheduleRestart(false); } catch (IOException e) { Main.showMessage("Restart failed", e); } System.exit(0); } else { String title = ApplicationBundle.message("title.import.settings", ApplicationNamesInfo.getInstance().getFullProductName()); String message = ApplicationBundle.message("restart.import.settings"); String yes = ApplicationBundle.message("restart.import.now"), no = ApplicationBundle.message("restart.import.later"); if (Messages.showYesNoDialog(message, title, yes, no, Messages.getQuestionIcon()) == Messages.YES) { System.exit(0); } } } System.setProperty(CONFIG_IMPORTED_IN_CURRENT_SESSION_KEY, Boolean.TRUE.toString()); } } private static boolean shouldAskForConfig(@NotNull Logger log) { try { String val = System.getProperty(SHOW_IMPORT_CONFIG_DIALOG_PROPERTY); if (val != null) { return Boolean.parseBoolean(val); } } catch (Throwable t) { log.error(t); } return false; } @Nullable private static Pair<Path, Path> showDialogAndGetOldConfigPath(@NotNull List<Path> guessedOldConfigDirs) { ImportOldConfigsPanel dialog = new ImportOldConfigsPanel(guessedOldConfigDirs, f -> findConfigDirectoryByPath(f)); dialog.setModalityType(Dialog.ModalityType.TOOLKIT_MODAL); AppUIUtil.updateWindowIcon(dialog); Ref<Pair<Path, Path>> result = new Ref<>(); SplashManager.executeWithHiddenSplash(dialog, () -> { dialog.setVisible(true); result.set(dialog.getSelectedFile()); dialog.dispose(); }); return result.get(); } /** Returns {@code true} when the IDE is launched for the first time (i.e. there was no config directory). */ public static boolean isFirstSession() { return Boolean.getBoolean(FIRST_SESSION_KEY); } /** Simple check by file type, content is not checked. */ public static boolean isSettingsFile(@NotNull VirtualFile file) { return FileTypeRegistry.getInstance().isFileOfType(file, ArchiveFileType.INSTANCE); } /** Returns {@code true} when the IDE is launched for the first time, and configs were imported from another installation. */ public static boolean isConfigImported() { return Boolean.getBoolean(CONFIG_IMPORTED_IN_CURRENT_SESSION_KEY); } static boolean isValidSettingsFile(@NotNull File file) { try (ZipFile zip = new ZipFile(file)) { return zip.getEntry(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER) != null; } catch (IOException ignored) { return false; } } static boolean isConfigDirectory(@NotNull Path candidate) { return Arrays.stream(OPTIONS).anyMatch(name -> Files.exists(candidate.resolve(name))); } static @NotNull List<Path> findConfigDirectories(@NotNull Path newConfigDir) { // looking for existing config directories ... Set<Path> homes = new HashSet<>(); homes.add(newConfigDir.getParent()); // ... in the vicinity of the new config directory homes.add(newConfigDir.getFileSystem().getPath(PathManager.getDefaultConfigPathFor("X")).getParent()); // ... in the default location Path historic = newConfigDir.getFileSystem().getPath(defaultConfigPath("X2019.3")); homes.add(SystemInfo.isMac ? historic.getParent() : historic.getParent().getParent()); // ... in the historic location String prefix = getPrefixFromSelector(PathManager.getPathsSelector()); if (prefix == null) prefix = getPrefixFromSelector(getNameWithVersion(newConfigDir)); if (prefix == null) { String productName = ApplicationNamesInfo.getInstance().getFullProductName(); if (productName != null) prefix = productName.replace(" ", ""); } if (prefix == null) prefix = PlatformUtils.getPlatformPrefix(); List<Path> candidates = new ArrayList<>(); for (Path home : homes) { if (home == null || !Files.isDirectory(home)) continue; try (DirectoryStream<Path> stream = Files.newDirectoryStream(home)) { for (Path path : stream) { if (!path.equals(newConfigDir)) { if (Files.isDirectory(path) && isConfigDirectory(path)) { candidates.add(path); } } } } catch (IOException ignore) { } } if (candidates.isEmpty()) { return Collections.emptyList(); } Map<Path, FileTime> lastModified = new THashMap<>(); for (Path child : candidates) { Path candidate = child, config = child.resolve(CONFIG); if (Files.isDirectory(config)) candidate = config; FileTime max = null; for (String name : OPTIONS) { try { FileTime cur = Files.getLastModifiedTime(candidate.resolve(name)); if (max == null || cur.compareTo(max) > 0) { max = cur; } } catch (IOException ignore) { } } lastModified.put(candidate, max != null ? max : FileTime.fromMillis(0)); } List<Path> result = new ArrayList<>(lastModified.keySet()); String productPrefix = prefix; result.sort((o1, o2) -> { String name1 = o1.getFileName().toString(); String name2 = o2.getFileName().toString(); if (isThisProduct(name1, productPrefix) && !isThisProduct(name2, productPrefix)){ return -1; } if (!isThisProduct(name1, productPrefix) && isThisProduct(name2, productPrefix)){ return 1; } int diff = lastModified.get(o2).compareTo(lastModified.get(o1)); if (diff == 0) { diff = StringUtil.naturalCompare(o2.toString(), o1.toString()); } return diff; }); return result; } private static boolean isThisProduct(@NotNull String configDirName, @NotNull String productPrefix) { String dotPrefix = '.' + productPrefix; return StringUtil.startsWithIgnoreCase(configDirName, productPrefix) || StringUtil.startsWithIgnoreCase(configDirName, dotPrefix); } private static String getNameWithVersion(Path configDir) { String name = configDir.getFileName().toString(); if (CONFIG.equals(name)) name = StringUtil.trimStart(configDir.getParent().getFileName().toString(), "."); return name; } private static @Nullable String getPrefixFromSelector(@Nullable String nameWithSelector) { if (nameWithSelector != null) { Matcher m = SELECTOR_PATTERN.matcher(nameWithSelector); if (m.matches()) { return m.group(1); } } return null; } private static @Nullable Pair<Path, Path> findConfigDirectoryByPath(Path selectedDir) { // tries to map a user selection into a valid config directory // returns a pair of a config directory and an IDE home (when a user pointed to it; null otherwise) if (isConfigDirectory(selectedDir)) { return pair(selectedDir, null); } Path config = selectedDir.resolve(CONFIG); if (isConfigDirectory(config)) { return pair(config, null); } if (Files.isDirectory(selectedDir.resolve(SystemInfo.isMac ? CONTENTS : BIN))) { Path configDir = getSettingsPath(selectedDir, PathManager.PROPERTY_CONFIG_PATH, ConfigImportHelper::defaultConfigPath); if (configDir != null && isConfigDirectory(configDir)) { return pair(configDir, selectedDir); } } return null; } private static @Nullable Path getSettingsPath(Path ideHome, String propertyName, Function<String, String> pathBySelector) { List<Path> files = new ArrayList<>(); if (SystemInfo.isMac) { files.add(ideHome.resolve(CONTENTS + '/' + BIN + '/' + PathManager.PROPERTIES_FILE_NAME)); files.add(ideHome.resolve(CONTENTS + '/' + PLIST)); } else { files.add(ideHome.resolve(BIN + '/' + PathManager.PROPERTIES_FILE_NAME)); String scriptName = ApplicationNamesInfo.getInstance().getScriptName(); files.add(ideHome.resolve(BIN + '/' + scriptName + ".bat")); files.add(ideHome.resolve(BIN + '/' + scriptName + ".sh")); } // explicitly specified directory for (Path file : files) { if (Files.isRegularFile(file)) { String candidatePath = PathManager.substituteVars(getPropertyFromFile(file, propertyName), ideHome.toString()); if (candidatePath != null) { Path candidate = ideHome.getFileSystem().getPath(candidatePath); if (Files.isDirectory(candidate)) { return candidate.toAbsolutePath(); } } } } // default directory for (Path file : files) { if (Files.isRegularFile(file)) { String selector = getPropertyFromFile(file, PathManager.PROPERTY_PATHS_SELECTOR); if (selector != null) { Path candidate = ideHome.getFileSystem().getPath(pathBySelector.apply(selector)); if (Files.isDirectory(candidate)) { return candidate; } } } } return null; } private static @Nullable String getPropertyFromFile(Path file, String propertyName) { try { String fileContent = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); final String fileName = file.getFileName().toString(); if (fileName.endsWith(".properties")) { PropertyResourceBundle bundle = new PropertyResourceBundle(new StringReader(fileContent)); return bundle.containsKey(propertyName) ? bundle.getString(propertyName) : null; } if (fileName.endsWith(".plist")) { String propertyValue = findPListKey(propertyName, fileContent); if (!StringUtil.isEmpty(propertyValue)) { return propertyValue; } } String propertyValue = findProperty(propertyName, fileContent); if (!StringUtil.isEmpty(propertyValue)) { return propertyValue; } } catch (IOException ignored) { } return null; } private static @Nullable String findPListKey(String propertyName, String fileContent) { String key = "<key>" + propertyName + "</key>"; int idx = fileContent.indexOf(key); if (idx > 0) { idx = fileContent.indexOf("<string>", idx + key.length()); if (idx != -1) { idx += "<string>".length(); return fixDirName(fileContent.substring(idx, fileContent.indexOf("</string>", idx))); } } return null; } private static @Nullable String findProperty(String propertyName, String fileContent) { String prefix = propertyName + "="; int idx = fileContent.indexOf(prefix); if (idx >= 0) { StringBuilder configDir = new StringBuilder(); idx += prefix.length(); if (fileContent.length() > idx) { boolean quoted = fileContent.charAt(idx) == '"'; if (quoted) idx++; while (fileContent.length() > idx && (quoted ? fileContent.charAt(idx) != '"' : fileContent.charAt(idx) != ' ' && fileContent.charAt(idx) != '\t') && fileContent.charAt(idx) != '\n' && fileContent.charAt(idx) != '\r') { configDir.append(fileContent.charAt(idx)); idx++; } } if (configDir.length() > 0) { return Paths.get(fixDirName(configDir.toString())).toString(); } } return null; } private static String fixDirName(String dir) { return FileUtil.expandUserHome(StringUtil.unquoteString(dir, '"')); } private static void doImport(@NotNull Path oldConfigDir, @NotNull Path newConfigDir, @Nullable Path oldIdeHome, @NotNull Logger log) { if (oldConfigDir.equals(newConfigDir)) { return; } Path oldPluginsDir = oldConfigDir.resolve(PLUGINS); if (!Files.isDirectory(oldPluginsDir)) { oldPluginsDir = null; if (oldIdeHome != null) { oldPluginsDir = getSettingsPath(oldIdeHome, PathManager.PROPERTY_PLUGINS_PATH, ConfigImportHelper::defaultPluginsPath); } if (oldPluginsDir == null) { oldPluginsDir = oldConfigDir.getFileSystem().getPath(defaultPluginsPath(getNameWithVersion(oldConfigDir))); // temporary code; safe to remove after 2020.1 branch is created if (!Files.isDirectory(oldPluginsDir) && oldPluginsDir.toString().contains("2020.1")) { oldPluginsDir = oldConfigDir.getFileSystem().getPath( defaultPluginsPath(getNameWithVersion(oldConfigDir).replace("2020.1", "2019.3")).replace("2019.3", "2020.1")); } } } Path newPluginsDir = newConfigDir.getFileSystem().getPath(PathManager.getPluginsPath()); try { doImport(oldConfigDir, newConfigDir, oldIdeHome, oldPluginsDir, newPluginsDir, log); } catch (Exception e) { log.warn(e); String message = ApplicationBundle.message("error.unable.to.import.settings", e.getMessage()); Main.showMessage(ApplicationBundle.message("title.settings.import.failed"), message, false); } } static void doImport(@NotNull Path oldConfigDir, @NotNull Path newConfigDir, @Nullable Path oldIdeHome, @NotNull Path oldPluginsDir, @NotNull Path newPluginsDir, @NotNull Logger log) throws IOException { if (Files.isRegularFile(oldConfigDir)) { new Decompressor.Zip(oldConfigDir.toFile()).extract(newConfigDir.toFile()); return; } // copy everything except plugins FileUtil.copyDir(oldConfigDir.toFile(), newConfigDir.toFile(), file -> !blockImport(file.toPath(), oldConfigDir, newConfigDir, oldPluginsDir)); // copy plugins, unless new plugin directory is not empty (the plugin manager will sort out incompatible ones) if (!Files.isDirectory(oldPluginsDir)) { log.info("non-existing plugins directory: " + oldPluginsDir); } else if (!isEmptyDirectory(newPluginsDir)) { log.info("non-empty plugins directory: " + newPluginsDir); } else { FileUtil.copyDir(oldPluginsDir.toFile(), newPluginsDir.toFile()); } if (SystemInfo.isMac && (PlatformUtils.isIntelliJ() || "AndroidStudio".equals(PlatformUtils.getPlatformPrefix()))) { setKeymapIfNeeded(oldConfigDir, newConfigDir, log); } // apply stale plugin updates if (Files.isDirectory(oldPluginsDir)) { Path oldSystemDir = oldConfigDir.getParent().resolve(SYSTEM); if (!Files.isDirectory(oldSystemDir)) { oldSystemDir = null; if (oldIdeHome != null) { oldSystemDir = getSettingsPath(oldIdeHome, PathManager.PROPERTY_SYSTEM_PATH, ConfigImportHelper::defaultSystemPath); } if (oldSystemDir == null) { oldSystemDir = oldConfigDir.getFileSystem().getPath(defaultSystemPath(getNameWithVersion(oldConfigDir))); } } Path script = oldSystemDir.resolve(PLUGINS + '/' + StartupActionScriptManager.ACTION_SCRIPT_FILE); // PathManager#getPluginTempPath if (Files.isRegularFile(script)) { StartupActionScriptManager.executeActionScript(script.toFile(), oldPluginsDir.toFile(), new File(PathManager.getPluginsPath())); } } updateVMOptions(newConfigDir, log); } private static boolean isEmptyDirectory(Path newPluginsDir) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(newPluginsDir)) { for (Path path : stream) { boolean hidden = SystemInfo.isWindows ? Files.readAttributes(path, DosFileAttributes.class).isHidden() : path.getFileName().startsWith("."); if (!hidden) { return false; } } } catch (IOException ignored) { } return true; } static void setKeymapIfNeeded(@NotNull Path oldConfigDir, @NotNull Path newConfigDir, @NotNull Logger log) { String nameWithVersion = getNameWithVersion(oldConfigDir); Matcher m = Pattern.compile("\\.?[^\\d]+(\\d+\\.\\d+)?").matcher(nameWithVersion); if (!m.matches() || VersionComparatorUtil.compare("2019.1", m.group(1)) < 0) { return; } Path keymapOptionFile = newConfigDir.resolve("options/keymap.xml"); if (Files.exists(keymapOptionFile)) { return; } try { Files.createDirectories(keymapOptionFile.getParent()); Files.write(keymapOptionFile, ("<application>\n" + " <component name=\"KeymapManager\">\n" + " <active_keymap name=\"Mac OS X\" />\n" + " </component>\n" + "</application>").getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { log.error("Cannot set keymap", e); } } /* Fix VM options in the custom *.vmoptions file that won't work with the current IDE version. */ private static void updateVMOptions(Path newConfigDir, Logger log) { Path vmOptionsFile = newConfigDir.resolve(VMOptions.getCustomVMOptionsFileName()); if (Files.exists(vmOptionsFile)) { try { List<String> lines = Files.readAllLines(vmOptionsFile); boolean updated = false; for (ListIterator<String> i = lines.listIterator(); i.hasNext(); ) { String line = i.next().trim(); if (line.equals("-XX:MaxJavaStackTraceDepth=-1")) { i.set("-XX:MaxJavaStackTraceDepth=10000"); updated = true; } else if (line.startsWith("-agentlib:yjpagent")) { i.remove(); updated = true; } } if (updated) { Files.write(vmOptionsFile, lines); } } catch (IOException e) { log.warn("Failed to update custom VM options file " + vmOptionsFile, e); } } } private static boolean blockImport(Path path, Path oldConfig, Path newConfig, Path oldPluginsDir) { if (oldConfig.equals(path.getParent())) { String name = path.getFileName().toString(); return "user.web.token".equals(name) || name.startsWith("chrome-user-data") || Files.exists(newConfig.resolve(path.getFileName())) || path.startsWith(oldPluginsDir); } return false; } private static String defaultConfigPath(String selector) { return newOrUnknown(selector) ? PathManager.getDefaultConfigPathFor(selector) : SystemInfo.isMac ? SystemProperties.getUserHome() + "/Library/Preferences/" + selector : SystemProperties.getUserHome() + "/." + selector + '/' + CONFIG; } private static String defaultPluginsPath(String selector) { return newOrUnknown(selector) ? PathManager.getDefaultPluginPathFor(selector) : SystemInfo.isMac ? SystemProperties.getUserHome() + "/Library/Application Support/" + selector : SystemProperties.getUserHome() + "/." + selector + '/' + CONFIG + '/' + PLUGINS; } private static String defaultSystemPath(String selector) { return newOrUnknown(selector) ? PathManager.getDefaultSystemPathFor(selector) : SystemInfo.isMac ? SystemProperties.getUserHome() + "/Library/Caches/" + selector : SystemProperties.getUserHome() + "/." + selector + '/' + SYSTEM; } private static boolean newOrUnknown(String selector) { Matcher m = SELECTOR_PATTERN.matcher(selector); return !m.matches() || "2020.1".compareTo(m.group(2)) <= 0; } }
package com.intellij.openapi.fileChooser.tree; import com.intellij.execution.wsl.WSLDistribution; import com.intellij.execution.wsl.WSLUtil; import com.intellij.execution.wsl.WslDistributionManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Experiments; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileElement; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.*; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.ui.tree.MapBasedTree; import com.intellij.ui.tree.MapBasedTree.Entry; import com.intellij.ui.tree.MapBasedTree.UpdateResult; import com.intellij.util.ReflectionUtil; import com.intellij.util.concurrency.Invoker; import com.intellij.util.concurrency.InvokerSupplier; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.tree.AbstractTreeModel; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.TreePath; import java.lang.reflect.Method; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; public final class FileTreeModel extends AbstractTreeModel implements InvokerSupplier { private static final Logger LOG = Logger.getInstance(FileTreeModel.class); private final Invoker invoker = Invoker.forBackgroundThreadWithReadAction(this); private final State state; private volatile List<Root> roots; public FileTreeModel(@NotNull FileChooserDescriptor descriptor, FileRefresher refresher) { this(descriptor, refresher, true, false); } public FileTreeModel(@NotNull FileChooserDescriptor descriptor, FileRefresher refresher, boolean sortDirectories, boolean sortArchives) { if (refresher != null) Disposer.register(this, refresher); state = new State(descriptor, refresher, sortDirectories, sortArchives, this); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends VFileEvent> events) { invoker.invoke(() -> process(events)); } }); } public void invalidate() { invoker.invoke(() -> { if (roots != null) { for (Root root : roots) { root.tree.invalidate(); } } treeStructureChanged(state.path, null, null); }); } @NotNull @Override public Invoker getInvoker() { return invoker; } @Override public final Object getRoot() { if (state.path != null) return state; if (roots == null) roots = state.getRoots(); return 1 == roots.size() ? roots.get(0) : null; } @Override public final Object getChild(Object object, int index) { if (object == state) { if (roots == null) roots = state.getRoots(); if (0 <= index && index < roots.size()) return roots.get(index); } else if (object instanceof Node) { Entry<Node> entry = getEntry((Node)object, true); if (entry != null) return entry.getChild(index); } return null; } @Override public final int getChildCount(Object object) { if (object == state) { if (roots == null) roots = state.getRoots(); return roots.size(); } else if (object instanceof Node) { Entry<Node> entry = getEntry((Node)object, true); if (entry != null) return entry.getChildCount(); } return 0; } @Override public final boolean isLeaf(Object object) { if (object instanceof Node) { Entry<Node> entry = getEntry((Node)object, false); if (entry != null) return entry.isLeaf(); } return false; } @Override public final int getIndexOfChild(Object object, Object child) { if (object == state) { if (roots == null) roots = state.getRoots(); for (int i = 0; i < roots.size(); i++) { if (child == roots.get(i)) return i; } } else if (object instanceof Node && child instanceof Node) { Entry<Node> entry = getEntry((Node)object, true); if (entry != null) return entry.getIndexOf((Node)child); } return -1; } private boolean hasEntry(VirtualFile file) { if (file == null) return false; if (roots != null) { for (Root root : roots) { Entry<Node> entry = root.tree.findEntry(file); if (entry != null) return true; } } return false; } private Entry<Node> getEntry(Node node, boolean loadChildren) { if (roots != null) { for (Root root : roots) { Entry<Node> entry = root.tree.getEntry(node); if (entry != null) { if (loadChildren && entry.isLoadingRequired()) { root.updateChildren(state, entry); //TODO: update updated } return entry; } } } return null; } private void process(List<? extends VFileEvent> events) { if (roots == null) return; HashSet<VirtualFile> files = new HashSet<>(); HashSet<VirtualFile> parents = new HashSet<>(); for (VFileEvent event : events) { if (event instanceof VFilePropertyChangeEvent) { if (hasEntry(event.getFile())) files.add(event.getFile()); } else if (event instanceof VFileCreateEvent) { VFileCreateEvent create = (VFileCreateEvent)event; if (hasEntry(create.getParent())) parents.add(create.getParent()); } else if (event instanceof VFileCopyEvent) { VFileCopyEvent copy = (VFileCopyEvent)event; if (hasEntry(copy.getNewParent())) parents.add(copy.getNewParent()); } else if (event instanceof VFileMoveEvent) { VFileMoveEvent move = (VFileMoveEvent)event; if (hasEntry(move.getNewParent())) parents.add(move.getNewParent()); if (hasEntry(move.getOldParent())) parents.add(move.getOldParent()); } else if (event instanceof VFileDeleteEvent) { VirtualFile file = event.getFile(); if (hasEntry(file)) { files.add(file); //TODO:for all roots file = file.getParent(); parents.add(hasEntry(file) ? file : null); } } } for (VirtualFile parent : parents) { for (Root root : roots) { Entry<Node> entry = root.tree.findEntry(parent); if (entry != null) { UpdateResult<Node> update = root.updateChildren(state, entry); //TODO:listeners.isEmpty boolean removed = !update.getRemoved().isEmpty(); boolean inserted = !update.getInserted().isEmpty(); boolean contained = !update.getContained().isEmpty(); if (!removed && !inserted && !contained) continue; if (!removed && inserted) { if (listeners.isEmpty()) continue; listeners.treeNodesInserted(update.getEvent(this, entry, update.getInserted())); continue; } if (!inserted && removed) { if (listeners.isEmpty()) continue; listeners.treeNodesRemoved(update.getEvent(this, entry, update.getRemoved())); continue; } treeStructureChanged(entry, null, null); } } } for (VirtualFile file : files) { //TODO:update } //TODO:on valid thread / entry - mark as valid } private static VirtualFile findFile(String path) { return LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(path)); } private static final class State { private final TreePath path; private final FileChooserDescriptor descriptor; private final FileRefresher refresher; private final boolean sortDirectories; private final boolean sortArchives; private final List<VirtualFile> roots; private final FileTreeModel model; private State(FileChooserDescriptor descriptor, FileRefresher refresher, boolean sortDirectories, boolean sortArchives, FileTreeModel model) { this.descriptor = descriptor; this.refresher = refresher; this.sortDirectories = sortDirectories; this.sortArchives = sortArchives; this.roots = getRoots(descriptor); this.path = roots != null && 1 == roots.size() ? null : new TreePath(this); this.model = model; } private int compare(VirtualFile one, VirtualFile two) { if (one == null && two == null) return 0; if (one == null) return -1; if (two == null) return 1; if (sortDirectories) { boolean isDirectory = one.isDirectory(); if (isDirectory != two.isDirectory()) return isDirectory ? -1 : 1; if (!isDirectory && sortArchives && descriptor.isChooseJarContents()) { boolean isArchive = FileElement.isArchive(one); if (isArchive != FileElement.isArchive(two)) return isArchive ? -1 : 1; } } return StringUtil.naturalCompare(one.getName(), two.getName()); } private static boolean isValid(VirtualFile file) { return file != null && file.isValid(); } private boolean isVisible(VirtualFile file) { return isValid(file) && descriptor.isFileVisible(file, descriptor.isShowHiddenFiles()); } private boolean isLeaf(VirtualFile file) { if (file == null || file.isDirectory()) return false; return !descriptor.isChooseJarContents() || !FileElement.isArchive(file); } private VirtualFile[] getChildren(VirtualFile file) { if (!isValid(file)) return null; if (file.isDirectory()) return file.getChildren(); if (!descriptor.isChooseJarContents() || !FileElement.isArchive(file)) return null; String path = file.getPath() + JarFileSystem.JAR_SEPARATOR; VirtualFile jar = JarFileSystem.getInstance().findFileByPath(path); return jar == null ? VirtualFile.EMPTY_ARRAY : jar.getChildren(); } private List<Root> getRoots() { List<VirtualFile> files = roots; if (files == null) files = getSystemRoots(); if (files.isEmpty()) return Collections.emptyList(); return ContainerUtil.map(files, file -> new Root(this, file)); } private static List<VirtualFile> getRoots(FileChooserDescriptor descriptor) { List<VirtualFile> list = ContainerUtil.filter(descriptor.getRoots(), State::isValid); return list.isEmpty() && descriptor.isShowFileSystemRoots() ? null : list; } private static @NotNull List<VirtualFile> getSystemRoots() { List<Path> roots = ContainerUtil.newArrayList(FileSystems.getDefault().getRootDirectories()); if (WSLUtil.isSystemCompatible() && Experiments.getInstance().isFeatureEnabled("wsl.p9.show.roots.in.file.chooser")) { LOG.debug("Fetching WSL distributions..."); Future<List<WSLDistribution>> future = WslDistributionManager.getInstance().getInstalledDistributionsFuture(); try { List<WSLDistribution> distributions = future.get(100, TimeUnit.MILLISECONDS); List<Path> wslRoots = ContainerUtil.map(distributions, WSLDistribution::getUNCRootPath); if (LOG.isDebugEnabled()) { LOG.debug("Added WSL roots: " + wslRoots); } roots.addAll(wslRoots); } catch (InterruptedException | ExecutionException e) { LOG.error("Unexpected exception when fetching WSL distributions", e); } catch (TimeoutException e) { LOG.info("Timed out when fetching WSL distributions, re-fetch scheduled"); throw new ProcessCanceledException(e); } } return toVirtualFiles(roots); } private static @NotNull List<VirtualFile> toVirtualFiles(@NotNull List<Path> paths) { return paths.stream().map(root -> LocalFileSystem.getInstance().findFileByNioFile(root)).filter(State::isValid).collect( Collectors.toList()); } @Override public String toString() { return descriptor.getTitle(); } } private static class Node extends FileNode { private boolean invalid; private Node(State state, VirtualFile file) { super(file); if (state.refresher != null && !state.refresher.isRecursive()) state.refresher.register(file); updateContent(state); } private boolean updateContent(State state) { VirtualFile file = getFile(); if (file == null) return updateName(state.descriptor.getTitle()); Icon icon = state.descriptor.getIcon(file); String name = state.descriptor.getName(file); String comment = state.descriptor.getComment(file); if (name == null || comment == null) name = file.getPresentableName(); boolean updated = false; if (updateIcon(icon)) updated = true; if (updateName(name)) updated = true; if (updateComment(comment)) updated = true; if (updateValid(file.isValid())) updated = true; if (updateHidden(FileElement.isFileHidden(file))) updated = true; if (updateSpecial(file.is(VFileProperty.SPECIAL))) updated = true; if (updateSymlink(file.is(VFileProperty.SYMLINK))) updated = true; if (updateWritable(file.isWritable())) updated = true; return updated; } @Override public String toString() { return getName(); } } private static final class Root extends Node { private final MapBasedTree<VirtualFile, Node> tree; private Root(State state, VirtualFile file) { super(state, file); if (state.refresher != null && state.refresher.isRecursive()) state.refresher.register(file); tree = new MapBasedTree<>(false, node -> node.getFile(), state.path); tree.onInsert(node -> markDirtyInternal(node.getFile())); tree.updateRoot(Pair.create(this, state.isLeaf(file))); } private static void markDirtyInternal(VirtualFile file) { if (file instanceof VirtualFileSystemEntry) { Method method = ReflectionUtil.getDeclaredMethod(VirtualFileSystemEntry.class, "markDirtyInternal"); if (method != null) { try { method.invoke(file); } catch (Exception ignore) { } } } } private UpdateResult<Node> updateChildren(State state, Entry<Node> parent) { VirtualFile[] children = state.getChildren(parent.getNode().getFile()); if (children == null) return tree.update(parent, null); if (children.length == 0) return tree.update(parent, Collections.emptyList()); return tree.update(parent, Arrays.stream(children).filter(state::isVisible).sorted(state::compare).map(file -> { Entry<Node> entry = tree.findEntry(file); return entry != null && parent == entry.getParentPath() ? Pair.create(entry.getNode(), entry.isLeaf()) : Pair.create(new Node(state, file), state.isLeaf(file)); }).collect(Collectors.toList())); } } }
package com.ceco.gm2.gravitybox; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.MultiSelectListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.provider.MediaStore; import android.view.Display; import android.view.Window; import android.widget.Toast; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Rect; import net.margaritov.preference.colorpicker.ColorPickerPreference; public class GravityBoxSettings extends Activity { public static final String PREF_KEY_QUICK_SETTINGS = "pref_quick_settings"; public static final String PREF_KEY_QUICK_SETTINGS_TILES_PER_ROW = "pref_qs_tiles_per_row"; public static final String PREF_KEY_QUICK_SETTINGS_AUTOSWITCH = "pref_auto_switch_qs"; public static final String PREF_KEY_QUICK_PULLDOWN = "pref_quick_pulldown"; public static final int QUICK_PULLDOWN_OFF = 0; public static final int QUICK_PULLDOWN_RIGHT = 1; public static final int QUICK_PULLDOWN_LEFT = 2; public static final String PREF_KEY_BATTERY_STYLE = "pref_battery_style"; public static final String PREF_KEY_BATTERY_PERCENT_TEXT = "pref_battery_percent_text"; public static final int BATTERY_STYLE_STOCK = 1; public static final int BATTERY_STYLE_CIRCLE = 2; public static final int BATTERY_STYLE_CIRCLE_PERCENT = 3; public static final int BATTERY_STYLE_NONE = 0; public static final String PREF_KEY_LOW_BATTERY_WARNING_POLICY = "pref_low_battery_warning_policy"; public static final int BATTERY_WARNING_POPUP = 1; public static final int BATTERY_WARNING_SOUND = 2; public static final String PREF_KEY_SIGNAL_ICON_AUTOHIDE = "pref_signal_icon_autohide"; public static final String PREF_KEY_DISABLE_ROAMING_INDICATORS = "pref_disable_roaming_indicators"; public static final String ACTION_DISABLE_ROAMING_INDICATORS_CHANGED = "gravitybox.intent.action.DISABLE_ROAMING_INDICATORS_CHANGED"; public static final String EXTRA_INDICATORS_DISABLED = "indicatorsDisabled"; public static final String PREF_KEY_POWEROFF_ADVANCED = "pref_poweroff_advanced"; public static final String PREF_KEY_VOL_KEY_CURSOR_CONTROL = "pref_vol_key_cursor_control"; public static final int VOL_KEY_CURSOR_CONTROL_OFF = 0; public static final int VOL_KEY_CURSOR_CONTROL_ON = 1; public static final int VOL_KEY_CURSOR_CONTROL_ON_REVERSE = 2; public static final String PREF_KEY_RECENTS_CLEAR_ALL = "pref_recents_clear_all2"; public static final String PREF_KEY_RECENTS_CLEAR_MARGIN_TOP = "pref_recent_clear_margin_top"; public static final int RECENT_CLEAR_OFF = 0; public static final int RECENT_CLEAR_TOP_LEFT = 51; public static final int RECENT_CLEAR_TOP_RIGHT = 53; public static final int RECENT_CLEAR_BOTTOM_LEFT = 83; public static final int RECENT_CLEAR_BOTTOM_RIGHT = 85; public static final String PREF_CAT_KEY_PHONE = "pref_cat_phone"; public static final String PREF_KEY_CALLER_FULLSCREEN_PHOTO = "pref_caller_fullscreen_photo"; public static final String PREF_KEY_ROAMING_WARNING_DISABLE = "pref_roaming_warning_disable"; public static final String PREF_CAT_KEY_FIXES = "pref_cat_fixes"; public static final String PREF_KEY_FIX_DATETIME_CRASH = "pref_fix_datetime_crash"; public static final String PREF_KEY_FIX_CALLER_ID_PHONE = "pref_fix_caller_id_phone"; public static final String PREF_KEY_FIX_CALLER_ID_MMS = "pref_fix_caller_id_mms"; public static final String PREF_KEY_FIX_MMS_WAKELOCK = "pref_mms_fix_wakelock"; public static final String PREF_KEY_FIX_CALENDAR = "pref_fix_calendar"; public static final String PREF_CAT_KEY_STATUSBAR = "pref_cat_statusbar"; public static final String PREF_CAT_KEY_STATUSBAR_QS = "pref_cat_statusbar_qs"; public static final String PREF_KEY_STATUSBAR_BGCOLOR = "pref_statusbar_bgcolor2"; public static final String PREF_KEY_STATUSBAR_ICON_COLOR_ENABLE = "pref_statusbar_icon_color_enable"; public static final String PREF_KEY_STATUSBAR_ICON_COLOR = "pref_statusbar_icon_color"; public static final String PREF_KEY_STATUSBAR_DATA_ACTIVITY_COLOR = "pref_statusbar_data_activity_color"; public static final String PREF_KEY_STATUSBAR_CENTER_CLOCK = "pref_statusbar_center_clock"; public static final String PREF_KEY_STATUSBAR_CLOCK_DOW = "pref_statusbar_clock_dow"; public static final String PREF_KEY_STATUSBAR_CLOCK_AMPM_HIDE = "pref_clock_ampm_hide"; public static final String PREF_KEY_STATUSBAR_CLOCK_HIDE = "pref_clock_hide"; public static final String PREF_KEY_ALARM_ICON_HIDE = "pref_alarm_icon_hide"; public static final String PREF_KEY_TM_STATUSBAR_LAUNCHER = "pref_tm_statusbar_launcher"; public static final String PREF_KEY_TM_STATUSBAR_LOCKSCREEN = "pref_tm_statusbar_lockscreen"; public static final String PREF_KEY_TM_NAVBAR_LAUNCHER = "pref_tm_navbar_launcher"; public static final String PREF_KEY_TM_NAVBAR_LOCKSCREEN = "pref_tm_navbar_lockscreen"; public static final String PREF_KEY_FIX_TTS_SETTINGS = "pref_fix_tts_settings"; public static final String PREF_KEY_FIX_DEV_OPTS = "pref_fix_dev_opts"; public static final String PREF_KEY_ABOUT_GRAVITYBOX = "pref_about_gb"; public static final String PREF_KEY_ABOUT_XPOSED = "pref_about_xposed"; public static final String PREF_KEY_ABOUT_DONATE = "pref_about_donate"; public static final String PREF_KEY_CRT_OFF_EFFECT = "pref_crt_off_effect"; public static final String PREF_KEY_ENGINEERING_MODE = "pref_engineering_mode"; public static final String APP_ENGINEERING_MODE = "com.mediatek.engineermode"; public static final String APP_ENGINEERING_MODE_CLASS = "com.mediatek.engineermode.EngineerMode"; public static final String PREF_KEY_DUAL_SIM_RINGER = "pref_dual_sim_ringer"; public static final String APP_DUAL_SIM_RINGER = "dualsim.ringer"; public static final String APP_DUAL_SIM_RINGER_CLASS = "dualsim.ringer.main"; public static final String PREF_CAT_KEY_LOCKSCREEN_BACCKGROUND = "pref_cat_lockscreen_background"; public static final String PREF_KEY_LOCKSCREEN_BACKGROUND = "pref_lockscreen_background"; public static final String PREF_KEY_LOCKSCREEN_BACKGROUND_COLOR = "pref_lockscreen_bg_color"; public static final String PREF_KEY_LOCKSCREEN_BACKGROUND_IMAGE = "pref_lockscreen_bg_image"; public static final String LOCKSCREEN_BG_DEFAULT = "default"; public static final String LOCKSCREEN_BG_COLOR = "color"; public static final String LOCKSCREEN_BG_IMAGE = "image"; private static final int LOCKSCREEN_BACKGROUND = 1024; public static final String PREF_KEY_LOCKSCREEN_MAXIMIZE_WIDGETS = "pref_lockscreen_maximize_widgets"; public static final String PREF_KEY_LOCKSCREEN_ROTATION = "pref_lockscreen_rotation"; public static final String PREF_KEY_LOCKSCREEN_MENU_KEY = "pref_lockscreen_menu_key"; public static final String PREF_KEY_FLASHING_LED_DISABLE = "pref_flashing_led_disable"; public static final String PREF_KEY_CHARGING_LED_DISABLE = "pref_charging_led_disable"; public static final String PREF_KEY_BRIGHTNESS_MIN = "pref_brightness_min2"; public static final String PREF_KEY_SCREEN_DIM_LEVEL = "pref_screen_dim_level"; public static final String PREF_KEY_AUTOBRIGHTNESS = "pref_autobrightness"; public static final String PREF_KEY_HOLO_BG_SOLID_BLACK = "pref_holo_bg_solid_black"; public static final String PREF_KEY_HOLO_BG_DITHER = "pref_holo_bg_dither"; public static final String PREF_KEY_VOL_MUSIC_CONTROLS = "pref_vol_music_controls"; public static final String PREF_KEY_MUSIC_VOLUME_STEPS = "pref_music_volume_steps"; public static final String PREF_KEY_SAFE_MEDIA_VOLUME = "pref_safe_media_volume"; public static final String PREF_KEY_VOLUME_PANEL_EXPANDABLE = "pref_volume_panel_expandable"; public static final String ACTION_PREF_VOLUME_PANEL_MODE_CHANGED = "gravitybox.intent.action.VOLUME_PANEL_MODE_CHANGED"; public static final String EXTRA_EXPANDABLE = "expandable"; public static final String PREF_KEY_LINK_VOLUMES = "pref_link_volumes"; public static final String ACTION_PREF_LINK_VOLUMES_CHANGED = "gravitybox.intent.action.LINK_VOLUMES_CHANGED"; public static final String EXTRA_LINKED = "linked"; public static final String PREF_KEY_HWKEY_MENU_LONGPRESS = "pref_hwkey_menu_longpress"; public static final String PREF_KEY_HWKEY_MENU_DOUBLETAP = "pref_hwkey_menu_doubletap"; public static final String PREF_KEY_HWKEY_BACK_LONGPRESS = "pref_hwkey_back_longpress"; public static final String PREF_KEY_HWKEY_DOUBLETAP_SPEED = "pref_hwkey_doubletap_speed"; public static final String PREF_KEY_HWKEY_KILL_DELAY = "pref_hwkey_kill_delay"; public static final String PREF_KEY_VOLUME_ROCKER_WAKE_DISABLE = "pref_volume_rocker_wake_disable"; public static final int HWKEY_ACTION_DEFAULT = 0; public static final int HWKEY_ACTION_SEARCH = 1; public static final int HWKEY_ACTION_VOICE_SEARCH = 2; public static final int HWKEY_ACTION_PREV_APP = 3; public static final int HWKEY_ACTION_KILL = 4; public static final int HWKEY_ACTION_SLEEP = 5; public static final int HWKEY_DOUBLETAP_SPEED_DEFAULT = 400; public static final int HWKEY_KILL_DELAY_DEFAULT = 1000; public static final String ACTION_PREF_HWKEY_MENU_LONGPRESS_CHANGED = "gravitybox.intent.action.HWKEY_MENU_LONGPRESS_CHANGED"; public static final String ACTION_PREF_HWKEY_MENU_DOUBLETAP_CHANGED = "gravitybox.intent.action.HWKEY_MENU_DOUBLETAP_CHANGED"; public static final String ACTION_PREF_HWKEY_BACK_LONGPRESS_CHANGED = "gravitybox.intent.action.HWKEY_BACK_LONGPRESS_CHANGED"; public static final String ACTION_PREF_HWKEY_DOUBLETAP_SPEED_CHANGED = "gravitybox.intent.action.HWKEY_DOUBLETAP_SPEED_CHANGED"; public static final String ACTION_PREF_HWKEY_KILL_DELAY_CHANGED = "gravitybox.intent.action.HWKEY_KILL_DELAY_CHANGED"; public static final String ACTION_PREF_VOLUME_ROCKER_WAKE_CHANGED = "gravitybox.intent.action.VOLUME_ROCKER_WAKE_CHANGED"; public static final String EXTRA_HWKEY_VALUE = "hwKeyValue"; public static final String EXTRA_VOLUME_ROCKER_WAKE_DISABLE = "volumeRockerWakeDisable"; public static final String PREF_KEY_PHONE_FLIP = "pref_phone_flip"; public static final int PHONE_FLIP_ACTION_NONE = 0; public static final int PHONE_FLIP_ACTION_MUTE = 1; public static final int PHONE_FLIP_ACTION_DISMISS = 2; public static final String PREF_KEY_PHONE_CALL_CONNECT_VIBRATE_DISABLE = "pref_phone_call_connect_vibrate_disable"; public static final String PREF_CAT_KEY_NOTIF_DRAWER_STYLE = "pref_cat_notification_drawer_style"; public static final String PREF_KEY_NOTIF_BACKGROUND = "pref_notif_background"; public static final String PREF_KEY_NOTIF_COLOR = "pref_notif_color"; public static final String PREF_KEY_NOTIF_COLOR_MODE = "pref_notif_color_mode"; public static final String PREF_KEY_NOTIF_IMAGE_PORTRAIT = "pref_notif_image_portrait"; public static final String PREF_KEY_NOTIF_IMAGE_LANDSCAPE = "pref_notif_image_landscape"; public static final String PREF_KEY_NOTIF_BACKGROUND_ALPHA = "pref_notif_background_alpha"; public static final String NOTIF_BG_DEFAULT = "default"; public static final String NOTIF_BG_COLOR = "color"; public static final String NOTIF_BG_IMAGE = "image"; public static final String NOTIF_BG_COLOR_MODE_OVERLAY = "overlay"; public static final String NOTIF_BG_COLOR_MODE_UNDERLAY = "underlay"; private static final int NOTIF_BG_IMAGE_PORTRAIT = 1025; private static final int NOTIF_BG_IMAGE_LANDSCAPE = 1026; public static final String ACTION_NOTIF_BACKGROUND_CHANGED = "gravitybox.intent.action.NOTIF_BACKGROUND_CHANGED"; public static final String EXTRA_BG_TYPE = "bgType"; public static final String EXTRA_BG_COLOR = "bgColor"; public static final String EXTRA_BG_COLOR_MODE = "bgColorMode"; public static final String EXTRA_BG_ALPHA = "bgAlpha"; public static final String PREF_KEY_PIE_CONTROL_ENABLE = "pref_pie_control_enable"; public static final String PREF_KEY_PIE_CONTROL_SEARCH = "pref_pie_control_search"; public static final String PREF_KEY_PIE_CONTROL_MENU = "pref_pie_control_menu"; public static final String PREF_KEY_PIE_CONTROL_TRIGGERS = "pref_pie_control_trigger_positions"; public static final String PREF_KEY_PIE_CONTROL_TRIGGER_SIZE = "pref_pie_control_trigger_size"; public static final String PREF_KEY_PIE_CONTROL_SIZE = "pref_pie_control_size"; public static final String PREF_KEY_NAVBAR_DISABLE = "pref_navbar_disable"; public static final String PREF_KEY_HWKEYS_DISABLE = "pref_hwkeys_disable"; public static final String ACTION_PREF_PIE_CHANGED = "gravitybox.intent.action.PREF_PIE_CHANGED"; public static final String EXTRA_PIE_ENABLE = "pieEnable"; public static final String EXTRA_PIE_SEARCH = "pieSearch"; public static final String EXTRA_PIE_MENU = "pieMenu"; public static final String EXTRA_PIE_TRIGGERS = "pieTriggers"; public static final String EXTRA_PIE_TRIGGER_SIZE = "pieTriggerSize"; public static final String EXTRA_PIE_SIZE = "pieSize"; public static final String EXTRA_PIE_HWKEYS_DISABLE = "hwKeysDisable"; public static final String PREF_KEY_BUTTON_BACKLIGHT_MODE = "pref_button_backlight_mode"; public static final String PREF_KEY_BUTTON_BACKLIGHT_NOTIFICATIONS = "pref_button_backlight_notifications"; public static final String ACTION_PREF_BUTTON_BACKLIGHT_CHANGED = "gravitybox.intent.action.BUTTON_BACKLIGHT_CHANGED"; public static final String EXTRA_BB_MODE = "bbMode"; public static final String EXTRA_BB_NOTIF = "bbNotif"; public static final String BB_MODE_DEFAULT = "default"; public static final String BB_MODE_DISABLE = "disable"; public static final String BB_MODE_ALWAYS_ON = "always_on"; public static final String PREF_KEY_QUICKAPP_DEFAULT = "pref_quickapp_default"; public static final String PREF_KEY_QUICKAPP_SLOT1 = "pref_quickapp_slot1"; public static final String PREF_KEY_QUICKAPP_SLOT2 = "pref_quickapp_slot2"; public static final String PREF_KEY_QUICKAPP_SLOT3 = "pref_quickapp_slot3"; public static final String PREF_KEY_QUICKAPP_SLOT4 = "pref_quickapp_slot4"; public static final String ACTION_PREF_QUICKAPP_CHANGED = "gravitybox.intent.action.QUICKAPP_CHANGED"; public static final String EXTRA_QUICKAPP_DEFAULT = "quickAppDefault"; public static final String EXTRA_QUICKAPP_SLOT1 = "quickAppSlot1"; public static final String EXTRA_QUICKAPP_SLOT2 = "quickAppSlot2"; public static final String EXTRA_QUICKAPP_SLOT3 = "quickAppSlot3"; public static final String EXTRA_QUICKAPP_SLOT4 = "quickAppSlot4"; public static final String PREF_KEY_GB_THEME_DARK = "pref_gb_theme_dark"; public static final String FILE_THEME_DARK_FLAG = "theme_dark"; public static final String ACTION_PREF_BATTERY_STYLE_CHANGED = "gravitybox.intent.action.BATTERY_STYLE_CHANGED"; public static final String ACTION_PREF_SIGNAL_ICON_AUTOHIDE_CHANGED = "gravitybox.intent.action.SIGNAL_ICON_AUTOHIDE_CHANGED"; public static final String ACTION_PREF_STATUSBAR_COLOR_CHANGED = "gravitybox.intent.action.STATUSBAR_COLOR_CHANGED"; public static final String EXTRA_SB_BG_COLOR = "bgColor"; public static final String EXTRA_SB_ICON_COLOR_ENABLE = "iconColorEnable"; public static final String EXTRA_SB_ICON_COLOR = "iconColor"; public static final String EXTRA_SB_DATA_ACTIVITY_COLOR = "dataActivityColor"; public static final String EXTRA_TM_SB_LAUNCHER = "tmSbLauncher"; public static final String EXTRA_TM_SB_LOCKSCREEN = "tmSbLockscreen"; public static final String EXTRA_TM_NB_LAUNCHER = "tmNbLauncher"; public static final String EXTRA_TM_NB_LOCKSCREEN = "tmNbLockscreen"; public static final String ACTION_PREF_QUICKSETTINGS_CHANGED = "gravitybox.intent.action.QUICKSETTINGS_CHANGED"; public static final String EXTRA_QS_PREFS = "qsPrefs"; public static final String EXTRA_QS_COLS = "qsCols"; public static final String EXTRA_QS_AUTOSWITCH = "qsAutoSwitch"; public static final String EXTRA_QUICK_PULLDOWN = "quickPulldown"; public static final String ACTION_PREF_CLOCK_CHANGED = "gravitybox.intent.action.CENTER_CLOCK_CHANGED"; public static final String EXTRA_CENTER_CLOCK = "centerClock"; public static final String EXTRA_CLOCK_DOW = "clockDow"; public static final String EXTRA_AMPM_HIDE = "ampmHide"; public static final String EXTRA_CLOCK_HIDE = "clockHide"; public static final String EXTRA_ALARM_HIDE = "alarmHide"; public static final String ACTION_PREF_SAFE_MEDIA_VOLUME_CHANGED = "gravitybox.intent.action.SAFE_MEDIA_VOLUME_CHANGED"; public static final String EXTRA_SAFE_MEDIA_VOLUME_ENABLED = "enabled"; private static final List<String> rebootKeys = new ArrayList<String>(Arrays.asList( PREF_KEY_FIX_DATETIME_CRASH, PREF_KEY_FIX_CALENDAR, PREF_KEY_FIX_CALLER_ID_PHONE, PREF_KEY_FIX_CALLER_ID_MMS, PREF_KEY_FIX_TTS_SETTINGS, PREF_KEY_FIX_DEV_OPTS, PREF_KEY_BRIGHTNESS_MIN, PREF_KEY_LOCKSCREEN_MENU_KEY, PREF_KEY_FIX_MMS_WAKELOCK, PREF_KEY_MUSIC_VOLUME_STEPS, PREF_KEY_HOLO_BG_SOLID_BLACK, PREF_KEY_NAVBAR_DISABLE, PREF_KEY_HOLO_BG_DITHER, PREF_KEY_SCREEN_DIM_LEVEL )); @Override protected void onCreate(Bundle savedInstanceState) { // set Holo Dark theme if flag file exists File file = new File(getFilesDir() + "/" + FILE_THEME_DARK_FLAG); if (file.exists()) { this.setTheme(android.R.style.Theme_Holo); } super.onCreate(savedInstanceState); if (savedInstanceState == null) getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit(); } public static class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { private ListPreference mBatteryStyle; private ListPreference mLowBatteryWarning; private MultiSelectListPreference mSignalIconAutohide; private SharedPreferences mPrefs; private AlertDialog mDialog; private MultiSelectListPreference mQuickSettings; private ColorPickerPreference mStatusbarBgColor; private Preference mPrefAboutGb; private Preference mPrefAboutXposed; private Preference mPrefAboutDonate; private Preference mPrefEngMode; private Preference mPrefDualSimRinger; private PreferenceCategory mPrefCatLockscreenBg; private ListPreference mPrefLockscreenBg; private ColorPickerPreference mPrefLockscreenBgColor; private Preference mPrefLockscreenBgImage; private File wallpaperImage; private File wallpaperTemporary; private File notifBgImagePortrait; private File notifBgImageLandscape; private ListPreference mPrefHwKeyMenuLongpress; private ListPreference mPrefHwKeyMenuDoubletap; private ListPreference mPrefHwKeyBackLongpress; private ListPreference mPrefHwKeyDoubletapSpeed; private ListPreference mPrefHwKeyKillDelay; private ListPreference mPrefPhoneFlip; private CheckBoxPreference mPrefSbIconColorEnable; private ColorPickerPreference mPrefSbIconColor; private ColorPickerPreference mPrefSbDaColor; private PreferenceScreen mPrefCatFixes; private PreferenceScreen mPrefCatStatusbar; private PreferenceScreen mPrefCatStatusbarQs; private CheckBoxPreference mPrefAutoSwitchQs; private ListPreference mPrefQuickPulldown; private PreferenceScreen mPrefCatNotifDrawerStyle; private ListPreference mPrefNotifBackground; private ColorPickerPreference mPrefNotifColor; private Preference mPrefNotifImagePortrait; private Preference mPrefNotifImageLandscape; private ListPreference mPrefNotifColorMode; private CheckBoxPreference mPrefDisableRoamingIndicators; private ListPreference mPrefButtonBacklightMode; private CheckBoxPreference mPrefPieEnabled; private CheckBoxPreference mPrefPieNavBarDisabled; private CheckBoxPreference mPrefPieHwKeysDisabled; private CheckBoxPreference mPrefGbThemeDark; private ListPreference mPrefRecentClear; private PreferenceScreen mPrefCatPhone; private CheckBoxPreference mPrefRoamingWarningDisable; @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this is important because although the handler classes that read these settings // are in the same package, they are executed in the context of the hooked package getPreferenceManager().setSharedPreferencesMode(Context.MODE_WORLD_READABLE); addPreferencesFromResource(R.xml.gravitybox); mPrefs = getPreferenceScreen().getSharedPreferences(); mBatteryStyle = (ListPreference) findPreference(PREF_KEY_BATTERY_STYLE); mLowBatteryWarning = (ListPreference) findPreference(PREF_KEY_LOW_BATTERY_WARNING_POLICY); mSignalIconAutohide = (MultiSelectListPreference) findPreference(PREF_KEY_SIGNAL_ICON_AUTOHIDE); mQuickSettings = (MultiSelectListPreference) findPreference(PREF_KEY_QUICK_SETTINGS); mStatusbarBgColor = (ColorPickerPreference) findPreference(PREF_KEY_STATUSBAR_BGCOLOR); mPrefAboutGb = (Preference) findPreference(PREF_KEY_ABOUT_GRAVITYBOX); String version = ""; try { PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version = " v" + pInfo.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } finally { mPrefAboutGb.setTitle(getActivity().getTitle() + version); } mPrefAboutXposed = (Preference) findPreference(PREF_KEY_ABOUT_XPOSED); mPrefAboutDonate = (Preference) findPreference(PREF_KEY_ABOUT_DONATE); mPrefEngMode = (Preference) findPreference(PREF_KEY_ENGINEERING_MODE); if (!isAppInstalled(APP_ENGINEERING_MODE)) { getPreferenceScreen().removePreference(mPrefEngMode); } mPrefDualSimRinger = (Preference) findPreference(PREF_KEY_DUAL_SIM_RINGER); if (!isAppInstalled(APP_DUAL_SIM_RINGER)) { getPreferenceScreen().removePreference(mPrefDualSimRinger); } mPrefCatLockscreenBg = (PreferenceCategory) findPreference(PREF_CAT_KEY_LOCKSCREEN_BACCKGROUND); mPrefLockscreenBg = (ListPreference) findPreference(PREF_KEY_LOCKSCREEN_BACKGROUND); mPrefLockscreenBgColor = (ColorPickerPreference) findPreference(PREF_KEY_LOCKSCREEN_BACKGROUND_COLOR); mPrefLockscreenBgImage = (Preference) findPreference(PREF_KEY_LOCKSCREEN_BACKGROUND_IMAGE); wallpaperImage = new File(getActivity().getFilesDir() + "/lockwallpaper"); wallpaperTemporary = new File(getActivity().getCacheDir() + "/lockwallpaper.tmp"); notifBgImagePortrait = new File(getActivity().getFilesDir() + "/notifwallpaper"); notifBgImageLandscape = new File(getActivity().getFilesDir() + "/notifwallpaper_landscape"); mPrefHwKeyMenuLongpress = (ListPreference) findPreference(PREF_KEY_HWKEY_MENU_LONGPRESS); mPrefHwKeyMenuDoubletap = (ListPreference) findPreference(PREF_KEY_HWKEY_MENU_DOUBLETAP); mPrefHwKeyBackLongpress = (ListPreference) findPreference(PREF_KEY_HWKEY_BACK_LONGPRESS); mPrefHwKeyDoubletapSpeed = (ListPreference) findPreference(PREF_KEY_HWKEY_DOUBLETAP_SPEED); mPrefHwKeyKillDelay = (ListPreference) findPreference(PREF_KEY_HWKEY_KILL_DELAY); mPrefPhoneFlip = (ListPreference) findPreference(PREF_KEY_PHONE_FLIP); mPrefSbIconColorEnable = (CheckBoxPreference) findPreference(PREF_KEY_STATUSBAR_ICON_COLOR_ENABLE); mPrefSbIconColor = (ColorPickerPreference) findPreference(PREF_KEY_STATUSBAR_ICON_COLOR); mPrefSbDaColor = (ColorPickerPreference) findPreference(PREF_KEY_STATUSBAR_DATA_ACTIVITY_COLOR); mPrefCatFixes = (PreferenceScreen) findPreference(PREF_CAT_KEY_FIXES); mPrefCatStatusbar = (PreferenceScreen) findPreference(PREF_CAT_KEY_STATUSBAR); mPrefCatStatusbarQs = (PreferenceScreen) findPreference(PREF_CAT_KEY_STATUSBAR_QS); mPrefAutoSwitchQs = (CheckBoxPreference) findPreference(PREF_KEY_QUICK_SETTINGS_AUTOSWITCH); mPrefQuickPulldown = (ListPreference) findPreference(PREF_KEY_QUICK_PULLDOWN); mPrefCatNotifDrawerStyle = (PreferenceScreen) findPreference(PREF_CAT_KEY_NOTIF_DRAWER_STYLE); mPrefNotifBackground = (ListPreference) findPreference(PREF_KEY_NOTIF_BACKGROUND); mPrefNotifColor = (ColorPickerPreference) findPreference(PREF_KEY_NOTIF_COLOR); mPrefNotifImagePortrait = (Preference) findPreference(PREF_KEY_NOTIF_IMAGE_PORTRAIT); mPrefNotifImageLandscape = (Preference) findPreference(PREF_KEY_NOTIF_IMAGE_LANDSCAPE); mPrefNotifColorMode = (ListPreference) findPreference(PREF_KEY_NOTIF_COLOR_MODE); mPrefDisableRoamingIndicators = (CheckBoxPreference) findPreference(PREF_KEY_DISABLE_ROAMING_INDICATORS); mPrefButtonBacklightMode = (ListPreference) findPreference(PREF_KEY_BUTTON_BACKLIGHT_MODE); mPrefPieEnabled = (CheckBoxPreference) findPreference(PREF_KEY_PIE_CONTROL_ENABLE); mPrefPieNavBarDisabled = (CheckBoxPreference) findPreference(PREF_KEY_NAVBAR_DISABLE); mPrefPieHwKeysDisabled = (CheckBoxPreference) findPreference(PREF_KEY_HWKEYS_DISABLE); mPrefGbThemeDark = (CheckBoxPreference) findPreference(PREF_KEY_GB_THEME_DARK); File file = new File(getActivity().getFilesDir() + "/" + FILE_THEME_DARK_FLAG); mPrefGbThemeDark.setChecked(file.exists()); mPrefRecentClear = (ListPreference) findPreference(PREF_KEY_RECENTS_CLEAR_ALL); mPrefCatPhone = (PreferenceScreen) findPreference(PREF_CAT_KEY_PHONE); mPrefRoamingWarningDisable = (CheckBoxPreference) findPreference(PREF_KEY_ROAMING_WARNING_DISABLE); // Remove Phone specific preferences on Tablet devices if (Utils.isTablet(getActivity())) { mPrefCatStatusbarQs.removePreference(mPrefAutoSwitchQs); mPrefCatStatusbarQs.removePreference(mPrefQuickPulldown); } // Remove MTK specific preferences for non-mtk device if (!Utils.isMtkDevice()) { getPreferenceScreen().removePreference(mPrefCatFixes); mPrefCatStatusbar.removePreference(mSignalIconAutohide); mPrefCatStatusbar.removePreference(mPrefDisableRoamingIndicators); mQuickSettings.setEntries(R.array.qs_tile_aosp_entries); mQuickSettings.setEntryValues(R.array.qs_tile_aosp_values); mPrefCatPhone.removePreference(mPrefRoamingWarningDisable); } else { mQuickSettings.setEntries(R.array.qs_tile_entries); mQuickSettings.setEntryValues(R.array.qs_tile_values); } setDefaultValues(); } @Override public void onResume() { super.onResume(); updatePreferences(null); mPrefs.registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { mPrefs.unregisterOnSharedPreferenceChangeListener(this); if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); mDialog = null; } super.onPause(); } private void setDefaultValues() { if (mPrefs.getStringSet(PREF_KEY_QUICK_SETTINGS, null) == null) { Editor e = mPrefs.edit(); Set<String> defVal = new HashSet<String>( Arrays.asList(getResources().getStringArray( Utils.isMtkDevice() ? R.array.qs_tile_values : R.array.qs_tile_aosp_values))); e.putStringSet(PREF_KEY_QUICK_SETTINGS, defVal); e.commit(); mQuickSettings.setValues(defVal); } } private void updatePreferences(String key) { if (key == null || key.equals(PREF_KEY_BATTERY_STYLE)) { mBatteryStyle.setSummary(mBatteryStyle.getEntry()); } if (key == null || key.equals(PREF_KEY_LOW_BATTERY_WARNING_POLICY)) { mLowBatteryWarning.setSummary(mLowBatteryWarning.getEntry()); } if (key == null || key.equals(PREF_KEY_SIGNAL_ICON_AUTOHIDE)) { Set<String> autoHide = mSignalIconAutohide.getValues(); String summary = ""; if (autoHide.contains("notifications_disabled")) { summary += getString(R.string.sim_disable_notifications_summary); } if (autoHide.contains("sim1")) { if (!summary.isEmpty()) summary += ", "; summary += getString(R.string.sim_slot_1); } if (autoHide.contains("sim2")) { if (!summary.isEmpty()) summary += ", "; summary += getString(R.string.sim_slot_2); } if (summary.isEmpty()) { summary = getString(R.string.signal_icon_autohide_summary); } mSignalIconAutohide.setSummary(summary); } if (key == null || key.equals(PREF_KEY_LOCKSCREEN_BACKGROUND)) { mPrefLockscreenBg.setSummary(mPrefLockscreenBg.getEntry()); mPrefCatLockscreenBg.removePreference(mPrefLockscreenBgColor); mPrefCatLockscreenBg.removePreference(mPrefLockscreenBgImage); String option = mPrefs.getString(PREF_KEY_LOCKSCREEN_BACKGROUND, LOCKSCREEN_BG_DEFAULT); if (option.equals(LOCKSCREEN_BG_COLOR)) { mPrefCatLockscreenBg.addPreference(mPrefLockscreenBgColor); } else if (option.equals(LOCKSCREEN_BG_IMAGE)) { mPrefCatLockscreenBg.addPreference(mPrefLockscreenBgImage); } } if (key == null || key.equals(PREF_KEY_HWKEY_MENU_LONGPRESS)) { mPrefHwKeyMenuLongpress.setSummary(mPrefHwKeyMenuLongpress.getEntry()); } if (key == null || key.equals(PREF_KEY_HWKEY_MENU_DOUBLETAP)) { mPrefHwKeyMenuDoubletap.setSummary(mPrefHwKeyMenuDoubletap.getEntry()); } if (key == null || key.equals(PREF_KEY_HWKEY_BACK_LONGPRESS)) { mPrefHwKeyBackLongpress.setSummary(mPrefHwKeyBackLongpress.getEntry()); } if (key == null || key.equals(PREF_KEY_HWKEY_DOUBLETAP_SPEED)) { mPrefHwKeyDoubletapSpeed.setSummary(getString(R.string.pref_hwkey_doubletap_speed_summary) + " (" + mPrefHwKeyDoubletapSpeed.getEntry() + ")"); } if (key == null || key.equals(PREF_KEY_HWKEY_KILL_DELAY)) { mPrefHwKeyKillDelay.setSummary(getString(R.string.pref_hwkey_kill_delay_summary) + " (" + mPrefHwKeyKillDelay.getEntry() + ")"); } if (key == null || key.equals(PREF_KEY_PHONE_FLIP)) { mPrefPhoneFlip.setSummary(getString(R.string.pref_phone_flip_summary) + " (" + mPrefPhoneFlip.getEntry() + ")"); } if (key == null || key.equals(PREF_KEY_STATUSBAR_ICON_COLOR_ENABLE)) { mPrefSbIconColor.setEnabled(mPrefSbIconColorEnable.isChecked()); mPrefSbDaColor.setEnabled(mPrefSbIconColorEnable.isChecked()); } if (key == null || key.equals(PREF_KEY_NOTIF_BACKGROUND)) { mPrefNotifBackground.setSummary(mPrefNotifBackground.getEntry()); mPrefCatNotifDrawerStyle.removePreference(mPrefNotifColor); mPrefCatNotifDrawerStyle.removePreference(mPrefNotifColorMode); mPrefCatNotifDrawerStyle.removePreference(mPrefNotifImagePortrait); mPrefCatNotifDrawerStyle.removePreference(mPrefNotifImageLandscape); String option = mPrefs.getString(PREF_KEY_NOTIF_BACKGROUND, NOTIF_BG_DEFAULT); if (option.equals(NOTIF_BG_COLOR)) { mPrefCatNotifDrawerStyle.addPreference(mPrefNotifColor); mPrefCatNotifDrawerStyle.addPreference(mPrefNotifColorMode); } else if (option.equals(NOTIF_BG_IMAGE)) { mPrefCatNotifDrawerStyle.addPreference(mPrefNotifImagePortrait); mPrefCatNotifDrawerStyle.addPreference(mPrefNotifImageLandscape); mPrefCatNotifDrawerStyle.addPreference(mPrefNotifColorMode); } } if (key == null || key.equals(PREF_KEY_NOTIF_COLOR_MODE)) { mPrefNotifColorMode.setSummary(mPrefNotifColorMode.getEntry()); } if (key == null || key.equals(PREF_KEY_BUTTON_BACKLIGHT_MODE)) { mPrefButtonBacklightMode.setSummary(mPrefButtonBacklightMode.getEntry()); } if (key == null || key.equals(PREF_KEY_PIE_CONTROL_ENABLE)) { if (!mPrefPieEnabled.isChecked()) { if (mPrefPieNavBarDisabled.isChecked()) { Editor e = mPrefs.edit(); e.putBoolean(PREF_KEY_NAVBAR_DISABLE, false); e.commit(); mPrefPieNavBarDisabled.setChecked(false); Toast.makeText(getActivity(), getString( R.string.reboot_required), Toast.LENGTH_SHORT).show(); } if (mPrefPieHwKeysDisabled.isChecked()) { Editor e = mPrefs.edit(); e.putBoolean(PREF_KEY_HWKEYS_DISABLE, false); e.commit(); mPrefPieHwKeysDisabled.setChecked(false); } mPrefPieHwKeysDisabled.setEnabled(false); mPrefPieNavBarDisabled.setEnabled(false); } else { mPrefPieNavBarDisabled.setEnabled(true); mPrefPieHwKeysDisabled.setEnabled(true); } } if (key == null || key.equals(PREF_KEY_RECENTS_CLEAR_ALL)) { mPrefRecentClear.setSummary(mPrefRecentClear.getEntry()); } } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { updatePreferences(key); Intent intent = new Intent(); if (key.equals(PREF_KEY_BATTERY_STYLE)) { intent.setAction(ACTION_PREF_BATTERY_STYLE_CHANGED); int batteryStyle = Integer.valueOf(prefs.getString(PREF_KEY_BATTERY_STYLE, "1")); intent.putExtra("batteryStyle", batteryStyle); } else if (key.equals(PREF_KEY_BATTERY_PERCENT_TEXT)) { intent.setAction(ACTION_PREF_BATTERY_STYLE_CHANGED); intent.putExtra("batteryPercent", prefs.getBoolean(PREF_KEY_BATTERY_PERCENT_TEXT, false)); } else if (key.equals(PREF_KEY_SIGNAL_ICON_AUTOHIDE)) { intent.setAction(ACTION_PREF_SIGNAL_ICON_AUTOHIDE_CHANGED); String[] autohidePrefs = mSignalIconAutohide.getValues().toArray(new String[0]); intent.putExtra("autohidePrefs", autohidePrefs); } else if (key.equals(PREF_KEY_QUICK_SETTINGS)) { intent.setAction(ACTION_PREF_QUICKSETTINGS_CHANGED); String[] qsPrefs = mQuickSettings.getValues().toArray(new String[0]); intent.putExtra(EXTRA_QS_PREFS, qsPrefs); } else if (key.equals(PREF_KEY_QUICK_SETTINGS_TILES_PER_ROW)) { intent.setAction(ACTION_PREF_QUICKSETTINGS_CHANGED); intent.putExtra(EXTRA_QS_COLS, Integer.valueOf( prefs.getString(PREF_KEY_QUICK_SETTINGS_TILES_PER_ROW, "3"))); } else if (key.equals(PREF_KEY_QUICK_SETTINGS_AUTOSWITCH)) { intent.setAction(ACTION_PREF_QUICKSETTINGS_CHANGED); intent.putExtra(EXTRA_QS_AUTOSWITCH, prefs.getBoolean(PREF_KEY_QUICK_SETTINGS_AUTOSWITCH, false)); } else if (key.equals(PREF_KEY_QUICK_PULLDOWN)) { intent.setAction(ACTION_PREF_QUICKSETTINGS_CHANGED); intent.putExtra(EXTRA_QUICK_PULLDOWN, Integer.valueOf( prefs.getString(PREF_KEY_QUICK_PULLDOWN, "0"))); } else if (key.equals(PREF_KEY_STATUSBAR_BGCOLOR)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_SB_BG_COLOR, prefs.getInt(PREF_KEY_STATUSBAR_BGCOLOR, Color.BLACK)); } else if (key.equals(PREF_KEY_STATUSBAR_ICON_COLOR_ENABLE)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_SB_ICON_COLOR_ENABLE, prefs.getBoolean(PREF_KEY_STATUSBAR_ICON_COLOR_ENABLE, false)); } else if (key.equals(PREF_KEY_STATUSBAR_ICON_COLOR)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_SB_ICON_COLOR, prefs.getInt(PREF_KEY_STATUSBAR_ICON_COLOR, getResources().getInteger(R.integer.COLOR_HOLO_BLUE_LIGHT))); } else if (key.equals(PREF_KEY_STATUSBAR_DATA_ACTIVITY_COLOR)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_SB_DATA_ACTIVITY_COLOR, prefs.getInt(PREF_KEY_STATUSBAR_DATA_ACTIVITY_COLOR, Color.WHITE)); } else if (key.equals(PREF_KEY_TM_STATUSBAR_LAUNCHER)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_TM_SB_LAUNCHER, prefs.getInt(PREF_KEY_TM_STATUSBAR_LAUNCHER, 0)); } else if (key.equals(PREF_KEY_TM_STATUSBAR_LOCKSCREEN)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_TM_SB_LOCKSCREEN, prefs.getInt(PREF_KEY_TM_STATUSBAR_LOCKSCREEN, 0)); } else if (key.equals(PREF_KEY_TM_NAVBAR_LAUNCHER)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_TM_NB_LAUNCHER, prefs.getInt(PREF_KEY_TM_NAVBAR_LAUNCHER, 0)); } else if (key.equals(PREF_KEY_TM_NAVBAR_LOCKSCREEN)) { intent.setAction(ACTION_PREF_STATUSBAR_COLOR_CHANGED); intent.putExtra(EXTRA_TM_NB_LOCKSCREEN, prefs.getInt(PREF_KEY_TM_NAVBAR_LOCKSCREEN, 0)); } else if (key.equals(PREF_KEY_STATUSBAR_CENTER_CLOCK)) { intent.setAction(ACTION_PREF_CLOCK_CHANGED); intent.putExtra(EXTRA_CENTER_CLOCK, prefs.getBoolean(PREF_KEY_STATUSBAR_CENTER_CLOCK, false)); } else if (key.equals(PREF_KEY_STATUSBAR_CLOCK_DOW)) { intent.setAction(ACTION_PREF_CLOCK_CHANGED); intent.putExtra(EXTRA_CLOCK_DOW, prefs.getBoolean(PREF_KEY_STATUSBAR_CLOCK_DOW, false)); } else if (key.equals(PREF_KEY_STATUSBAR_CLOCK_AMPM_HIDE)) { intent.setAction(ACTION_PREF_CLOCK_CHANGED); intent.putExtra(EXTRA_AMPM_HIDE, prefs.getBoolean( PREF_KEY_STATUSBAR_CLOCK_AMPM_HIDE, false)); } else if (key.equals(PREF_KEY_STATUSBAR_CLOCK_HIDE)) { intent.setAction(ACTION_PREF_CLOCK_CHANGED); intent.putExtra(EXTRA_CLOCK_HIDE, prefs.getBoolean(PREF_KEY_STATUSBAR_CLOCK_HIDE, false)); } else if (key.equals(PREF_KEY_ALARM_ICON_HIDE)) { intent.setAction(ACTION_PREF_CLOCK_CHANGED); intent.putExtra(EXTRA_ALARM_HIDE, prefs.getBoolean(PREF_KEY_ALARM_ICON_HIDE, false)); } else if (key.equals(PREF_KEY_SAFE_MEDIA_VOLUME)) { intent.setAction(ACTION_PREF_SAFE_MEDIA_VOLUME_CHANGED); intent.putExtra(EXTRA_SAFE_MEDIA_VOLUME_ENABLED, prefs.getBoolean(PREF_KEY_SAFE_MEDIA_VOLUME, false)); } else if (key.equals(PREF_KEY_HWKEY_MENU_LONGPRESS)) { intent.setAction(ACTION_PREF_HWKEY_MENU_LONGPRESS_CHANGED); intent.putExtra(EXTRA_HWKEY_VALUE, Integer.valueOf( prefs.getString(PREF_KEY_HWKEY_MENU_LONGPRESS, "0"))); } else if (key.equals(PREF_KEY_HWKEY_MENU_DOUBLETAP)) { intent.setAction(ACTION_PREF_HWKEY_MENU_DOUBLETAP_CHANGED); intent.putExtra(EXTRA_HWKEY_VALUE, Integer.valueOf( prefs.getString(PREF_KEY_HWKEY_MENU_DOUBLETAP, "0"))); } else if (key.equals(PREF_KEY_HWKEY_BACK_LONGPRESS)) { intent.setAction(ACTION_PREF_HWKEY_BACK_LONGPRESS_CHANGED); intent.putExtra(EXTRA_HWKEY_VALUE, Integer.valueOf( prefs.getString(PREF_KEY_HWKEY_BACK_LONGPRESS, "0"))); } else if (key.equals(PREF_KEY_HWKEY_DOUBLETAP_SPEED)) { intent.setAction(ACTION_PREF_HWKEY_DOUBLETAP_SPEED_CHANGED); intent.putExtra(EXTRA_HWKEY_VALUE, Integer.valueOf( prefs.getString(PREF_KEY_HWKEY_DOUBLETAP_SPEED, "400"))); } else if (key.equals(PREF_KEY_HWKEY_KILL_DELAY)) { intent.setAction(ACTION_PREF_HWKEY_KILL_DELAY_CHANGED); intent.putExtra(EXTRA_HWKEY_VALUE, Integer.valueOf( prefs.getString(PREF_KEY_HWKEY_KILL_DELAY, "1000"))); } else if (key.equals(PREF_KEY_VOLUME_ROCKER_WAKE_DISABLE)) { intent.setAction(ACTION_PREF_VOLUME_ROCKER_WAKE_CHANGED); intent.putExtra(EXTRA_VOLUME_ROCKER_WAKE_DISABLE, prefs.getBoolean(PREF_KEY_VOLUME_ROCKER_WAKE_DISABLE, false)); } else if (key.equals(PREF_KEY_VOLUME_PANEL_EXPANDABLE)) { intent.setAction(ACTION_PREF_VOLUME_PANEL_MODE_CHANGED); intent.putExtra(EXTRA_EXPANDABLE, prefs.getBoolean(PREF_KEY_VOLUME_PANEL_EXPANDABLE, true)); } else if (key.equals(PREF_KEY_LINK_VOLUMES)) { intent.setAction(ACTION_PREF_LINK_VOLUMES_CHANGED); intent.putExtra(EXTRA_LINKED, prefs.getBoolean(PREF_KEY_LINK_VOLUMES, true)); } else if (key.equals(PREF_KEY_NOTIF_BACKGROUND)) { intent.setAction(ACTION_NOTIF_BACKGROUND_CHANGED); intent.putExtra(EXTRA_BG_TYPE, prefs.getString( PREF_KEY_NOTIF_BACKGROUND, NOTIF_BG_DEFAULT)); } else if (key.equals(PREF_KEY_NOTIF_COLOR)) { intent.setAction(ACTION_NOTIF_BACKGROUND_CHANGED); intent.putExtra(EXTRA_BG_COLOR, prefs.getInt(PREF_KEY_NOTIF_COLOR, Color.BLACK)); } else if (key.equals(PREF_KEY_NOTIF_COLOR_MODE)) { intent.setAction(ACTION_NOTIF_BACKGROUND_CHANGED); intent.putExtra(EXTRA_BG_COLOR_MODE, prefs.getString( PREF_KEY_NOTIF_COLOR_MODE, NOTIF_BG_COLOR_MODE_OVERLAY)); } else if (key.equals(PREF_KEY_NOTIF_BACKGROUND_ALPHA)) { intent.setAction(ACTION_NOTIF_BACKGROUND_CHANGED); intent.putExtra(EXTRA_BG_ALPHA, prefs.getInt(PREF_KEY_NOTIF_BACKGROUND_ALPHA, 60)); } else if (key.equals(PREF_KEY_DISABLE_ROAMING_INDICATORS)) { intent.setAction(ACTION_DISABLE_ROAMING_INDICATORS_CHANGED); intent.putExtra(EXTRA_INDICATORS_DISABLED, prefs.getBoolean(PREF_KEY_DISABLE_ROAMING_INDICATORS, false)); } else if (key.equals(PREF_KEY_PIE_CONTROL_ENABLE)) { intent.setAction(ACTION_PREF_PIE_CHANGED); boolean enabled = prefs.getBoolean(PREF_KEY_PIE_CONTROL_ENABLE, false); intent.putExtra(EXTRA_PIE_ENABLE, enabled); if (!enabled) { intent.putExtra(EXTRA_PIE_HWKEYS_DISABLE, false); } } else if (key.equals(PREF_KEY_PIE_CONTROL_SEARCH)) { intent.setAction(ACTION_PREF_PIE_CHANGED); intent.putExtra(EXTRA_PIE_SEARCH, prefs.getBoolean(PREF_KEY_PIE_CONTROL_SEARCH, false)); } else if (key.equals(PREF_KEY_PIE_CONTROL_MENU)) { intent.setAction(ACTION_PREF_PIE_CHANGED); intent.putExtra(EXTRA_PIE_MENU, prefs.getBoolean(PREF_KEY_PIE_CONTROL_MENU, false)); } else if (key.equals(PREF_KEY_PIE_CONTROL_TRIGGERS)) { intent.setAction(ACTION_PREF_PIE_CHANGED); String[] triggers = prefs.getStringSet( PREF_KEY_PIE_CONTROL_TRIGGERS, new HashSet<String>()).toArray(new String[0]); intent.putExtra(EXTRA_PIE_TRIGGERS, triggers); } else if (key.equals(PREF_KEY_PIE_CONTROL_TRIGGER_SIZE)) { intent.setAction(ACTION_PREF_PIE_CHANGED); intent.putExtra(EXTRA_PIE_TRIGGER_SIZE, prefs.getInt(PREF_KEY_PIE_CONTROL_TRIGGER_SIZE, 5)); } else if (key.equals(PREF_KEY_PIE_CONTROL_SIZE)) { intent.setAction(ACTION_PREF_PIE_CHANGED); intent.putExtra(EXTRA_PIE_SIZE, prefs.getInt(PREF_KEY_PIE_CONTROL_SIZE, 1000)); } else if (key.equals(PREF_KEY_HWKEYS_DISABLE)) { intent.setAction(ACTION_PREF_PIE_CHANGED); intent.putExtra(EXTRA_PIE_HWKEYS_DISABLE, prefs.getBoolean(PREF_KEY_HWKEYS_DISABLE, false)); } else if (key.equals(PREF_KEY_BUTTON_BACKLIGHT_MODE)) { intent.setAction(ACTION_PREF_BUTTON_BACKLIGHT_CHANGED); intent.putExtra(EXTRA_BB_MODE, prefs.getString( PREF_KEY_BUTTON_BACKLIGHT_MODE, BB_MODE_DEFAULT)); } else if (key.equals(PREF_KEY_BUTTON_BACKLIGHT_NOTIFICATIONS)) { intent.setAction(ACTION_PREF_BUTTON_BACKLIGHT_CHANGED); intent.putExtra(EXTRA_BB_NOTIF, prefs.getBoolean( PREF_KEY_BUTTON_BACKLIGHT_NOTIFICATIONS, false)); } else if (key.equals(PREF_KEY_QUICKAPP_DEFAULT)) { intent.setAction(ACTION_PREF_QUICKAPP_CHANGED); intent.putExtra(EXTRA_QUICKAPP_DEFAULT, prefs.getString(PREF_KEY_QUICKAPP_DEFAULT, null)); } else if (key.equals(PREF_KEY_QUICKAPP_SLOT1)) { intent.setAction(ACTION_PREF_QUICKAPP_CHANGED); intent.putExtra(EXTRA_QUICKAPP_SLOT1, prefs.getString(PREF_KEY_QUICKAPP_SLOT1, null)); } else if (key.equals(PREF_KEY_QUICKAPP_SLOT2)) { intent.setAction(ACTION_PREF_QUICKAPP_CHANGED); intent.putExtra(EXTRA_QUICKAPP_SLOT2, prefs.getString(PREF_KEY_QUICKAPP_SLOT2, null)); } else if (key.equals(PREF_KEY_QUICKAPP_SLOT3)) { intent.setAction(ACTION_PREF_QUICKAPP_CHANGED); intent.putExtra(EXTRA_QUICKAPP_SLOT3, prefs.getString(PREF_KEY_QUICKAPP_SLOT3, null)); } else if (key.equals(PREF_KEY_QUICKAPP_SLOT4)) { intent.setAction(ACTION_PREF_QUICKAPP_CHANGED); intent.putExtra(EXTRA_QUICKAPP_SLOT4, prefs.getString(PREF_KEY_QUICKAPP_SLOT4, null)); } if (intent.getAction() != null) { getActivity().sendBroadcast(intent); } if (key.equals(PREF_KEY_FIX_CALLER_ID_PHONE) || key.equals(PREF_KEY_FIX_CALLER_ID_MMS)) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.important); int msgId = (key.equals(PREF_KEY_FIX_CALLER_ID_PHONE)) ? R.string.fix_caller_id_phone_alert : R.string.fix_caller_id_mms_alert; builder.setMessage(msgId); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Toast.makeText(getActivity(), getString(R.string.reboot_required), Toast.LENGTH_SHORT).show(); } }); mDialog = builder.create(); mDialog.show(); } if (rebootKeys.contains(key)) Toast.makeText(getActivity(), getString(R.string.reboot_required), Toast.LENGTH_SHORT).show(); } @Override public boolean onPreferenceTreeClick(PreferenceScreen prefScreen, Preference pref) { Intent intent = null; if (pref == mPrefAboutGb) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_gravitybox))); } else if (pref == mPrefAboutXposed) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_xposed))); } else if (pref == mPrefAboutDonate) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_donate))); } else if (pref == mPrefEngMode) { intent = new Intent(Intent.ACTION_MAIN); intent.setClassName(APP_ENGINEERING_MODE, APP_ENGINEERING_MODE_CLASS); } else if (pref == mPrefDualSimRinger) { intent = new Intent(Intent.ACTION_MAIN); intent.setClassName(APP_DUAL_SIM_RINGER, APP_DUAL_SIM_RINGER_CLASS); } else if (pref == mPrefLockscreenBgImage) { setCustomLockscreenImage(); return true; } else if (pref == mPrefNotifImagePortrait) { setCustomNotifBgPortrait(); return true; } else if (pref == mPrefNotifImageLandscape) { setCustomNotifBgLandscape(); return true; } else if (pref == mPrefGbThemeDark) { File file = new File(getActivity().getFilesDir() + "/" + FILE_THEME_DARK_FLAG); if (mPrefGbThemeDark.isChecked()) { if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } else { if (file.exists()) { file.delete(); } } getActivity().recreate(); } if (intent != null) { try { startActivity(intent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } return true; } return super.onPreferenceTreeClick(prefScreen, pref); } private boolean isAppInstalled(String appUri) { PackageManager pm = getActivity().getPackageManager(); try { pm.getPackageInfo(appUri, PackageManager.GET_ACTIVITIES); return true; } catch (Exception e) { return false; } } @SuppressWarnings("deprecation") private void setCustomLockscreenImage() { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
package com.intellij.ui.tree.ui; import com.intellij.ui.RestoreScaleRule; import com.intellij.util.ui.EmptyIcon; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; import java.awt.Graphics; import javax.swing.Icon; import static com.intellij.util.ui.JBUI.setUserScaleFactor; public class TreeControlPainterTest { @ClassRule public static final RestoreScaleRule MANAGE_STATE = new RestoreScaleRule(); @Test public void testClassicDefault() { setUserScaleFactor(1); Control.Painter painter = new ClassicPainter(true, 7, 11, null); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 18, 36, 54, 72, 90, 108); testRendererOffset(painter, even, true, 18, 36, 54, 72, 90, 108); testControlOffset(painter, even, 2, 20, 38, 56, 74, 92); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 18, 36, 54, 72, 90, 108); testRendererOffset(painter, odd, true, 18, 36, 54, 72, 90, 108); testControlOffset(painter, odd, 1, 19, 37, 55, 73, 91); } @Test public void testClassicDefaultLeafIndent() { setUserScaleFactor(1); Control.Painter painter = new ClassicPainter(false, 7, 11, 0); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 18, 36, 54, 72, 90, 108); testRendererOffset(painter, even, true, 0, 18, 36, 54, 72, 90); testControlOffset(painter, even, 2, 20, 38, 56, 74, 92); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 18, 36, 54, 72, 90, 108); testRendererOffset(painter, odd, true, 0, 18, 36, 54, 72, 90); testControlOffset(painter, odd, 1, 19, 37, 55, 73, 91); } @Test public void testClassicCompact() { setUserScaleFactor(1); Control.Painter painter = new ClassicPainter(true, 0, 0, null); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 10, 15, 20, 25, 30, 35); testRendererOffset(painter, even, true, 10, 15, 20, 25, 30, 35); testControlOffset(painter, even, 0, 5, 10, 15, 20, 25); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 11, 17, 23, 29, 35, 41); testRendererOffset(painter, odd, true, 11, 17, 23, 29, 35, 41); testControlOffset(painter, odd, 0, 6, 12, 18, 24, 30); } @Test public void testClassicCompactLeafIndent() { setUserScaleFactor(1); Control.Painter painter = new ClassicPainter(false, 0, 0, 0); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 10, 15, 20, 25, 30, 35); testRendererOffset(painter, even, true, 0, 5, 10, 15, 20, 25); testControlOffset(painter, even, 0, 5, 10, 15, 20, 25); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 11, 17, 23, 29, 35, 41); testRendererOffset(painter, odd, true, 0, 6, 12, 18, 24, 30); testControlOffset(painter, odd, 0, 6, 12, 18, 24, 30); } @Test public void testCompact() { setUserScaleFactor(1); for (int i = 0; i < 4; i++) { Control.Painter painter = new CompactPainter(true, i, i, -1); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 10 + 2 * i, 12 + 3 * i, 14 + 4 * i, 16 + 5 * i, 18 + 6 * i, 20 + 7 * i); testRendererOffset(painter, even, true, 10 + 2 * i, 12 + 3 * i, 14 + 4 * i, 16 + 5 * i, 18 + 6 * i, 20 + 7 * i); testControlOffset(painter, even, i, 2 + 2 * i, 4 + 3 * i, 6 + 4 * i, 8 + 5 * i, 10 + 6 * i); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 11 + 2 * i, 13 + 3 * i, 15 + 4 * i, 17 + 5 * i, 19 + 6 * i, 21 + 7 * i); testRendererOffset(painter, odd, true, 11 + 2 * i, 13 + 3 * i, 15 + 4 * i, 17 + 5 * i, 19 + 6 * i, 21 + 7 * i); testControlOffset(painter, odd, i, 2 + 2 * i, 4 + 3 * i, 6 + 4 * i, 8 + 5 * i, 10 + 6 * i); } } @Test public void testCompactLeafIndent() { setUserScaleFactor(1); for (int i = 0; i < 4; i++) { Control.Painter painter = new CompactPainter(false, i, i, 0); Control even = new TestControl(10, 10); testRendererOffset(painter, even, false, 10 + 2 * i, 12 + 3 * i, 14 + 4 * i, 16 + 5 * i, 18 + 6 * i, 20 + 7 * i); testRendererOffset(painter, even, true, 0, 2 + i, 4 + 2 * i, 6 + 3 * i, 8 + 4 * i, 10 + 5 * i); testControlOffset(painter, even, i, 2 + 2 * i, 4 + 3 * i, 6 + 4 * i, 8 + 5 * i, 10 + 6 * i); Control odd = new TestControl(11, 11); testRendererOffset(painter, odd, false, 11 + 2 * i, 13 + 3 * i, 15 + 4 * i, 17 + 5 * i, 19 + 6 * i, 21 + 7 * i); testRendererOffset(painter, odd, true, 0, 2 + i, 4 + 2 * i, 6 + 3 * i, 8 + 4 * i, 10 + 5 * i); testControlOffset(painter, odd, i, 2 + 2 * i, 4 + 3 * i, 6 + 4 * i, 8 + 5 * i, 10 + 6 * i); } } private static void assertRendererOffset(Control.Painter painter, Control control, int depth, boolean leaf) { Assert.assertTrue("depth=" + depth, painter.getRendererOffset(control, depth, leaf) < 0); } private static void assertRendererOffset(Control.Painter painter, Control control, int depth, boolean leaf, int expected) { Assert.assertEquals("depth=" + depth, expected, painter.getRendererOffset(control, depth, leaf)); } private static void testRendererOffset(Control.Painter painter, Control control, boolean leaf, int... expected) { for (int depth : new int[]{Integer.MIN_VALUE, -1, -10}) { assertRendererOffset(painter, control, depth, leaf); } assertRendererOffset(painter, control, 0, leaf, 0); for (int depth = 0; depth < expected.length; depth++) { assertRendererOffset(painter, control, depth + 1, leaf, expected[depth]); } } private static void assertControlOffset(Control.Painter painter, Control control, int depth, boolean leaf) { Assert.assertTrue("depth=" + depth, painter.getControlOffset(control, depth, leaf) < 0); } private static void assertControlOffset(Control.Painter painter, Control control, int depth, int expected) { Assert.assertEquals("depth=" + depth, expected, painter.getControlOffset(control, depth, false)); } private static void testControlOffset(Control.Painter painter, Control control, int... expected) { for (int depth : new int[]{Integer.MIN_VALUE, -1, -10, 0}) { assertControlOffset(painter, control, depth, true); assertControlOffset(painter, control, depth, false); } for (int depth = 0; depth < expected.length; depth++) { assertControlOffset(painter, control, depth + 1, true); assertControlOffset(painter, control, depth + 1, expected[depth]); } } private static final class TestControl implements Control { private final Icon icon; private TestControl(int width, int height) { icon = EmptyIcon.create(width, height); } @NotNull @Override public Icon getIcon(boolean expanded, boolean selected) { return icon; } @Override public int getWidth() { return icon.getIconWidth(); } @Override public int getHeight() { return icon.getIconHeight(); } @Override public void paint(@NotNull Graphics g, int x, int y, int width, int height, boolean expanded, boolean selected) { } } }