answer
stringlengths
17
10.2M
package org.robovm.bindings.mopub; import org.robovm.cocoatouch.coregraphics.CGRect; import org.robovm.cocoatouch.foundation.NSAutoreleasePool; import org.robovm.cocoatouch.uikit.UIApplication; import org.robovm.cocoatouch.uikit.UIApplicationDelegate; import org.robovm.cocoatouch.uikit.UIColor; import org.robovm.cocoatouch.uikit.UIScreen; import org.robovm.cocoatouch.uikit.UIViewController; import org.robovm.cocoatouch.uikit.UIWindow; /** * Basic usage of banners and interstitials. */ public class Sample extends UIApplicationDelegate.Adapter { private UIViewController interstitialViewController; @Override public void didFinishLaunching(UIApplication application) { // We need a view controller to see ads. interstitialViewController = new UIViewController(); // Create an interstitial. MPInterstitialAdController interstitial = MPInterstitialAdController.getAdController("YOUR_AD_UNIT_ID"); // The delegate for an interstitial is optional. MPInterstitialAdControllerDelegate delegate = new MPInterstitialAdControllerDelegate.Adapter() { @Override public void didDisappear(MPInterstitialAdController interstitial) { interstitial.loadAd(); } @Override public void didExpire(MPInterstitialAdController interstitial) { // If the ad did expire, load a new ad. interstitial.loadAd(); } @Override public void didLoadAd(MPInterstitialAdController interstitial) { // If the ad is ready, show it. // It's best to call these methods manually and not in didLoadAd(). if (interstitial.isReady()) interstitial.show(interstitialViewController); } @Override public void didFailToLoadAd(MPInterstitialAdController interstitial) { // If the ad did fail to load, load a new ad. Check the debug log to see why it didn't load. interstitial.loadAd(); } }; interstitial.setDelegate(delegate); // Load an interstitial ad. interstitial.loadAd(); // Create a MoPub ad. In this case a banner, but you can make it any size you want. MPAdView banner = new MPAdView("YOUR_AD_UNIT_ID", MPConstants.MOPUB_BANNER_SIZE); // Let's calculate our banner size. We need to do this because the resolution of a retina and normal device is different. float bannerWidth = UIScreen.getMainScreen().getApplicationFrame().size().width(); float bannerHeight = bannerWidth / MPConstants.MOPUB_BANNER_SIZE.width() * MPConstants.MOPUB_BANNER_SIZE.height(); // Let's set the frame (boundings) of our banner view. Remember on iOS view coordinates have their origin top-left. // Position banner on the top. // banner.setFrame(new CGRect(0, 0, bannerWidth, bannerHeight)); // Position banner on the bottom. banner.setFrame(new CGRect(0, UIScreen.getMainScreen().getApplicationFrame().size().height() - bannerHeight, bannerWidth, bannerHeight)); // Let's color the background for testing, so we can see if it is positioned correctly, even if no ad is loaded yet. banner.setBackgroundColor(new UIColor(1, 0, 0, 1)); // Remove this after testing. // The delegate for the banner. It is required to override getViewController() to get ads. MPAdViewDelegate bannerDelegate = new MPAdViewDelegate.Adapter() { @Override public UIViewController getViewController() { return interstitialViewController; } }; banner.setDelegate(bannerDelegate); // Add banner to our view controller. interstitialViewController.getView().addSubview(banner); // Finally load a banner ad. This ad gets refreshed automatically, although you can refresh it at any time via refreshAd(). banner.loadAd(); // Create a standard UIWindow at screen size, add the view controller and show it. UIWindow window = new UIWindow(UIScreen.getMainScreen().getBounds()); window.setRootViewController(interstitialViewController); window.makeKeyAndVisible(); // If you are already using a UIWindow, you can do the following (f.e. LibGDX): // UIView interstitialView = new UIView(UIScreen.getMainScreen().getBounds()); // interstitialView.setUserInteractionEnabled(false); // interstitialViewController.setView(interstitialView); // application.getKeyWindow().addSubview(interstitialViewController.getView()); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, Sample.class); pool.drain(); } }
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package cc.arduino.packages.uploaders; import cc.arduino.packages.Uploader; import processing.app.*; import processing.app.debug.RunnerException; import processing.app.debug.TargetPlatform; import processing.app.helpers.PreferencesMap; import processing.app.helpers.StringReplacer; import java.io.File; import java.util.ArrayList; import java.util.List; import static processing.app.I18n._; public class SerialUploader extends Uploader { public boolean uploadUsingPreferences(File sourcePath, String buildPath, String className, boolean usingProgrammer, List<String> warningsAccumulator) throws Exception { // FIXME: Preferences should be reorganized TargetPlatform targetPlatform = Base.getTargetPlatform(); PreferencesMap prefs = Preferences.getMap(); prefs.putAll(Base.getBoardPreferences()); String tool = prefs.getOrExcept("upload.tool"); if (tool.contains(":")) { String[] split = tool.split(":", 2); targetPlatform = Base.getCurrentTargetPlatformFromPackage(split[0]); tool = split[1]; } prefs.putAll(targetPlatform.getTool(tool)); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || prefs.get("upload.protocol") == null) { return uploadUsingProgrammer(buildPath, className); } // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. String t = prefs.get("upload.use_1200bps_touch"); boolean doTouch = t != null && t.equals("true"); t = prefs.get("upload.wait_for_upload_port"); boolean waitForUploadPort = (t != null) && t.equals("true"); if (doTouch) { String uploadPort = prefs.getOrExcept("serial.port"); try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose) System.out.println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); } if (waitForUploadPort) { // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. Thread.sleep(300); uploadPort = waitForUploadPort(uploadPort, before); } else { Thread.sleep(400); } } catch (SerialException e) { throw new RunnerException(e); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } prefs.put("serial.port", uploadPort); if (uploadPort.startsWith("/dev/")) prefs.put("serial.port.file", uploadPort.substring(5)); else prefs.put("serial.port.file", uploadPort); } prefs.put("build.path", buildPath); prefs.put("build.project_name", className); if (verbose) prefs.put("upload.verbose", prefs.getOrExcept("upload.params.verbose")); else prefs.put("upload.verbose", prefs.getOrExcept("upload.params.quiet")); boolean uploadResult; try { // if (prefs.get("upload.disable_flushing") == null // || prefs.get("upload.disable_flushing").toLowerCase().equals("false")) { // flushSerialBuffer(); String pattern = prefs.getOrExcept("upload.pattern"); String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true); uploadResult = executeUploadCommand(cmd); } catch (Exception e) { throw new RunnerException(e); } // Remove the magic baud rate (1200bps) to avoid // future unwanted board resets try { if (uploadResult && doTouch) { String uploadPort = Preferences.get("serial.port"); if (waitForUploadPort) { // For Due/Leonardo wait until the bootloader serial port disconnects and the // sketch serial port reconnects (or timeout after a few seconds if the // sketch port never comes back). Doing this saves users from accidentally // opening Serial Monitor on the soon-to-be-orphaned bootloader port. Thread.sleep(1000); long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); if (portList.contains(uploadPort)) { try { Serial.touchPort(uploadPort, 9600); break; } catch (SerialException e) { // Port already in use } } Thread.sleep(250); } } else { try { Serial.touchPort(uploadPort, 9600); } catch (SerialException e) { throw new RunnerException(e); } } } } catch (InterruptedException ex) { // noop } return uploadResult; } private String waitForUploadPort(String uploadPort, List<String> before) throws InterruptedException, RunnerException { // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose) { System.out.print("PORTS {"); for (String p : before) System.out.print(p + ", "); System.out.print("} / {"); for (String p : now) System.out.print(p + ", "); System.out.print("} => {"); for (String p : diff) System.out.print(p + ", "); System.out.println("}"); } if (diff.size() > 0) { String newPort = diff.get(0); if (verbose) System.out.println("Found upload port: " + newPort); return newPort; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the // selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose) System.out.println("Uploading using selected port: " + uploadPort); return uploadPort; } } // Something happened while detecting port throw new RunnerException(_("Couldn't find a Board on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); } public boolean uploadUsingProgrammer(String buildPath, String className) throws Exception { TargetPlatform targetPlatform = Base.getTargetPlatform(); String programmer = Preferences.get("programmer"); if (programmer.contains(":")) { String[] split = programmer.split(":", 2); targetPlatform = Base.getCurrentTargetPlatformFromPackage(split[0]); programmer = split[1]; } PreferencesMap prefs = Preferences.getMap(); prefs.putAll(Base.getBoardPreferences()); prefs.putAll(targetPlatform.getProgrammer(programmer)); prefs.putAll(targetPlatform.getTool(prefs.getOrExcept("program.tool"))); prefs.put("build.path", buildPath); prefs.put("build.project_name", className); if (verbose) prefs.put("program.verbose", prefs.getOrExcept("program.params.verbose")); else prefs.put("program.verbose", prefs.getOrExcept("program.params.quiet")); try { // if (prefs.get("program.disable_flushing") == null // || prefs.get("program.disable_flushing").toLowerCase().equals("false")) // flushSerialBuffer(); String pattern = prefs.getOrExcept("program.pattern"); String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true); return executeUploadCommand(cmd); } catch (Exception e) { throw new RunnerException(e); } } public boolean burnBootloader() throws Exception { TargetPlatform targetPlatform = Base.getTargetPlatform(); // Find preferences for the selected programmer PreferencesMap programmerPrefs; String programmer = Preferences.get("programmer"); if (programmer.contains(":")) { String[] split = programmer.split(":", 2); TargetPlatform platform = Base.getCurrentTargetPlatformFromPackage(split[0]); programmer = split[1]; programmerPrefs = platform.getProgrammer(programmer); } else { programmerPrefs = targetPlatform.getProgrammer(programmer); } // Build configuration for the current programmer PreferencesMap prefs = Preferences.getMap(); prefs.putAll(Base.getBoardPreferences()); prefs.putAll(programmerPrefs); // Create configuration for bootloader tool PreferencesMap toolPrefs = new PreferencesMap(); String tool = prefs.getOrExcept("bootloader.tool"); if (tool.contains(":")) { String[] split = tool.split(":", 2); TargetPlatform platform = Base.getCurrentTargetPlatformFromPackage(split[0]); tool = split[1]; toolPrefs.putAll(platform.getTool(tool)); if (toolPrefs.size() == 0) throw new RunnerException(I18n.format(_("Could not find tool {0} from package {1}"), tool, split[0])); } toolPrefs.putAll(targetPlatform.getTool(tool)); if (toolPrefs.size() == 0) throw new RunnerException(I18n.format(_("Could not find tool {0}"), tool)); // Merge tool with global configuration prefs.putAll(toolPrefs); if (verbose) { prefs.put("erase.verbose", prefs.getOrExcept("erase.params.verbose")); prefs.put("bootloader.verbose", prefs.getOrExcept("bootloader.params.verbose")); } else { prefs.put("erase.verbose", prefs.getOrExcept("erase.params.quiet")); prefs.put("bootloader.verbose", prefs.getOrExcept("bootloader.params.quiet")); } try { String pattern = prefs.getOrExcept("erase.pattern"); String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true); if (!executeUploadCommand(cmd)) return false; pattern = prefs.getOrExcept("bootloader.pattern"); cmd = StringReplacer.formatAndSplit(pattern, prefs, true); return executeUploadCommand(cmd); } catch (Exception e) { throw new RunnerException(e); } } }
package tech.pinto.tests; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import tech.pinto.Pinto; import tech.pinto.TimeSeries; import tech.pinto.time.PeriodicRange; import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.DoubleStream; public class IndexTester { @SuppressWarnings("unused") private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass()); private static Pinto pinto; @BeforeClass public static void setup() { pinto = AllTests.component.pinto(); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testWildcards() throws Exception { List<TimeSeries> ts = pinto.execute("1 2 3 label(hotdiggitydog,burger,hotdog) [hot*dog] eval").get(0).getTimeSeries().get(); assertEquals("wildcard label", 2, ts.size()); } /*@Test public void testReverse() throws Exception { List<TimeSeries> ts = pinto.execute("1 2 3 rev [~] label(c,b,a) eval").get(0).getTimeSeries().get(); assertEquals("reverse index (simple) label", ts.get(2).getLabel(),"a"); assertEquals("reverse index (simple) value", ts.get(2).stream().toArray()[0],1.0,0.1); ts = pinto.execute("1 2 3 rev [~0:2] label(b,a) eval").get(0).getTimeSeries().get(); assertEquals("reverse index (with number index)", "a", ts.get(1).getLabel()); }*/ @Test public void testNumbers() throws Exception { List<TimeSeries> ts = pinto.execute("1 2 3 [0] eval").get(0).getTimeSeries().get(); assertEquals("number index (simple) value", 3.0, ts.get(0).stream().toArray()[0],0.1); ts = pinto.execute("1 2 3 [-1] eval").get(0).getTimeSeries().get(); assertEquals("number index (neg) value",1.0, ts.get(0).stream().toArray()[0],0.1); ts = pinto.execute("1 2 3 [1:2] eval").get(0).getTimeSeries().get(); assertEquals("number index (range) value",2.0, ts.get(0).stream().toArray()[0],0.1); ts = pinto.execute("1 2 3 [-3:-1] eval").get(0).getTimeSeries().get(); assertEquals("number index (range w/ neg) value",2.0, ts.get(1).stream().toArray()[0],0.1); ts = pinto.execute("1 2 3 [2,1,0] eval").get(0).getTimeSeries().get(); assertEquals("number index (list) value", 2.0, ts.get(1).stream().toArray()[0],0.1); /*ts = pinto.execute("1 2 3 rev [~] label(a,b,c) [1,1] neg eval").get(0).getTimeSeries().get(); double sum = ts.stream().map(TimeSeries::stream).map(DoubleStream::toArray).mapToDouble(a -> a[0]).sum(); assertEquals("number index (list) value", 0.0, sum, 0.1);*/ } @Test public void testLabels() throws Exception { List<TimeSeries> ts = pinto.execute("1 2 3 label(a,b,c) [c] eval").get(0).getTimeSeries().get(); assertEquals("label index (simple) value", 3.0, ts.get(0).stream().toArray()[0], 0.1); ts = pinto.execute("1 2 3 label(a,b,c) [b,b] neg eval").get(0).getTimeSeries().get(); double sum = ts.stream().map(TimeSeries::stream).map(DoubleStream::toArray).mapToDouble(a -> a[0]).sum(); assertEquals("label index (get one twice) value", sum,0.0,0.1); ts = pinto.execute("1 2 3 label(b,b,a) [b] neg eval").get(0).getTimeSeries().get(); sum = ts.stream().map(TimeSeries::stream).map(DoubleStream::toArray).mapToDouble(a -> a[0]).sum(); assertEquals("label index (repeated label) value", sum,0.0,0.1); } @SuppressWarnings("unused") private double[][] run(String line) throws Exception { List<TimeSeries> dd = pinto.execute(line).get(0).getTimeSeries().get(); if(dd.size() > 0) { PeriodicRange<?> range = dd.get(0).getRange(); double[][] table = new double[dd.size()][(int) range.size()]; for(AtomicInteger i = new AtomicInteger(0); i.get() < dd.size();i.incrementAndGet()) { AtomicInteger j = new AtomicInteger(0); dd.get(i.get()).stream().forEach( d -> table[i.get()][j.getAndIncrement()] = d); } return table; } else { return null; } } }
package org.eigenbase.sql; import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.*; /** * <code>SqlDialect</code> encapsulates the differences between dialects of SQL. * * <p>It is used by classes such as {@link SqlWriter} and * {@link org.eigenbase.sql.util.SqlBuilder}. */ public class SqlDialect { /** * A dialect useful for generating generic SQL. If you need to do something * database-specific like quoting identifiers, don't rely on this dialect to * do what you want. */ public static SqlDialect DUMMY; /** * A dialect useful for generating SQL which can be parsed by the * Eigenbase parser, in particular quoting literals and identifiers. If you * want a dialect that knows the full capabilities of the database, create * one from a connection. */ public static SqlDialect EIGENBASE; private final String databaseProductName; private final String identifierQuoteString; private final String identifierEndQuoteString; private final String identifierEscapedQuote; private final DatabaseProduct databaseProduct; /** * Creates a <code>SqlDialect</code> from a DatabaseMetaData. * * <p>Does not maintain a reference to the DatabaseMetaData -- or, more * importantly, to its {@link java.sql.Connection} -- after this call has * returned. * * @param databaseMetaData used to determine which dialect of SQL to * generate */ public static SqlDialect create(DatabaseMetaData databaseMetaData) { String identifierQuoteString; try { identifierQuoteString = databaseMetaData.getIdentifierQuoteString(); } catch (SQLException e) { throw FakeUtil.newInternal(e, "while quoting identifier"); } String databaseProductName; try { databaseProductName = databaseMetaData.getDatabaseProductName(); } catch (SQLException e) { throw FakeUtil.newInternal(e, "while detecting database product"); } final DatabaseProduct databaseProduct = getProduct(databaseProductName, null); return new SqlDialect( databaseProduct, databaseProductName, identifierQuoteString); } /** * Creates a SqlDialect. * * @param databaseProduct Database product; may be UNKNOWN, never null * @param databaseProductName Database product name from JDBC driver * @param identifierQuoteString String to quote identifiers. Null if quoting * is not supported. If "[", close quote is deemed to be "]". */ public SqlDialect( DatabaseProduct databaseProduct, String databaseProductName, String identifierQuoteString) { assert databaseProduct != null; assert databaseProductName != null; this.databaseProduct = databaseProduct; this.databaseProductName = databaseProductName; if (identifierQuoteString != null) { identifierQuoteString = identifierQuoteString.trim(); if (identifierQuoteString.equals("")) { identifierQuoteString = null; } } this.identifierQuoteString = identifierQuoteString; this.identifierEndQuoteString = identifierQuoteString == null ? null : identifierQuoteString.equals("[") ? "]" : identifierQuoteString; this.identifierEscapedQuote = identifierQuoteString == null ? null : this.identifierEndQuoteString + this.identifierEndQuoteString; } /** * Converts a product name and version (per the JDBC driver) into a product * enumeration. * * @param productName Product name * @param productVersion Product version * @return database product */ public static DatabaseProduct getProduct( String productName, String productVersion) { final String upperProductName = productName.toUpperCase(); if (productName.equals("ACCESS")) { return DatabaseProduct.ACCESS; } else if (upperProductName.trim().equals("APACHE DERBY")) { return DatabaseProduct.DERBY; } else if (upperProductName.trim().equals("DBMS:CLOUDSCAPE")) { return DatabaseProduct.DERBY; } else if (productName.startsWith("DB2")) { return DatabaseProduct.DB2; } else if (upperProductName.indexOf("FIREBIRD") >= 0) { return DatabaseProduct.FIREBIRD; } else if (productName.startsWith("Informix")) { return DatabaseProduct.INFORMIX; } else if (upperProductName.equals("INGRES")) { return DatabaseProduct.INGRES; } else if (productName.equals("Interbase")) { return DatabaseProduct.INTERBASE; } else if (upperProductName.equals("LUCIDDB")) { return DatabaseProduct.LUCIDDB; } else if (upperProductName.indexOf("SQL SERVER") >= 0) { return DatabaseProduct.MSSQL; } else if (productName.equals("Oracle")) { return DatabaseProduct.ORACLE; } else if (upperProductName.indexOf("POSTGRE") >= 0) { return DatabaseProduct.POSTGRESQL; } else if (upperProductName.indexOf("NETEZZA") >= 0) { return DatabaseProduct.NETEZZA; } else if (upperProductName.equals("MYSQL (INFOBRIGHT)")) { return DatabaseProduct.INFOBRIGHT; } else if (upperProductName.equals("MYSQL")) { return DatabaseProduct.MYSQL; } else if (productName.startsWith("HP Neoview")) { return DatabaseProduct.NEOVIEW; } else if (upperProductName.indexOf("SYBASE") >= 0) { return DatabaseProduct.SYBASE; } else if (upperProductName.indexOf("TERADATA") >= 0) { return DatabaseProduct.TERADATA; } else if (upperProductName.indexOf("HSQL") >= 0) { return DatabaseProduct.HSQLDB; } else if (upperProductName.indexOf("VERTICA") >= 0) { return DatabaseProduct.VERTICA; } else { return DatabaseProduct.UNKNOWN; } } // -- detect various databases -- /** * Encloses an identifier in quotation marks appropriate for the current SQL * dialect. * * <p>For example, <code>quoteIdentifier("emp")</code> yields a string * containing <code>"emp"</code> in Oracle, and a string containing <code> * [emp]</code> in Access. * * @param val Identifier to quote * * @return Quoted identifier */ public String quoteIdentifier(String val) { if (identifierQuoteString == null) { return val; // quoting is not supported } String val2 = val.replaceAll( identifierEndQuoteString, identifierEscapedQuote); return identifierQuoteString + val2 + identifierEndQuoteString; } /** * Encloses an identifier in quotation marks appropriate for the current SQL * dialect, writing the result to a {@link StringBuilder}. * * <p>For example, <code>quoteIdentifier("emp")</code> yields a string * containing <code>"emp"</code> in Oracle, and a string containing <code> * [emp]</code> in Access. * * @param buf Buffer * @param val Identifier to quote * * @return The buffer */ public StringBuilder quoteIdentifier( StringBuilder buf, String val) { if (identifierQuoteString == null) { buf.append(val); // quoting is not supported return buf; } String val2 = val.replaceAll( identifierEndQuoteString, identifierEscapedQuote); buf.append(identifierQuoteString); buf.append(val2); buf.append(identifierEndQuoteString); return buf; } /** * Quotes a multi-part identifier. * * @param buf Buffer * @param identifiers List of parts of the identifier to quote * * @return The buffer */ public StringBuilder quoteIdentifier( StringBuilder buf, List<String> identifiers) { int i = 0; for (String identifier : identifiers) { if (i++ > 0) { buf.append('.'); } quoteIdentifier(buf, identifier); } return buf; } /** * Returns whether a given identifier needs to be quoted. */ public boolean identifierNeedsToBeQuoted(String val) { return !Pattern.compile("^[A-Z_$0-9]+").matcher(val).matches(); } /** * Converts a string into a string literal. For example, <code>can't * run</code> becomes <code>'can''t run'</code>. */ public String quoteStringLiteral(String val) { val = FakeUtil.replace(val, "'", "''"); return "'" + val + "'"; } /** * Converts a string literal back into a string. For example, <code>'can''t * run'</code> becomes <code>can't run</code>. */ public String unquoteStringLiteral(String val) { if ((val != null) && (val.charAt(0) == '\'') && (val.charAt(val.length() - 1) == '\'')) { if (val.length() > 2) { val = FakeUtil.replace(val, "''", "'"); return val.substring(1, val.length() - 1); } else { // zero length string return ""; } } return val; } protected boolean allowsAs() { return !(databaseProduct == DatabaseProduct.ORACLE); } // -- behaviors -- protected boolean requiresAliasForFromItems() { return getDatabaseProduct() == DatabaseProduct.POSTGRESQL; } /** * Converts a timestamp to a SQL timestamp literal, e.g. * {@code TIMESTAMP '2009-12-17 12:34:56'}. * * <p>Timestamp values do not have a time zone. We therefore interpret them * as the number of milliseconds after the UTC epoch, and the formatted * value is that time in UTC. * * <p>In particular, * * <blockquote><code>quoteTimestampLiteral(new Timestamp(0));</code> * </blockquote> * * returns {@code TIMESTAMP '1970-01-01 00:00:00'}, regardless of the JVM's * timezone. * * @param timestamp Timestamp * @return SQL timestamp literal */ public String quoteTimestampLiteral(Timestamp timestamp) { final SimpleDateFormat format = new SimpleDateFormat( "'TIMESTAMP' ''yyyy-MM-DD HH:mm:SS''"); format.setTimeZone(TimeZone.getTimeZone("GMT")); return format.format(timestamp); } /** * Returns the database this dialect belongs to, * {@link SqlDialect.DatabaseProduct#UNKNOWN} if not known, never null. * * @return Database product */ public DatabaseProduct getDatabaseProduct() { return databaseProduct; } /** * A few utility functions copied from org.eigenbase.util.Util. We have * copied them because we wish to keep SqlDialect's dependencies to a * minimum. */ public static class FakeUtil { public static Error newInternal(Throwable e, String s) { String message = "Internal error: " + s; AssertionError ae = new AssertionError(message); ae.initCause(e); return ae; } /** * Replaces every occurrence of <code>find</code> in <code>s</code> with * <code>replace</code>. */ public static final String replace( String s, String find, String replace) { // let's be optimistic int found = s.indexOf(find); if (found == -1) { return s; } StringBuilder sb = new StringBuilder(s.length()); int start = 0; for (;;) { for (; start < found; start++) { sb.append(s.charAt(start)); } if (found == s.length()) { break; } sb.append(replace); start += find.length(); found = s.indexOf(find, start); if (found == -1) { found = s.length(); } } return sb.toString(); } } /** * Rough list of flavors of database. * * <p>These values cannot help you distinguish between features that exist * in different versions or ports of a database, but they are sufficient * to drive a {@code switch} statement if behavior is broadly different * between say, MySQL and Oracle. * * <p>If possible, you should not refer to particular database at all; write * extend the dialect to describe the particular capability, for example, * whether the database allows expressions to appear in the GROUP BY clause. */ public enum DatabaseProduct { ACCESS("Access", "\""), MSSQL("Microsoft SQL Server", "["), MYSQL("MySQL", "`"), ORACLE("Oracle", "\""), DERBY("Apache Derby", null), DB2("IBM DB2", null), FIREBIRD("Firebird", null), INFORMIX("Informix", null), INGRES("Ingres", null), LUCIDDB("LucidDB", "\""), INTERBASE("Interbase", null), POSTGRESQL("PostgreSQL", "\""), NETEZZA("Netezza", "\""), INFOBRIGHT("Infobright", "`"), NEOVIEW("Neoview", null), SYBASE("Sybase", null), TERADATA("Teradata", "\""), HSQLDB("Hsqldb", null), VERTICA("Vertica", "\""), SQLSTREAM("SQLstream", "\""), /** * Placeholder for the unknown database. * * <p>Its dialect is useful for generating generic SQL. If you need to * do something database-specific like quoting identifiers, don't rely * on this dialect to do what you want. */ UNKNOWN("Unknown", "`"); private final SqlDialect dialect; DatabaseProduct(String databaseProductName, String quoteString) { dialect = new SqlDialect(this, databaseProductName, quoteString); if ("Unknown".equals(databaseProductName)) { DUMMY = dialect; } else if ("LucidDB".equals(databaseProductName)) { EIGENBASE = dialect; } } /** * Returns a dummy dialect for this database. * * <p>Since databases have many versions and flavors, this dummy dialect * is at best an approximation. If you want exact information, better to * use a dialect created from an actual connection's metadata * (see {@link SqlDialect#create(java.sql.DatabaseMetaData)}). * * @return Dialect representing lowest-common-demoninator behavior for * all versions of this database */ public SqlDialect getDialect() { return dialect; } } } // End SqlDialect.java
package com.ecaresoft.cumulus; import android.content.res.ColorStateList; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.os.Bundle; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.ecaresoft.cumulus.fragments.FAllergy; import com.ecaresoft.cumulus.fragments.FAppointment; import com.ecaresoft.cumulus.fragments.FClinicHistory; import com.ecaresoft.cumulus.fragments.FDiagnostic; import com.ecaresoft.cumulus.fragments.FHome; import com.ecaresoft.cumulus.fragments.FHomeMeds; import com.ecaresoft.cumulus.fragments.FPrescription; import com.ecaresoft.cumulus.helpers.database.DataBaseHelper; import com.ecaresoft.cumulus.models.MEMR; public class MainActivity extends AppCompatActivity { //Defining Variables private Toolbar toolbar; private NavigationView navigationView; private DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int[][] states = new int[][]{ new int[]{android.R.attr.state_checked}, new int[]{-android.R.attr.state_checked}, }; int[] colors = new int[]{ Color.rgb(0, 164, 147), Color.rgb(112, 121, 122) }; ColorStateList colorStateList = new ColorStateList(states, colors); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); drawerLayout = (DrawerLayout) findViewById(R.id.drawer); MEMR emr = new MEMR(getApplicationContext(), DataBaseHelper.getSession(getApplicationContext())); emr.updtate(); // Initializing Toolbar and setting it as the actionbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view); navigationView.setItemTextColor(colorStateList); navigationView.setItemIconTintList(colorStateList); //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not make it in checked state if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); //Closing drawer on item click drawerLayout.closeDrawers(); android.support.v4.app.Fragment fragment = null; //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment Which is our Inbox View; case R.id.home: fragment = new FHome(); break;//return true; case R.id.citas: fragment = new FAppointment(); break;//return true; case R.id.recetas: fragment = new FPrescription(); break;//return true; case R.id.historia: fragment = new FClinicHistory(); break;//return true; case R.id.alergias: fragment = new FAllergy(); break;//return true; case R.id.diagnos: fragment = new FDiagnostic(); break;//return true; case R.id.medica: fragment = new FHomeMeds(); break;//return true; } android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame, fragment); fragmentTransaction.commit(); return true; } }); // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawer); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawerLayout.setDrawerListener(actionBarDrawerToggle); //calling sync state is necessay or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); } @Override public boolean onCreateOptionsMenu (Menu menu){ // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, 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 if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.artifex.mupdfdemo; import java.util.LinkedList; import java.util.NoSuchElementException; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.util.AttributeSet; import android.util.SparseArray; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.Scroller; public class ReaderView extends AdapterView<Adapter> implements GestureDetector.OnGestureListener, ScaleGestureDetector.OnScaleGestureListener, Runnable { private static final int MOVING_DIAGONALLY = 0; private static final int MOVING_LEFT = 1; private static final int MOVING_RIGHT = 2; private static final int MOVING_UP = 3; private static final int MOVING_DOWN = 4; private static final int FLING_MARGIN = 100; private static final int GAP = 20; private static final float MIN_SCALE = 1.0f; private static final float MAX_SCALE = 5.0f; private static final float REFLOW_SCALE_FACTOR = 0.5f; private Adapter mAdapter; private int mCurrent; // Adapter's index for the current view private boolean mResetLayout; private final SparseArray<View> mChildViews = new SparseArray<View>(3); // Shadows the children of the adapter view // but with more sensible indexing private final LinkedList<View> mViewCache = new LinkedList<View>(); private boolean mUserInteracting; // Whether the user is interacting private boolean mScaling; // Whether the user is currently pinch zooming private float mScale = 1.0f; private int mXScroll; // Scroll amounts recorded from events. private int mYScroll; // and then accounted for in onLayout private boolean mReflow = false; private final GestureDetector mGestureDetector; private final ScaleGestureDetector mScaleGestureDetector; private final Scroller mScroller; private int mScrollerLastX; private int mScrollerLastY; static abstract class ViewMapper { abstract void applyToView(View view); } public ReaderView(Context context) { super(context); mGestureDetector = new GestureDetector(this); mScaleGestureDetector = new ScaleGestureDetector(context, this); mScroller = new Scroller(context); } public ReaderView(Context context, AttributeSet attrs) { super(context, attrs); mGestureDetector = new GestureDetector(this); mScaleGestureDetector = new ScaleGestureDetector(context, this); mScroller = new Scroller(context); } public ReaderView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mGestureDetector = new GestureDetector(this); mScaleGestureDetector = new ScaleGestureDetector(context, this); mScroller = new Scroller(context); } public int getDisplayedViewIndex() { return mCurrent; } public void setDisplayedViewIndex(int i) { if (0 <= i && i < mAdapter.getCount()) { onMoveOffChild(mCurrent); mCurrent = i; onMoveToChild(i); mResetLayout = true; requestLayout(); } } public void moveToNext() { View v = mChildViews.get(mCurrent+1); if (v != null) slideViewOntoScreen(v); } public void moveToPrevious() { View v = mChildViews.get(mCurrent-1); if (v != null) slideViewOntoScreen(v); } // When advancing down the page, we want to advance by about // 90% of a screenful. But we'd be happy to advance by between // 80% and 95% if it means we hit the bottom in a whole number // of steps. private int smartAdvanceAmount(int screenHeight, int max) { int advance = (int)(screenHeight * 0.9 + 0.5); int leftOver = max % advance; int steps = max / advance; if (leftOver == 0) { // We'll make it exactly. No adjustment } else if ((float)leftOver / steps <= screenHeight * 0.05) { // We can adjust up by less than 5% to make it exact. advance += (int)((float)leftOver/steps + 0.5); } else { int overshoot = advance - leftOver; if ((float)overshoot / steps <= screenHeight * 0.1) { // We can adjust down by less than 10% to make it exact. advance -= (int)((float)overshoot/steps + 0.5); } } if (advance > max) advance = max; return advance; } public void smartMoveForwards() { View v = mChildViews.get(mCurrent); if (v == null) return; // The following code works in terms of where the screen is on the views; // so for example, if the currentView is at (-100,-100), the visible // region would be at (100,100). If the previous page was (2000, 3000) in // size, the visible region of the previous page might be (2100 + GAP, 100) // (i.e. off the previous page). This is different to the way the rest of // the code in this file is written, but it's easier for me to think about. // At some point we may refactor this to fit better with the rest of the // code. // screenWidth/Height are the actual width/height of the screen. e.g. 480/800 int screenWidth = getWidth(); int screenHeight = getHeight(); // We might be mid scroll; we want to calculate where we scroll to based on // where this scroll would end, not where we are now (to allow for people // bashing 'forwards' very fast. int remainingX = mScroller.getFinalX() - mScroller.getCurrX(); int remainingY = mScroller.getFinalY() - mScroller.getCurrY(); // right/bottom is in terms of pixels within the scaled document; e.g. 1000 int top = -(v.getTop() + mYScroll + remainingY); int right = screenWidth -(v.getLeft() + mXScroll + remainingX); int bottom = screenHeight+top; // docWidth/Height are the width/height of the scaled document e.g. 2000x3000 int docWidth = v.getMeasuredWidth(); int docHeight = v.getMeasuredHeight(); int xOffset, yOffset; if (bottom >= docHeight) { // We are flush with the bottom. Advance to next column. if (right + screenWidth > docWidth) { // No room for another column - go to next page View nv = mChildViews.get(mCurrent+1); if (nv == null) // No page to advance to return; int nextTop = -(nv.getTop() + mYScroll + remainingY); int nextLeft = -(nv.getLeft() + mXScroll + remainingX); int nextDocWidth = nv.getMeasuredWidth(); int nextDocHeight = nv.getMeasuredHeight(); // Allow for the next page maybe being shorter than the screen is high yOffset = (nextDocHeight < screenHeight ? ((nextDocHeight - screenHeight)>>1) : 0); if (nextDocWidth < screenWidth) { // Next page is too narrow to fill the screen. Scroll to the top, centred. xOffset = (nextDocWidth - screenWidth)>>1; } else { // Reset X back to the left hand column xOffset = right % screenWidth; // Adjust in case the previous page is less wide if (xOffset + screenWidth > nextDocWidth) xOffset = nextDocWidth - screenWidth; } xOffset -= nextLeft; yOffset -= nextTop; } else { // Move to top of next column xOffset = screenWidth; yOffset = screenHeight - bottom; } } else { // Advance by 90% of the screen height downwards (in case lines are partially cut off) xOffset = 0; yOffset = smartAdvanceAmount(screenHeight, docHeight - bottom); } mScrollerLastX = mScrollerLastY = 0; mScroller.startScroll(0, 0, remainingX - xOffset, remainingY - yOffset, 400); post(this); } public void smartMoveBackwards() { View v = mChildViews.get(mCurrent); if (v == null) return; // The following code works in terms of where the screen is on the views; // so for example, if the currentView is at (-100,-100), the visible // region would be at (100,100). If the previous page was (2000, 3000) in // size, the visible region of the previous page might be (2100 + GAP, 100) // (i.e. off the previous page). This is different to the way the rest of // the code in this file is written, but it's easier for me to think about. // At some point we may refactor this to fit better with the rest of the // code. // screenWidth/Height are the actual width/height of the screen. e.g. 480/800 int screenWidth = getWidth(); int screenHeight = getHeight(); // We might be mid scroll; we want to calculate where we scroll to based on // where this scroll would end, not where we are now (to allow for people // bashing 'forwards' very fast. int remainingX = mScroller.getFinalX() - mScroller.getCurrX(); int remainingY = mScroller.getFinalY() - mScroller.getCurrY(); // left/top is in terms of pixels within the scaled document; e.g. 1000 int left = -(v.getLeft() + mXScroll + remainingX); int top = -(v.getTop() + mYScroll + remainingY); // docWidth/Height are the width/height of the scaled document e.g. 2000x3000 int docHeight = v.getMeasuredHeight(); int xOffset, yOffset; if (top <= 0) { // We are flush with the top. Step back to previous column. if (left < screenWidth) { /* No room for previous column - go to previous page */ View pv = mChildViews.get(mCurrent-1); if (pv == null) /* No page to advance to */ return; int prevDocWidth = pv.getMeasuredWidth(); int prevDocHeight = pv.getMeasuredHeight(); // Allow for the next page maybe being shorter than the screen is high yOffset = (prevDocHeight < screenHeight ? ((prevDocHeight - screenHeight)>>1) : 0); int prevLeft = -(pv.getLeft() + mXScroll); int prevTop = -(pv.getTop() + mYScroll); if (prevDocWidth < screenWidth) { // Previous page is too narrow to fill the screen. Scroll to the bottom, centred. xOffset = (prevDocWidth - screenWidth)>>1; } else { // Reset X back to the right hand column xOffset = (left > 0 ? left % screenWidth : 0); if (xOffset + screenWidth > prevDocWidth) xOffset = prevDocWidth - screenWidth; while (xOffset + screenWidth*2 < prevDocWidth) xOffset += screenWidth; } xOffset -= prevLeft; yOffset -= prevTop-prevDocHeight+screenHeight; } else { // Move to bottom of previous column xOffset = -screenWidth; yOffset = docHeight - screenHeight + top; } } else { // Retreat by 90% of the screen height downwards (in case lines are partially cut off) xOffset = 0; yOffset = -smartAdvanceAmount(screenHeight, top); } mScrollerLastX = mScrollerLastY = 0; mScroller.startScroll(0, 0, remainingX - xOffset, remainingY - yOffset, 400); post(this); } public void resetupChildren() { for (int i = 0; i < mChildViews.size(); i++) onChildSetup(mChildViews.keyAt(i), mChildViews.valueAt(i)); } public void applyToChildren(ViewMapper mapper) { for (int i = 0; i < mChildViews.size(); i++) mapper.applyToView(mChildViews.valueAt(i)); } public void refresh(boolean reflow) { mReflow = reflow; mScale = 1.0f; mXScroll = mYScroll = 0; int numChildren = mChildViews.size(); for (int i = 0; i < numChildren; i++) { View v = mChildViews.valueAt(i); onNotInUse(v); removeViewInLayout(v); } mChildViews.clear(); mViewCache.clear(); requestLayout(); } protected void onChildSetup(int i, View v) {} protected void onMoveToChild(int i) {} protected void onMoveOffChild(int i) {} protected void onSettle(View v) {}; protected void onUnsettle(View v) {}; protected void onNotInUse(View v) {}; protected void onScaleChild(View v, Float scale) {}; public View getView(int i) { return mChildViews.get(i); } public View getDisplayedView() { return mChildViews.get(mCurrent); } public void run() { if (!mScroller.isFinished()) { mScroller.computeScrollOffset(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); mXScroll += x - mScrollerLastX; mYScroll += y - mScrollerLastY; mScrollerLastX = x; mScrollerLastY = y; requestLayout(); post(this); } else if (!mUserInteracting) { // End of an inertial scroll and the user is not interacting. // The layout is stable View v = mChildViews.get(mCurrent); if (v != null) postSettle(v); } } public boolean onDown(MotionEvent arg0) { mScroller.forceFinished(true); return true; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (mScaling) return true; View v = mChildViews.get(mCurrent); if (v != null) { Rect bounds = getScrollBounds(v); switch(directionOfTravel(velocityX, velocityY)) { case MOVING_LEFT: if (bounds.left >= 0) { // Fling off to the left bring next view onto screen View vl = mChildViews.get(mCurrent+1); if (vl != null) { slideViewOntoScreen(vl); return true; } } break; case MOVING_RIGHT: if (bounds.right <= 0) { // Fling off to the right bring previous view onto screen View vr = mChildViews.get(mCurrent-1); if (vr != null) { slideViewOntoScreen(vr); return true; } } break; } mScrollerLastX = mScrollerLastY = 0; // If the page has been dragged out of bounds then we want to spring back // nicely. fling jumps back into bounds instantly, so we don't want to use // fling in that case. On the other hand, we don't want to forgo a fling // just because of a slightly off-angle drag taking us out of bounds other // than in the direction of the drag, so we test for out of bounds only // in the direction of travel. // Also don't fling if out of bounds in any direction by more than fling // margin Rect expandedBounds = new Rect(bounds); expandedBounds.inset(-FLING_MARGIN, -FLING_MARGIN); if(withinBoundsInDirectionOfTravel(bounds, velocityX, velocityY) && expandedBounds.contains(0, 0)) { mScroller.fling(0, 0, (int)velocityX, (int)velocityY, bounds.left, bounds.right, bounds.top, bounds.bottom); post(this); } } return true; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!mScaling) { mXScroll -= distanceX; mYScroll -= distanceY; requestLayout(); } return true; } public void onShowPress(MotionEvent e) { } public boolean onSingleTapUp(MotionEvent e) { return false; } public boolean onScale(ScaleGestureDetector detector) { float previousScale = mScale; float scale_factor = mReflow ? REFLOW_SCALE_FACTOR : 1.0f; float min_scale = MIN_SCALE * scale_factor; float max_scale = MAX_SCALE * scale_factor; mScale = Math.min(Math.max(mScale * detector.getScaleFactor(), min_scale), max_scale); if (mReflow) { View v = mChildViews.get(mCurrent); if (v != null) onScaleChild(v, mScale); } else { float factor = mScale/previousScale; View v = mChildViews.get(mCurrent); if (v != null) { // Work out the focus point relative to the view top left int viewFocusX = (int)detector.getFocusX() - (v.getLeft() + mXScroll); int viewFocusY = (int)detector.getFocusY() - (v.getTop() + mYScroll); // Scroll to maintain the focus point mXScroll += viewFocusX - viewFocusX * factor; mYScroll += viewFocusY - viewFocusY * factor; requestLayout(); } } return true; } public boolean onScaleBegin(ScaleGestureDetector detector) { mScaling = true; // Ignore any scroll amounts yet to be accounted for: the // screen is not showing the effect of them, so they can // only confuse the user mXScroll = mYScroll = 0; return true; } public void onScaleEnd(ScaleGestureDetector detector) { if (mReflow) { applyToChildren(new ViewMapper() { @Override void applyToView(View view) { onScaleChild(view, mScale); } }); } mScaling = false; } @Override public boolean onTouchEvent(MotionEvent event) { mScaleGestureDetector.onTouchEvent(event); mGestureDetector.onTouchEvent(event); if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mUserInteracting = true; } if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { mUserInteracting = false; View v = mChildViews.get(mCurrent); if (v != null) { if (mScroller.isFinished()) { // If, at the end of user interaction, there is no // current inertial scroll in operation then animate // the view onto screen if necessary slideViewOntoScreen(v); } if (mScroller.isFinished()) { // If still there is no inertial scroll in operation // then the layout is stable postSettle(v); } } } requestLayout(); return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int n = getChildCount(); for (int i = 0; i < n; i++) measureView(getChildAt(i)); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); View cv = mChildViews.get(mCurrent); Point cvOffset; if (!mResetLayout) { // Move to next or previous if current is sufficiently off center if (cv != null) { cvOffset = subScreenSizeOffset(cv); // cv.getRight() may be out of date with the current scale // so add left to the measured width for the correct position if (cv.getLeft() + cv.getMeasuredWidth() + cvOffset.x + GAP/2 + mXScroll < getWidth()/2 && mCurrent + 1 < mAdapter.getCount()) { postUnsettle(cv); // post to invoke test for end of animation // where we must set hq area for the new current view post(this); onMoveOffChild(mCurrent); mCurrent++; onMoveToChild(mCurrent); } if (cv.getLeft() - cvOffset.x - GAP/2 + mXScroll >= getWidth()/2 && mCurrent > 0) { postUnsettle(cv); // post to invoke test for end of animation // where we must set hq area for the new current view post(this); onMoveOffChild(mCurrent); mCurrent onMoveToChild(mCurrent); } } // Remove not needed children and hold them for reuse int numChildren = mChildViews.size(); int childIndices[] = new int[numChildren]; for (int i = 0; i < numChildren; i++) childIndices[i] = mChildViews.keyAt(i); for (int i = 0; i < numChildren; i++) { int ai = childIndices[i]; if (ai < mCurrent - 1 || ai > mCurrent + 1) { View v = mChildViews.get(ai); onNotInUse(v); mViewCache.add(v); removeViewInLayout(v); mChildViews.remove(ai); } } } else { mResetLayout = false; mXScroll = mYScroll = 0; // Remove all children and hold them for reuse int numChildren = mChildViews.size(); for (int i = 0; i < numChildren; i++) { View v = mChildViews.valueAt(i); onNotInUse(v); mViewCache.add(v); removeViewInLayout(v); } mChildViews.clear(); // post to ensure generation of hq area post(this); } // Ensure current view is present int cvLeft, cvRight, cvTop, cvBottom; boolean notPresent = (mChildViews.get(mCurrent) == null); cv = getOrCreateChild(mCurrent); // When the view is sub-screen-size in either dimension we // offset it to center within the screen area, and to keep // the views spaced out cvOffset = subScreenSizeOffset(cv); if (notPresent) { //Main item not already present. Just place it top left cvLeft = cvOffset.x; cvTop = cvOffset.y; } else { // Main item already present. Adjust by scroll offsets cvLeft = cv.getLeft() + mXScroll; cvTop = cv.getTop() + mYScroll; } // Scroll values have been accounted for mXScroll = mYScroll = 0; cvRight = cvLeft + cv.getMeasuredWidth(); cvBottom = cvTop + cv.getMeasuredHeight(); if (!mUserInteracting && mScroller.isFinished()) { Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom)); cvRight += corr.x; cvLeft += corr.x; cvTop += corr.y; cvBottom += corr.y; } else if (cv.getMeasuredHeight() <= getHeight()) { // When the current view is as small as the screen in height, clamp // it vertically Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom)); cvTop += corr.y; cvBottom += corr.y; } cv.layout(cvLeft, cvTop, cvRight, cvBottom); if (mCurrent > 0) { View lv = getOrCreateChild(mCurrent - 1); Point leftOffset = subScreenSizeOffset(lv); int gap = leftOffset.x + GAP + cvOffset.x; lv.layout(cvLeft - lv.getMeasuredWidth() - gap, (cvBottom + cvTop - lv.getMeasuredHeight())/2, cvLeft - gap, (cvBottom + cvTop + lv.getMeasuredHeight())/2); } if (mCurrent + 1 < mAdapter.getCount()) { View rv = getOrCreateChild(mCurrent + 1); Point rightOffset = subScreenSizeOffset(rv); int gap = cvOffset.x + GAP + rightOffset.x; rv.layout(cvRight + gap, (cvBottom + cvTop - rv.getMeasuredHeight())/2, cvRight + rv.getMeasuredWidth() + gap, (cvBottom + cvTop + rv.getMeasuredHeight())/2); } invalidate(); } @Override public Adapter getAdapter() { return mAdapter; } @Override public View getSelectedView() { throw new UnsupportedOperationException(getContext().getString(R.string.not_supported)); } @Override public void setAdapter(Adapter adapter) { mAdapter = adapter; mChildViews.clear(); removeAllViewsInLayout(); requestLayout(); } @Override public void setSelection(int arg0) { throw new UnsupportedOperationException(getContext().getString(R.string.not_supported)); } private View getCached() { if (mViewCache.size() == 0) return null; else return mViewCache.removeFirst(); } private View getOrCreateChild(int i) { View v = mChildViews.get(i); if (v == null) { v = mAdapter.getView(i, getCached(), this); addAndMeasureChild(i, v); onChildSetup(i, v); onScaleChild(v, mScale); } return v; } private void addAndMeasureChild(int i, View v) { LayoutParams params = v.getLayoutParams(); if (params == null) { params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } addViewInLayout(v, 0, params, true); mChildViews.append(i, v); // Record the view against it's adapter index measureView(v); } private void measureView(View v) { // See what size the view wants to be v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); if (!mReflow) { // Work out a scale that will fit it to this view float scale = Math.min((float)getWidth()/(float)v.getMeasuredWidth(), (float)getHeight()/(float)v.getMeasuredHeight()); // Use the fitting values scaled by our current scale factor v.measure(View.MeasureSpec.EXACTLY | (int)(v.getMeasuredWidth()*scale*mScale), View.MeasureSpec.EXACTLY | (int)(v.getMeasuredHeight()*scale*mScale)); } else { v.measure(View.MeasureSpec.EXACTLY | (int)(v.getMeasuredWidth()), View.MeasureSpec.EXACTLY | (int)(v.getMeasuredHeight())); } } private Rect getScrollBounds(int left, int top, int right, int bottom) { int xmin = getWidth() - right; int xmax = -left; int ymin = getHeight() - bottom; int ymax = -top; // In either dimension, if view smaller than screen then // constrain it to be central if (xmin > xmax) xmin = xmax = (xmin + xmax)/2; if (ymin > ymax) ymin = ymax = (ymin + ymax)/2; return new Rect(xmin, ymin, xmax, ymax); } private Rect getScrollBounds(View v) { // There can be scroll amounts not yet accounted for in // onLayout, so add mXScroll and mYScroll to the current // positions when calculating the bounds. return getScrollBounds(v.getLeft() + mXScroll, v.getTop() + mYScroll, v.getLeft() + v.getMeasuredWidth() + mXScroll, v.getTop() + v.getMeasuredHeight() + mYScroll); } private Point getCorrection(Rect bounds) { return new Point(Math.min(Math.max(0,bounds.left),bounds.right), Math.min(Math.max(0,bounds.top),bounds.bottom)); } private void postSettle(final View v) { // onSettle and onUnsettle are posted so that the calls // wont be executed until after the system has performed // layout. post (new Runnable() { public void run () { onSettle(v); } }); } private void postUnsettle(final View v) { post (new Runnable() { public void run () { onUnsettle(v); } }); } private void slideViewOntoScreen(View v) { Point corr = getCorrection(getScrollBounds(v)); if (corr.x != 0 || corr.y != 0) { mScrollerLastX = mScrollerLastY = 0; mScroller.startScroll(0, 0, corr.x, corr.y, 400); post(this); } } private Point subScreenSizeOffset(View v) { return new Point(Math.max((getWidth() - v.getMeasuredWidth())/2, 0), Math.max((getHeight() - v.getMeasuredHeight())/2, 0)); } private static int directionOfTravel(float vx, float vy) { if (Math.abs(vx) > 2 * Math.abs(vy)) return (vx > 0) ? MOVING_RIGHT : MOVING_LEFT; else if (Math.abs(vy) > 2 * Math.abs(vx)) return (vy > 0) ? MOVING_DOWN : MOVING_UP; else return MOVING_DIAGONALLY; } private static boolean withinBoundsInDirectionOfTravel(Rect bounds, float vx, float vy) { switch (directionOfTravel(vx, vy)) { case MOVING_DIAGONALLY: return bounds.contains(0, 0); case MOVING_LEFT: return bounds.left <= 0; case MOVING_RIGHT: return bounds.right >= 0; case MOVING_UP: return bounds.top <= 0; case MOVING_DOWN: return bounds.bottom >= 0; default: throw new NoSuchElementException(); } } }
package fi.hu.cs.titokone.resources; import java.util.ListResourceBundle; /** This translation is what all translations should be based on. It translates keys to plain English. Note that not all keys are equal to their values; the key may contain a specification part which should not be translated. The specification part ought to be put between ? and :, eg. "?Menu:File" would mean "translate the word 'File' as if you would see it on the common menu name" as opposed to "?Utility item:File", which might mean "translate the word 'File' as you would if it meant a nail file". */ public class Translations extends ListResourceBundle { public Object[][] getContents() { // To be simultaneously compatible with the general ListResourceBundle // functionality and provide a base template array for other // translations, we do not repeat every line in the emptyContents // array, but instead arrange the duplication when asked for // the real contents. (Only necessary the first time.) if(contents == null) { contents = new String[emptyContents.length][]; for(int i = 0; i < emptyContents.length; i++) { contents[i] = new String[2]; contents[i][0] = emptyContents[i][0]; contents[i][1] = emptyContents[i][0]; } } return contents; } protected static Object[][] contents; private static final Object[][] emptyContents = { // Localize below, pairs of key-value (what key is in your language)... // Remove lines which you do not wish to translate completely. Leaving // in a value of "" will translate the message to "" as well. // Class: Animator, not processed yet - TODO. // Class: Application. // General messages: (none) // Exception messages: { "No more keyboard data stored on application." , null }, { "No more stdin data stored on application.", null }, { "Keyboard input string \"{0}\" invalid, should be eg. \\n-separated " + "list of integers." , null }, { "Stdin input string \"{0}\" invalid, should be eg. \\n-separated " + "list of integers.", null }, // Log messages: { "Application has no more keyboard data, read: {0}, buffer length " + "{1}.", null }, { "Application has no more stdin data, read: {0}, buffer length {1}.", null }, { "Accepted \"{0}\" as keyboard input, tokens found: {1}.", null }, { "Accepted \"{0}\" as stdin input, tokens found: {1}.", null }, // Class: BinaryInterpreter, no messages. // Class: Binary {"___b91___ is missing.", null}, {"___code___ is missing.", null}, {"Invalid code area value on line: {0}", null}, {"Invalid code area length on line: {0}", null}, {"Invalid command on line: {0}", null}, {"Invalid number of code lines.", null}, {"___data___ is missing.", null}, {"Invalid data area value on line: {0}", null}, {"Invalid data area length on line: {0}", null}, {"Invalid data on line: {0}", null}, {"___symboltable___ is missing.", null}, {"Invalid symbol on line: {0}", null}, {"Invalid symbol value on line: {0}", null}, {"___end___ is missing.", null}, {"Lines after ___end___", null}, // Class: CompileDebugger, no messages. // Class: CompileInfo, no messages. // Class: Compiler // line (approx) {"Compilation is not finished yet.", null}, // 203 {"Invalid command.", null}, // 255 {"Invalid label.", null}, // 271, 328, 345 and 349 {"Found label {0} and variable {1}.", null}, // 323 {"Variable {0} used.", null}, // 328 {"Label {0} found.", null}, // 333 {"Invalid size for a DS.", null}, // 358 and 362 {"Invalid value for a DC.", null}, // 373 {"Variable {0} defined as {1}.", null}, // 401 {"Found variable {0}.", null}, // 419 and 436 {"{0} defined as {1}.", null}, // 449 {"Invalid DEF operation.", null}, // 454 {"{0} --> {1} ({2}) ", null}, // symb --> bin (:-sep. bin); 650 // Class: Control {"No default STDIN file set.", null}, {"No default STDOUT file set.", null}, {"No application to load.", null}, {"STDIN data file unreadable: {0}", null}, {"STDIN data file contains invalid data: {0}", null}, {"STDIN files were null, data not inserted to the application.", null }, {"Application contained an odd definition key '{0}'.", null}, {"Trying to run an unsupported type of application. (The application " + "must be created using the same program.)", null}, {"Cannot form a binary out of an unsupported type of an application. " + "(The application must be created using the same program.)", null}, {"There is no application available to run from!", null}, {"No STDOUT file set, not writing to it.", null}, {"Memory size must be between 2^9 and 2^16, a change to 2^{0} failed.", null}, {"StdIn file contents are invalid; the file should contain only " + "integers and separators.", null}, {"Modified source was null.", null}, {"No source file set, use openSource first.", null}, {"Cannot deduce the file to store the binary into; no source " + "file has been loaded.", null}, {"Cannot save binary to file; no application has been compiled or " + "loaded.", null}, // Class: DebugInfo, no messages. // Class: FileHandler {"{0} in loadResourceBundle(): {1}", null}, {"No read access to {0}.", null}, {"No write access to {0}.", null}, // Class: GUI {"File", null}, {"Open", null}, {"Compile", null}, {"Run", null}, {"Continue", null}, {"Continue without pauses", null}, {"Stop", null}, {"Erase memory", null}, {"Exit", null}, {"Options", null}, {"Set memory size", null}, {"Help", null}, {"Manual", null}, {"About", null}, {"Set compiling options", null}, {"Set running options", null}, {"Configure file system", null}, {"Select default stdin file", null}, {"Select default stdout file", null}, {"Set language", null}, {"Select from a file...", null}, {"Line", null}, {"Numeric", null}, {"Symbolic", null}, {"Open a new file", null}, {"Compile the opened file", null}, {"Run the loaded program", null}, {"Continue current operation", null}, {"Continue current operation without pauses", null}, {"Stop current operation", null}, {"Open the selected file", null}, {"Enter", null}, // button used to enter a number to the KBD device. {"Symbol table", null}, {"Registers", null}, // Class: GUIBrain {"Main path not found! (Trying to locate etc/settings.cfg.) " + "...exiting.", null}, //exception opening etc/settings.cfg {"I/O error while reading settings file: {0}", null}, {"Parse error in settings file.", null}, {"Settings class messed up, parseException on passing null to the " + "constructor.", null}, {"Titokone out of memory: {0}", null}, {"File extension must be k91 or b91", null}, {"Illegal input", null}, {"Illegal input. You must insert a number between {0}...{1}", null}, {"Error", null}, {"Enter a number in the text field above.", null}, {"Not a language file", null}, {"Cannot overwrite {0}", null}, {"Default stdin file set to {0}", null}, {"Default stdout file set to {0}", null}, {"Error while emptying {0}", null}, {"Overwrite?", null}, {"Do you want to overwrite the file? Select {1} to append or {0} " + "to overwrite.", null}, {"B91 binary", null}, {"K91 source", null}, {"Class file", null}, // Class: GUICompileSettingsDialog - not processed yet - TODO // Class: GUIRunSettingsDialog - not processed yet - TODO // Class: GUIThreader, no messages. // Class: Interpreter, no messages. // Class: InvalidDefinitionException, no messages. // Class: InvalidSymbolException, no messages. // Class: JFileChooser {"Open", null}, {"Cancel", null}, {"Look in:", null}, {"File name:", null}, {"Files of type:", null}, {"Up one level", null}, {"Up", null}, {"Desktop", null}, {"Create new folder", null}, {"New folder", null}, {"List", null}, {"Details", null}, {"All files", null}, // Class: JOptionPane {"Yes", null}, {"No", null}, {"Pause whenever a comment occurs" , null}, {"Show extra comments while compiling", null}, {"Execute code line by line", null}, {"Show extra comments while executing", null}, {"Show animation while executing", null}, {"Apply" , null}, {"Close" , null}, // Class: JTableX, no messages. // Class: Loader {"Null is an invalid parameter, instance of {0} required.", null}, {"Program loaded into memory. FP set to {0} and SP to {1}.", null}, // Class: LoadInfo, no messages. // Class: MemoryLine, no messages. // Class: Message, no messages. (Surprising, huh?) // Class: Processor {"Invalid operation code {0}", null}, {"Memory address out of bounds", null}, {"Invalid memory addressing mode", null}, {"Invalid memory access mode in branching command", null}, {"Invalid memory access mode in STORE", null}, {"No keyboard data available", null}, {"No standard input data available", null}, {"Invalid device number", null}, {"Integer overflow", null}, {"Division by zero", null}, {"Row number {0} is beyond memory limits.", null}, // in memoryInput // Class: RandomAccessMemory {"Memory size cannot be negative.", null}, {"Tried to set symbol table to null.", null}, {"Trying to load a null memory line.", null}, {"Address {0} too large, memory size {1} (indexing starts at 0).", null}, {"Address {0} below zero.", null}, {"Code area size cannot be negative.", null}, {"Code area size cannot be bigger than the size of the whole memory.", null}, {"Data area size cannot be negative.", null}, {"Data area size cannot be bigger than the size of the whole memory.", null}, // Class: Registers {"Unknown registerId: {0}", null}, {"Unknown registerName: {0}", null}, // Class: ResourceLoadFailedException, no messages. // Class: RunDebugger, comments {"{0}{1} Indexing {2}, direct.", null}, {"{0}{1} Indexing {2}, direct addressing.", null}, {"{0}{1} Indexing {2}, indirect addressing.", null}, // Comment with value (=KBD, =CRT =STDIN =STDOUT) {"{0}{1} Indexing {2}, direct, value {3}.", null}, // Are these two needed? {"{0}{1} Indexing {2}, direct addressing, value {3}.", null}, {"{0}{1} Indexing {2}, indirect addressing {3}.", null}, // Class: RunInfo, no messages. // Class: Settings. // General messages: (none) // Exception messages: { "value", null }, { "a linebreak", null }, { "Illegal {0} \"{1}\", contains {2}.", null }, { "Illegal {0}: null. Try an empty string instead.", null }, { "Syntax error on line {0}, which was: \"{1}\".", null }, // Log messages: { "Settings successfully parsed, lines: {0}, unique keys found: {1}.", null }, // Class: Source, no messages. // Class: SymbolicInterpreter, no messages. // Class: SymbolTable {"SymbolName was null.", null}, {"Definition key was null.", null}, {"Definition {0} not found.", null} // Class: Translator: no translateable strings set to avoid // looping bugs. // Localizable bit ends. }; }
package com.mhalka.babytracker; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Calendar; import java.util.GregorianCalendar; public class BabyTracker extends Activity { // Namjesti konstante za preference. private static final String PREFS_NAME = "BabyTrackerPrefs"; private static final String NOTIFIKACIJA = "Notifikacija"; private static final String DAN = "DanPocetkaPracenja"; private static final String MJESEC = "MjesecPocetkaPracenja"; private static final String GODINA = "GodinaPocetkaPracenja"; private static final String MJESECI = "TrenutnaStarostBebe"; private String shareVrijeme; /** * Called when the activity is first created. */ @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.babytracker); // Zabiljezi broj otvaranja aplikacije i pokazi rate dijalog ako su uslovi ispunjeni AppRater.appLaunched(this); // Povezi prethodno setirane varijable za elemente forme sa njihovim vrijednostima. LinearLayout bebaLayout = (LinearLayout) findViewById(R.id.llBabyTracker); TextView podaciBeba = (TextView) findViewById(R.id.txtPodaciBeba); TextView introPodaciBeba = (TextView) findViewById(R.id.txtIntroPodaciBeba); ImageView slikaBeba = (ImageView) findViewById(R.id.ivSlikaBeba); String vasaBeba = this.getString(R.string.vasa_beba); String mjesec = this.getString(R.string.mjesec); String nerealnaVrijednost = this.getString(R.string.nerealna_vrijednost); String napunjenaGodina = this.getString(R.string.napunjena_godina); String prekoGodine = this.getString(R.string.vise_od_godine); // Procitaj preference SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); Boolean NotifikacijaUkljucena = settings.getBoolean(NOTIFIKACIJA, true); // Dobavi datum pocetka pracenja i danasnji datum. Calendar datumPocetkaPracenja = new GregorianCalendar(settings.getInt(GODINA, 1920), settings.getInt(MJESEC, 0), settings.getInt(DAN, 1)); Calendar today = Calendar.getInstance(); // Izracunaj starost bebe u mjesecima. Calendar datum = (Calendar) datumPocetkaPracenja.clone(); long monthsBetween = 0; while (datum.before(today)) { today.add(Calendar.MONTH, -1); monthsBetween++; } int months = (int) monthsBetween; /** Ponovo dobavi datum pocetka pracenja i danasnji datum, jer, iz nekog razloga, donji if * statement ne moze da koristi prethodno dobavljene vrijednosti. */ Calendar pocetak = new GregorianCalendar(settings.getInt(GODINA, 1920), settings.getInt(MJESEC, 0), settings.getInt(DAN, 1)); Calendar danas = Calendar.getInstance(); /** Provjeri da li je izracunata vrijednost 12 i da li datum rodjenja (mjesec i dan) odgovaraju * danasnjem datumu i shodno tome pokazi alert dijalog da je beba napunila godinu dana. */ if ((months == 12) && ((pocetak.get(Calendar.YEAR)) < (danas.get(Calendar.YEAR))) && ((pocetak.get(Calendar.MONTH)) == (danas.get(Calendar.MONTH))) && ((pocetak.get(Calendar.DAY_OF_MONTH)) == (danas.get(Calendar.DAY_OF_MONTH)))) { bebaLayout.setVisibility(View.INVISIBLE); AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setMessage(napunjenaGodina); alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }); alertbox.show(); } // Provjeri da izracunata vrijednost nije negativna. else if (months < 1) { bebaLayout.setVisibility(View.INVISIBLE); AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setMessage(nerealnaVrijednost); alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Intent podesavanja = new Intent(BabyTracker.this, SettingsActivity.class); startActivityForResult(podesavanja, 0); finish(); } }); alertbox.show(); } // Provjeri da li je izracunata vrijednost veca od 12 i shodno tome pokazi odgovarajuci alert. else if (months > 12) { bebaLayout.setVisibility(View.INVISIBLE); /** Provjeri da li datum rodjenja (mjesec i dan) odgovaraju danasnjem datumu i shodno tome * pokazi alert dijalog da je beba napunila godinu dana. */ if (((pocetak.get(Calendar.YEAR)) < (danas.get(Calendar.YEAR))) && ((pocetak.get(Calendar.MONTH)) == (danas.get(Calendar.MONTH))) && ((pocetak.get(Calendar.DAY_OF_MONTH)) == (danas.get(Calendar.DAY_OF_MONTH)))) { AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setMessage(napunjenaGodina); alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }); alertbox.show(); } else { /** Ako izracunata vrijednost premasuje dozvoljenu granicu izbaci upozorenje i * vrati korisnika na settings activity. */ AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setMessage(prekoGodine); alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Intent podesavanja = new Intent(BabyTracker.this, SettingsActivity.class); startActivityForResult(podesavanja, 0); finish(); } }); alertbox.show(); } } // Ako je izracunata vrijednost u dozvoljenim granicama nastavi dalje else { // Zapisi izracunatu vrijednost ako je ukljucena notifikacija i okini alarm. if (NotifikacijaUkljucena) { // Zapisi trenutnu vrijednost u preference radi koristenja kasnije SharedPreferences.Editor editor = settings.edit(); editor.putInt(MJESECI, months); editor.apply(); // Namjesti vrijeme za alarm i okidanje notifikacije Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), (24 * 60 * 60 * 1000), pendingIntent); } // Namjesti ActionBar ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowCustomEnabled(true); LayoutInflater inflater = LayoutInflater.from(this); View actionBarView = inflater.inflate(R.layout.actionbar, bebaLayout, false); TextView actionBarTitle = (TextView) actionBarView.findViewById(R.id.abTitle); TextView actionBarSubtitle = (TextView) actionBarView.findViewById(R.id.abSubtitle); actionBarTitle.setText(vasaBeba + " " + months + "." + " " + mjesec); actionBarSubtitle.setVisibility(View.GONE); actionBar.setCustomView(actionBarView); shareVrijeme = actionBarTitle.getText().toString(); } // Setiraj array sa resource ID-jevima za slike. int slike[] = {R.drawable.mjesec01, R.drawable.mjesec02, R.drawable.mjesec03, R.drawable.mjesec04, R.drawable.mjesec05, R.drawable.mjesec06, R.drawable.mjesec07, R.drawable.mjesec08, R.drawable.mjesec09, R.drawable.mjesec10, R.drawable.mjesec11, R.drawable.mjesec12}; // Setiraj resource ID shodno izracunatom mjesecu u kojem se beba trenutno nalazi. int resIdSlike = slike[months - 1]; // Populariziraj ImageView sa odgovarajucom slikom. slikaBeba.setImageResource(resIdSlike); // Setiraj array sa vrijednostima za podatke o razvoju. int podaci[] = {R.raw.mjesec01, R.raw.mjesec02, R.raw.mjesec03, R.raw.mjesec04, R.raw.mjesec05, R.raw.mjesec06, R.raw.mjesec07, R.raw.mjesec08, R.raw.mjesec09, R.raw.mjesec10, R.raw.mjesec11, R.raw.mjesec12}; // Setiraj resource ID shodno izracunatom mjesecu u kojem se beba trenutno nalazi. int resIdPodaci = podaci[months - 1]; /** Dobavi odgovarajuci text file, parsiraj ga i sa njegovim sadrzajem populariziraj * TextView u kojem treba da se nalaze podaci. */ InputStream inputStream = this.getResources().openRawResource(resIdPodaci); InputStreamReader inputreader = new InputStreamReader(inputStream); BufferedReader buffreader = new BufferedReader(inputreader); String line; int numLines = 2; int lineCtr = 0; StringBuilder introtext = new StringBuilder(); try { while ((line = buffreader.readLine()) != null) { if (lineCtr == numLines) { break; } lineCtr++; introtext.append(line); introtext.append('\n'); } } catch (IOException e) { return; } introPodaciBeba.setText(introtext.toString()); StringBuilder text = new StringBuilder(); try { while ((line = buffreader.readLine()) != null) { if (lineCtr >= numLines) { lineCtr++; text.append(line); text.append('\n'); } } } catch (IOException e) { return; } podaciBeba.setText(text.toString()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Opcije menija. switch (item.getItemId()) { case R.id.share: podijeliStanje(); return true; case R.id.podesavanja: Intent podesavanja = new Intent(this, SettingsActivity.class); startActivityForResult(podesavanja, 0); finish(); return true; case R.id.rateapp: AppRater.rateApp(this); return true; case R.id.about: Intent about = new Intent(this, About.class); startActivityForResult(about, 0); return true; default: return super.onOptionsItemSelected(item); } } private void podijeliStanje() { TextView introPodaciBeba = (TextView) findViewById(R.id.txtIntroPodaciBeba); TextView podaciBeba = (TextView) findViewById(R.id.txtPodaciBeba); Intent sharingIntent = new Intent(); sharingIntent.setAction(Intent.ACTION_SEND); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareVrijeme); String shareBody = introPodaciBeba.getText().toString().trim() + "\n\n" + podaciBeba.getText().toString().trim(); sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody); sharingIntent.setType("text/html"); startActivity(Intent.createChooser(sharingIntent, getString(R.string.share))); } }
package sketch.avengergear.com; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.app.Activity; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.widget.TextView; import org.spongycastle.jce.provider.BouncyCastleProvider; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.Cipher; import java.util.Arrays; import java.util.Map; import java.util.UUID; public class sketchUI extends Activity { private static final String TAG = "SKETCH-UI"; static { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { // Create the public and private keys KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC"); SecureRandom random = new SecureRandom(); generator.initialize(2048, random); KeyPair keyPair = generator.genKeyPair(); //PrivateKey privateKey = keyPair.getPrivate().getEncoded(); //PublicKey publicKey = keyPair.getPublic().getEncoded(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Log.v(TAG, keyPair.getPrivate().toString() ); String uuid = UUID.randomUUID().toString(); Log.v(TAG,"uuid = " + uuid); String testText = "Avenger testing the MoJo"; TextView original_textview = (TextView)findViewById(R.id.original_tv); original_textview.setText("[ORIGINAL]:\n" + testText + "\n"); // Encode the original data with RSA public key byte[] encoded = null; try { Cipher rsa_cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "SC"); rsa_cipher.init(Cipher.ENCRYPT_MODE, publicKey); encoded = rsa_cipher.doFinal(testText.getBytes()); } catch (Exception e) { Log.e(TAG, "RSA encryption error", e); } TextView encoded_textview = (TextView)findViewById(R.id.encoded_tv); encoded_textview.setText("[ENCODED]:\n" + Base64.encodeToString(encoded, Base64.DEFAULT) + "\n"); // Decode the encoded data with RSA public key byte[] decoded = null; try { Cipher rsa_cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "SC"); rsa_cipher.init(Cipher.DECRYPT_MODE, privateKey); decoded= rsa_cipher.doFinal(encoded); } catch (Exception e) { Log.e(TAG, "RSA decryption error", e); } TextView decoded_textview = (TextView)findViewById(R.id.decoded_tv); decoded_textview.setText("[DECODED]:\n" + new String(decoded) + "\n"); } catch (NoSuchProviderException e) { Log.e(TAG, "No provider exception", e); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "No Algorithum exception", e); } } }
package com.mikepenz.unsplash.models; import android.support.v7.graphics.Palette; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; public class Image implements Serializable { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private String color; private String image_src; private String author; private Date date; private Date modified_date; private float ratio; private int width; private int height; transient private Palette.Swatch swatch; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getHighResImage() { return image_src + "?q=100&fm=jpg"; } public String getImage_src() { return image_src + "?q=75&w=720&fit=max&fm=jpg"; } public void setImage_src(String image_src) { this.image_src = image_src; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getDate() { return date; } public String getReadableDate() { return sdf.format(date); } public void setDate(Date date) { this.date = date; } public Date getModified_date() { return modified_date; } public String getReadableModified_Date() { return sdf.format(modified_date); } public void setModified_date(Date modified_date) { this.modified_date = modified_date; } public float getRatio() { return ratio; } public void setRatio(float ratio) { this.ratio = ratio; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public Palette.Swatch getSwatch() { return swatch; } public void setSwatch(Palette.Swatch swatch) { this.swatch = swatch; } }
package com.pr0gramm.app.ui; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.util.Linkify; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.pr0gramm.app.R; import com.pr0gramm.app.api.pr0gramm.response.Message; import com.pr0gramm.app.ui.views.SenderInfoView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import roboguice.RoboGuice; import static com.google.common.collect.Lists.newArrayList; public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> { private final List<Message> messages; private final Context context; private final Picasso picasso; private final MessageActionListener actionListener; public MessageAdapter(Context context, List<Message> messages) { this(context, messages, null); } public MessageAdapter(Context context, List<Message> messages, MessageActionListener actionListener) { this.context = context; this.actionListener = actionListener; this.messages = new ArrayList<>(messages); this.picasso = RoboGuice.getInjector(context).getInstance(Picasso.class); setHasStableIds(true); } /** * Replace all the messages with the new messages from the given iterable. */ public void setMessages(Iterable<Message> messages) { this.messages.clear(); Iterables.addAll(this.messages, messages); notifyDataSetChanged(); } @Override public long getItemId(int position) { return messages.get(position).getId(); } @Override public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.inbox_message, parent, false); return new MessageViewHolder(view); } @SuppressWarnings("CodeBlock2Expr") @Override public void onBindViewHolder(MessageViewHolder view, int position) { Message message = messages.get(position); // set the type. if we have an item, we have a comment boolean isComment = message.getItemId() != 0; view.type.setText(isComment ? context.getString(R.string.inbox_message_comment) : context.getString(R.string.inbox_message_private)); // the text of the message view.text.setText(message.getMessage()); Linkify.addLinks(view.text, Linkify.WEB_URLS); // draw the image for this post if (isComment) { view.image.setVisibility(View.VISIBLE); String url = "http://thumb.pr0gramm.com/" + message.getThumb(); picasso.load(url).into(view.image); } else { view.image.setVisibility(View.GONE); picasso.cancelRequest(view.image); } // sender info view.sender.setSenderName(message.getName(), message.getMark()); view.sender.setPointsVisible(isComment); view.sender.setPoints(message.getScore()); view.sender.setDate(message.getCreated()); // reset the answer click listener view.sender.setAnswerClickedListener(null); if (actionListener != null) { view.sender.setOnSenderClickedListener(v -> { actionListener.onUserClicked(message.getSenderId(), message.getName()); }); if (isComment) { view.sender.setAnswerClickedListener(v -> { actionListener.onAnswerToCommentClicked(message.getItemId(), message.getId(), message.getName()); }); view.image.setOnClickListener(v -> { actionListener.onCommentClicked(message.getItemId(), message.getId()); }); } else { view.sender.setAnswerClickedListener(v -> { actionListener.onAnswerToPrivateMessage(message.getSenderId(), message.getName()); }); view.image.setOnClickListener(null); } } } @Override public int getItemCount() { return messages.size(); } static class MessageViewHolder extends RecyclerView.ViewHolder { final TextView text; final TextView type; final ImageView image; final SenderInfoView sender; public MessageViewHolder(View itemView) { super(itemView); text = (TextView) itemView.findViewById(R.id.message_text); type = (TextView) itemView.findViewById(R.id.message_type); image = (ImageView) itemView.findViewById(R.id.message_image); sender = (SenderInfoView) itemView.findViewById(R.id.sender_info); } } }
package com.samourai.wallet.api; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.ConnectivityStatus; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.R; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.script.Script; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.spongycastle.util.encoders.Hex; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.math.BigInteger; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; public class APIFactory { private static long xpub_balance = 0L; private static HashMap<String, Long> xpub_amounts = null; private static HashMap<String,List<Tx>> xpub_txs = null; private static HashMap<String,Integer> unspentAccounts = null; private static HashMap<String,String> unspentPaths = null; private static HashMap<String,UTXO> utxos = null; private static HashMap<String, Long> bip47_amounts = null; private static long latest_block_height = -1L; private static String latest_block_hash = null; private static APIFactory instance = null; private static Context context = null; private static AlertDialog alertDialog = null; private APIFactory() { ; } public static APIFactory getInstance(Context ctx) { context = ctx; if(instance == null) { xpub_amounts = new HashMap<String, Long>(); xpub_txs = new HashMap<String,List<Tx>>(); xpub_balance = 0L; bip47_amounts = new HashMap<String, Long>(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); instance = new APIFactory(); } return instance; } public synchronized void reset() { xpub_balance = 0L; xpub_amounts.clear(); bip47_amounts.clear(); xpub_txs.clear(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); } private synchronized JSONObject getXPUB(String[] xpubs) { JSONObject jsonObject = null; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "multiaddr?", args.toString()); Log.i("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "multiaddr", args); Log.i("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); xpub_txs.put(xpubs[0], new ArrayList<Tx>()); parseXPUB(jsonObject); xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_balance = walletObj.getLong("final_balance"); Log.d("APIFactory", "xpub_balance:" + xpub_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else { long amount = 0L; String addr = null; addr = (String)addrObj.get("address"); amount = addrObj.getLong("final_balance"); String pcode = BIP47Meta.getInstance().getPCode4Addr(addr); int idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(pcode != null && pcode.length() > 0) { if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } if(addr != null) { bip47_amounts.put(addr, amount); } } } } } if(jsonObject.has("txs")) { JSONArray txArray = (JSONArray)jsonObject.get("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); long height = 0L; long amount = 0L; long ts = 0L; String hash = null; String addr = null; String _addr = null; if(txObj.has("block_height")) { height = txObj.getLong("block_height"); } else { height = -1L; // 0 confirmations } if(txObj.has("hash")) { hash = (String)txObj.get("hash"); } if(txObj.has("result")) { amount = txObj.getLong("result"); } if(txObj.has("time")) { ts = txObj.getLong("time"); } if(txObj.has("inputs")) { JSONArray inputArray = (JSONArray)txObj.get("inputs"); JSONObject inputObj = null; for(int j = 0; j < inputArray.length(); j++) { inputObj = (JSONObject)inputArray.get(j); if(inputObj.has("prev_out")) { JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out"); if(prevOutObj.has("xpub")) { JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub"); addr = (String)xpubObj.get("m"); } else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) { _addr = (String)prevOutObj.get("addr"); } else { _addr = (String)prevOutObj.get("addr"); } } } } if(txObj.has("out")) { JSONArray outArray = (JSONArray)txObj.get("out"); JSONObject outObj = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("xpub")) { JSONObject xpubObj = (JSONObject)outObj.get("xpub"); addr = (String)xpubObj.get("m"); } else { _addr = (String)outObj.get("addr"); } } } if(addr != null || _addr != null) { if(addr == null) { addr = _addr; } Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0); if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) { tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr)); } if(!xpub_txs.containsKey(addr)) { xpub_txs.put(addr, new ArrayList<Tx>()); } if(FormatsUtil.getInstance().isValidXpub(addr)) { xpub_txs.get(addr).add(tx); } else { xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx); } if(height > 0L) { RBFUtil.getInstance().remove(hash); } } } } return true; } return false; } public long getLatestBlockHeight() { return latest_block_height; } public String getLatestBlockHash() { return latest_block_hash; } public JSONObject getNotifTx(String hash, String addr) { JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2); url.append("tx/"); url.append(hash); url.append("?fees=1"); Log.i("APIFactory", "Notif tx:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); Log.i("APIFactory", "Notif tx:" + response); try { jsonObject = new JSONObject(response); parseNotifTx(jsonObject, addr, hash); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public JSONObject getNotifAddress(String addr) { JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2); url.append("multiaddr?active="); url.append(addr); Log.i("APIFactory", "Notif address:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); Log.i("APIFactory", "Notif address:" + response); try { jsonObject = new JSONObject(response); parseNotifAddress(jsonObject, addr); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException { if(jsonObject != null && jsonObject.has("txs")) { JSONArray txArray = jsonObject.getJSONArray("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) { return; } String hash = null; if(txObj.has("hash")) { hash = (String)txObj.get("hash"); if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) { getNotifTx(hash, addr); } } } } } public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException { if(jsonObject != null) { byte[] mask = null; byte[] payload = null; PaymentCode pcode = null; if(jsonObject.has("inputs")) { JSONArray inArray = (JSONArray)jsonObject.get("inputs"); if(inArray.length() > 0) { JSONObject objInput = (JSONObject)inArray.get(0); String strScript = objInput.getString("sig"); Script script = new Script(Hex.decode(strScript)); Log.i("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey())); ECKey pKey = new ECKey(null, script.getPubKey(), true); Log.i("APIFactory", "address from script:" + pKey.toAddress(MainNetParams.get()).toString()); // Log.i("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey())); if(((JSONObject)inArray.get(0)).has("outpoint")) { JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint"); String strHash = received_from.getString("txid"); int idx = received_from.getInt("vout"); byte[] hashBytes = Hex.decode(strHash); Sha256Hash txHash = new Sha256Hash(hashBytes); TransactionOutPoint outPoint = new TransactionOutPoint(MainNetParams.get(), idx, txHash); byte[] outpoint = outPoint.bitcoinSerialize(); Log.i("APIFactory", "outpoint:" + Hex.toHexString(outpoint)); try { mask = BIP47Util.getInstance(context).getIncomingMask(script.getPubKey(), outpoint); Log.i("APIFactory", "mask:" + Hex.toHexString(mask)); } catch(Exception e) { e.printStackTrace(); } } } } if(jsonObject.has("outputs")) { JSONArray outArray = (JSONArray)jsonObject.get("outputs"); JSONObject outObj = null; boolean isIncoming = false; String _addr = null; String script = null; String op_return = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("address")) { _addr = outObj.getString("address"); if(addr.equals(_addr)) { isIncoming = true; } } if(outObj.has("scriptpubkey")) { script = outObj.getString("scriptpubkey"); if(script.startsWith("6a4c50")) { op_return = script; } } } if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) { payload = Hex.decode(op_return.substring(6)); } } if(mask != null && payload != null) { try { byte[] xlat_payload = PaymentCode.blind(payload, mask); Log.i("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload)); pcode = new PaymentCode(xlat_payload); Log.i("APIFactory", "incoming payment code:" + pcode.toString()); if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) { BIP47Meta.getInstance().setLabel(pcode.toString(), ""); BIP47Meta.getInstance().setIncomingStatus(hash); } } catch(AddressFormatException afe) { afe.printStackTrace(); } } // get receiving addresses for spends from decoded payment code if(pcode != null) { try { // initial lookup for(int i = 0; i < 3; i++) { PaymentAddress receiveAddress = BIP47Util.getInstance(context).getReceiveAddress(pcode, i); // Log.i("APIFactory", "receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString()); BIP47Meta.getInstance().setIncomingIdx(pcode.toString(), i, receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString()); BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), pcode.toString()); // Log.i("APIFactory", "send to " + i + ":" + sendAddress.getSendECKey().toAddress(MainNetParams.get()).toString()); } } catch(Exception e) { ; } } } } public synchronized int getNotifTxConfirmations(String hash) { // Log.i("APIFactory", "Notif tx:" + hash); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2); url.append("tx/"); url.append(hash); url.append("?fees=1"); // Log.i("APIFactory", "Notif tx:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Notif tx:" + response); jsonObject = new JSONObject(response); // Log.i("APIFactory", "Notif tx json:" + jsonObject.toString()); return parseNotifTx(jsonObject); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return 0; } public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException { int cf = 0; if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) { long latestBlockHeght = getLatestBlockHeight(); long height = jsonObject.getJSONObject("block").getLong("height"); cf = (int)((latestBlockHeght - height) + 1); if(cf < 0) { cf = 0; } } return cf; } public synchronized JSONObject getUnspentOutputs(String[] xpubs) { JSONObject jsonObject = null; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString()); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args); } parseUnspentOutputs(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString(); if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); String path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m)); } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxos.containsKey(script)) { utxos.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxos.put(script, utxo); } } catch(Exception e) { ; } } return true; } catch(JSONException je) { ; } } return false; } public synchronized JSONObject getAddressInfo(String addr) { return getXPUB(new String[] { addr }); } public synchronized JSONObject getTxInfo(String hash) { JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2); url.append("tx/"); url.append(hash); url.append("?fees=true"); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getBlockHeader(String hash) { JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2); url.append("header/"); url.append(hash); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getDynamicFees() { JSONObject jsonObject = null; try { int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0); if(sel == 2) { int[] blocks = new int[] { 2, 6, 24 }; List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); for(int i = 0; i < blocks.length; i++) { JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]); if(feeObj != null && feeObj.has("result")) { double fee = feeObj.getDouble("result"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8))); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); } } else { StringBuilder url = new StringBuilder(sel == 0 ? WebUtil._21CO_FEE_URL : WebUtil.BITCOIND_FEE_URL); // Log.i("APIFactory", "Dynamic fees:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Dynamic fees response:" + response); try { jsonObject = new JSONObject(response); if(sel == 0) { parseDynamicFees_21(jsonObject); } else { parseDynamicFees_bitcoind(jsonObject); } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseDynamicFees_21(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { // 21.co API List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); if(jsonObject.has("fastestFee")) { long fee = jsonObject.getInt("fastestFee"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("halfHourFee")) { long fee = jsonObject.getInt("halfHourFee"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("hourFee")) { long fee = jsonObject.getInt("hourFee"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); // Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString()); } return true; } return false; } private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { // bitcoind List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); if(jsonObject.has("2")) { long fee = jsonObject.getInt("2"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("6")) { long fee = jsonObject.getInt("6"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("24")) { long fee = jsonObject.getInt("24"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); // Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString()); } return true; } return false; } public synchronized void validateAPIThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); if(ConnectivityStatus.hasConnectivity(context)) { try { String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK); JSONObject jsonObject = new JSONObject(response); if(!jsonObject.has("process")) { showAlertDialog(context.getString(R.string.api_error), false); } } catch(Exception e) { showAlertDialog(context.getString(R.string.cannot_reach_api), false); } } else { showAlertDialog(context.getString(R.string.no_internet), false); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void showAlertDialog(final String message, final boolean forceExit){ if (!((Activity) context).isFinishing()) { if(alertDialog != null)alertDialog.dismiss(); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message); builder.setCancelable(false); if(!forceExit) { builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); //Retry validateAPIThread(); } }); } builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); ((Activity) context).finish(); } }); alertDialog = builder.create(); alertDialog.show(); } } public synchronized void initWallet() { Log.i("APIFactory", "initWallet()"); initWalletAmounts(); } private synchronized void initWalletAmounts() { APIFactory.getInstance(context).reset(); List<String> addressStrings = new ArrayList<String>(); String[] s = null; try { xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>()); addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false))); for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) { for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) { if(!addressStrings.contains(addr)) { addressStrings.add(addr); } } } if(addressStrings.size() > 0) { s = addressStrings.toArray(new String[0]); // Log.i("APIFactory", addressStrings.toString()); getUnspentOutputs(s); } HD_Wallet hdw = HD_WalletFactory.getInstance(context).get(); if(hdw != null && hdw.getXPUBs() != null) { String[] all = null; if(s != null && s.length > 0) { all = new String[hdw.getXPUBs().length + s.length]; System.arraycopy(hdw.getXPUBs(), 0, all, 0, hdw.getXPUBs().length); System.arraycopy(s, 0, all, hdw.getXPUBs().length, s.length); } else { all = hdw.getXPUBs(); } APIFactory.getInstance(context).getXPUB(all); String[] xs = new String[2]; xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(); xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr(); getUnspentOutputs(xs); getDynamicFees(); } } catch (IndexOutOfBoundsException ioobe) { ioobe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public synchronized int syncBIP47Incoming(String[] addresses) { JSONObject jsonObject = getXPUB(addresses); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); long amount = 0L; int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(addrObj.has("final_balance")) { amount = addrObj.getLong("final_balance"); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { // Log.i("APIFactory", "sync receive idx:" + idx + ", " + addr); ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public synchronized int syncBIP47Outgoing(String[] addresses) { JSONObject jsonObject = getXPUB(addresses); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { int stored = BIP47Meta.getInstance().getOutgoingIdx(pcode); if(idx >= stored) { // Log.i("APIFactory", "sync send idx:" + idx + ", " + addr); BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1); } ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public long getXpubBalance() { return xpub_balance; } public void setXpubBalance(long value) { xpub_balance = value; } public HashMap<String,Long> getXpubAmounts() { return xpub_amounts; } public HashMap<String,List<Tx>> getXpubTxs() { return xpub_txs; } public HashMap<String, String> getUnspentPaths() { return unspentPaths; } public HashMap<String, Integer> getUnspentAccounts() { return unspentAccounts; } public List<UTXO> getUtxos() { List<UTXO> unspents = new ArrayList<UTXO>(); unspents.addAll(utxos.values()); return unspents; } public void setUtxos(HashMap<String, UTXO> utxos) { APIFactory.utxos = utxos; } public synchronized List<Tx> getAllXpubTxs() { List<Tx> ret = new ArrayList<Tx>(); for(String key : xpub_txs.keySet()) { List<Tx> txs = xpub_txs.get(key); for(Tx tx : txs) { ret.add(tx); } } Collections.sort(ret, new TxMostRecentDateComparator()); return ret; } public synchronized UTXO getUnspentOutputsForSweep(String address) { try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(address); response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString()); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", address); response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args); } return parseUnspentOutputsForSweep(response); } catch(Exception e) { e.printStackTrace(); } return null; } private synchronized UTXO parseUnspentOutputsForSweep(String unspents) { UTXO utxo = null; if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return null; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return null; } // Log.d("APIFactory", "unspents found:" + outputsRoot.size()); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString(); // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxo == null) { utxo = new UTXO(); } utxo.getOutpoints().add(outPoint); } catch(Exception e) { ; } } } catch(JSONException je) { ; } } return utxo; } public static class TxMostRecentDateComparator implements Comparator<Tx> { public int compare(Tx t1, Tx t2) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; int ret = 0; if(t1.getTS() > t2.getTS()) { ret = BEFORE; } else if(t1.getTS() < t2.getTS()) { ret = AFTER; } else { ret = EQUAL; } return ret; } } }
package com.turo.ktalk.model; import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import com.hyphenate.EMContactListener; import com.hyphenate.EMGroupChangeListener; import com.hyphenate.chat.EMClient; import com.turo.ktalk.model.bean.GroupInfo; import com.turo.ktalk.model.bean.InvationInfo; import com.turo.ktalk.model.bean.UserInfo; import com.turo.ktalk.utils.Constant; import com.turo.ktalk.utils.SpUtils; import java.util.List; public class EventListener { private Context mContext; private final LocalBroadcastManager mLocalBroadcastManager; public EventListener(Context context) { mContext = context; mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext); EMClient.getInstance().contactManager().setContactListener(emContactListener); EMClient.getInstance().groupManager().addGroupChangeListener(eMGroupChangeListener); } private final EMContactListener emContactListener = new EMContactListener() { @Override public void onContactAdded(String hxid) { Model.getInstance().getDbManager().getContactTableDao().saveContact(new UserInfo(hxid),true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.CONTACT_CHANGED)); } @Override public void onContactDeleted(String hxid) { Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxId(hxid); Model.getInstance().getDbManager().getInviteTableDao().removeInvitation(hxid); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.CONTACT_CHANGED)); } @Override public void onContactInvited(String hxid, String reason) { InvationInfo invationInfo = new InvationInfo(); invationInfo.setUser(new UserInfo(hxid)); invationInfo.setReason(reason); invationInfo.setStatus(InvationInfo.InvitationStatus.NEW_INVITE); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.CONTACT_INVITE_CHANGED)); } @Override public void onFriendRequestAccepted(String hxid) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setUser(new UserInfo(hxid)); invitationInfo.setStatus(InvationInfo.InvitationStatus.INVITE_ACCEPT_BY_PEER); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.CONTACT_INVITE_CHANGED)); } @Override public void onFriendRequestDeclined(String s) { SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.CONTACT_INVITE_CHANGED)); } }; private final EMGroupChangeListener eMGroupChangeListener = new EMGroupChangeListener() { @Override public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(reason); invitationInfo.setGroup(new GroupInfo(groupName, groupId, inviter)); invitationInfo.setStatus(InvationInfo.InvitationStatus.NEW_GROUP_INVITE); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onRequestToJoinReceived(String groupId, String groupName, String applicant, String reason) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(reason); invitationInfo.setGroup(new GroupInfo(groupName, groupId, applicant)); invitationInfo.setStatus(InvationInfo.InvitationStatus.NEW_GROUP_APPLICATION); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onRequestToJoinAccepted(String groupId, String groupName, String accepter) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setGroup(new GroupInfo(groupName,groupId,accepter)); invitationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_APPLICATION_ACCEPTED); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onRequestToJoinDeclined(String groupId, String groupName, String decliner, String reason) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(reason); invitationInfo.setGroup(new GroupInfo(groupName, groupId, decliner)); invitationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_APPLICATION_DECLINED); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onInvitationAccepted(String groupId, String inviter, String reason) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(reason); invitationInfo.setGroup(new GroupInfo(groupId, groupId, inviter)); invitationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_INVITE_ACCEPTED); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onInvitationDeclined(String groupId, String inviter, String reason) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(reason); invitationInfo.setGroup(new GroupInfo(groupId, groupId, inviter)); invitationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_INVITE_DECLINED); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onUserRemoved(String groupId, String groupName) { } @Override public void onGroupDestroyed(String groupId, String groupName) { } @Override public void onAutoAcceptInvitationFromGroup(String groupId, String inviter, String inviteMessage) { InvationInfo invitationInfo = new InvationInfo(); invitationInfo.setReason(inviteMessage); invitationInfo.setGroup(new GroupInfo(groupId, groupId, inviter)); invitationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_INVITE_ACCEPTED); Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo); SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true); mLocalBroadcastManager.sendBroadcast(new Intent(Constant.GROUP_INVITE_CHANGED)); } @Override public void onMuteListAdded(String s, List<String> list, long l) { } @Override public void onMuteListRemoved(String s, List<String> list) { } @Override public void onAdminAdded(String s, String s1) { } @Override public void onAdminRemoved(String s, String s1) { } @Override public void onOwnerChanged(String s, String s1, String s2) { } @Override public void onMemberJoined(String s, String s1) { } @Override public void onMemberExited(String s, String s1) { } }; }
package com.veyndan.paper.reddit.util; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import rx.Observable; public abstract class Node<T> { @IntRange(from = 0) private int depth; @NonNull private Observable<Boolean> trigger = Observable.empty(); @NonNull private Observable<T> request = Observable.empty(); @IntRange(from = 0) public int getDepth() { return depth; } public void setDepth(@IntRange(from = 0) final int depth) { this.depth = depth; } @NonNull public abstract Observable<Node<T>> getChildren(); @NonNull public Observable<Boolean> getTrigger() { return trigger; } public void setTrigger(@NonNull final Observable<Boolean> trigger) { this.trigger = trigger; } @NonNull public Observable<T> getRequest() { return request; } public void setRequest(@NonNull final Observable<T> request) { this.request = request; } @NonNull public abstract Observable<Node<T>> asObservable(); }
package com.zhang.videoplayer; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.MediaController; import android.widget.SeekBar; import android.widget.TextView; import com.zhang.videoplayer.Adapter.RecyclerViewAdapter; import com.zhang.videoplayer.util.Utility; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; public class PlayActivity extends AppCompatActivity implements View.OnClickListener{ Handler mHandler = new Handler(); Timer mTimer; Button mPauseButton,mStopButton; SurfaceView mSurfaceView; TextView mTotalTime,mCurrentTime; SeekBar mSeekBar; MediaPlayer mMediaPlayer; int mPosition =0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play); //Intent mPosition = getIntent().getIntExtra(RecyclerViewAdapter.EXTRA_POSITION,0); //View initView(); mMediaPlayer = new MediaPlayer(); //mediaPlayer mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mMediaPlayer.start(); mTotalTime.setText(change(mMediaPlayer.getDuration()/1000)); //handler mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { final int currentTime = mMediaPlayer.getCurrentPosition(); mHandler.post(new Runnable() { @Override public void run() { mCurrentTime.setText(change(currentTime/1000)); } }); } },0,1000); } }); //surfaceViewHolder SurfaceHolder surfaceholder = mSurfaceView.getHolder(); surfaceholder.setKeepScreenOn(true); surfaceholder.addCallback(new SurfaceListener()); } private void initView() { mSeekBar = (SeekBar)findViewById(R.id.play_seekBar); mTotalTime =(TextView)findViewById(R.id.play_totalTime); mCurrentTime = (TextView)findViewById(R.id.play_currentTime); mStopButton = (Button)findViewById(R.id.player_stop); mPauseButton = (Button)findViewById(R.id.player_pause); mSurfaceView = (SurfaceView)findViewById(R.id.play_surfaceView); mPauseButton.setOnClickListener(this); mStopButton.setOnClickListener(this); //seekBar mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.player_pause: if(mMediaPlayer.isPlaying()){ mMediaPlayer.pause(); }else{ mMediaPlayer.start(); } break; case R.id.player_stop: if(mMediaPlayer.isPlaying()){ mMediaPlayer.stop(); } break; } } private class SurfaceListener implements SurfaceHolder.Callback{ @Override public void surfaceCreated(SurfaceHolder holder) { mMediaPlayer.setDisplay(mSurfaceView.getHolder()); try { mMediaPlayer.setDataSource(PlayActivity.this,Uri.parse(Utility.sVideos.get(mPosition).getPlayUri())); } catch (IOException e) { e.printStackTrace(); } //preperAsync()preper()ANR mMediaPlayer.prepareAsync(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { //cancleondestoysurfaceDedtroyed if(mTimer != null){ mTimer.cancel(); } } } @Override protected void onPause() { if(mMediaPlayer.isPlaying()){ mMediaPlayer.stop(); } super.onPause(); } @Override protected void onDestroy() { if(mMediaPlayer.isPlaying()){ mMediaPlayer.stop(); } mMediaPlayer.release(); super.onDestroy(); } /** * * @param second * @return */ public static String change(int second) { int hh = second/3600; int mm = second%3600/60; int ss = second%60; String str = null; if(hh != 0){ str=String.format("%02d:%02d:%02d",hh,mm,ss); }else{ str=String.format("%02d:%02d",mm,ss); } return str; } }
package fr.ydelouis.selfoss.entity; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.apache.commons.lang3.StringEscapeUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.TimeZone; import fr.ydelouis.selfoss.model.ArticleDao; @DatabaseTable(daoClass = ArticleDao.class) @JsonIgnoreProperties(ignoreUnknown = true) public class Article implements Parcelable { private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static { DATETIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } @DatabaseField(id = true, columnName = ArticleDao.COLUMN_ID) private int id; @DatabaseField(columnName = ArticleDao.COLUMN_DATETIME) private long dateTime; @DatabaseField private String title; @DatabaseField private String content; @DatabaseField(columnName = ArticleDao.COLUMN_UNREAD) private boolean unread; @DatabaseField(columnName = ArticleDao.COLUMN_STARRED) private boolean starred; @DatabaseField(columnName = ArticleDao.COLUMN_SOURCE_ID) private int sourceId; @DatabaseField private String thumbnail; @DatabaseField private String icon; @DatabaseField private String uid; @DatabaseField private String link; @DatabaseField @JsonProperty("sourcetitle") private String sourceTitle; @DatabaseField(columnName = ArticleDao.COLUMN_TAGS) private String tags; public Article() { } @JsonProperty("id") public void setId(Object id) { if (id instanceof Number) { this.id = (Integer) id; } else if (id instanceof String) { this.id = Integer.valueOf((String) id); } } @JsonProperty("datetime") public void setDateTime(String dateTimeStr) throws ParseException { dateTime = DATETIME_FORMAT.parse(dateTimeStr).getTime(); } @JsonProperty("unread") public void setUnread(Object unread) { if (unread instanceof Boolean) { this.unread = (Boolean) unread; } else if (unread instanceof String) { this.unread = "1".equals(unread); } } @JsonProperty("starred") public void setStarred(Object starred) { if (starred instanceof Boolean) { this.starred = (Boolean) starred; } else if (starred instanceof String) { this.starred = "1".equals(starred); } } @JsonProperty("source") public void setSourceId(Object sourceId) { if (sourceId instanceof Number) { this.sourceId = (Integer) sourceId; } else if (sourceId instanceof String) { this.sourceId = Integer.valueOf((String) sourceId); } } public int getId() { return Math.abs(id); } public void setId(int id) { this.id = id; } public long getDateTime() { return dateTime; } public void setDateTime(long dateTime) { this.dateTime = dateTime; } public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = StringEscapeUtils.unescapeHtml4(title); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public boolean isUnread() { return unread; } public void setUnread(boolean unread) { this.unread = unread; } public boolean isStarred() { return starred; } public void setStarred(boolean starred) { this.starred = starred; } public int getSourceId() { return sourceId; } public void setSourceId(int sourceId) { this.sourceId = sourceId; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public boolean hasIcon() { return icon != null && !icon.isEmpty(); } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getSourceTitle() { return sourceTitle; } public void setSourceTitle(String sourceTitle) { this.sourceTitle = sourceTitle; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public boolean isCached() { return id < 0; } public void setCached(boolean cached) { if (cached) { this.id = - getId(); } else { this.id = getId(); } } @Override public boolean equals(Object o) { if (!(o instanceof Article)) return false; return getId() == ((Article) o).getId(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeLong(this.dateTime); dest.writeString(this.title); dest.writeString(this.content); dest.writeByte(unread ? (byte) 1 : (byte) 0); dest.writeByte(starred ? (byte) 1 : (byte) 0); dest.writeInt(this.sourceId); dest.writeString(this.thumbnail); dest.writeString(this.icon); dest.writeString(this.uid); dest.writeString(this.link); dest.writeString(this.sourceTitle); dest.writeString(this.tags); } private Article(Parcel in) { this.id = in.readInt(); this.dateTime = in.readLong(); this.title = in.readString(); this.content = in.readString(); this.unread = in.readByte() != 0; this.starred = in.readByte() != 0; this.sourceId = in.readInt(); this.thumbnail = in.readString(); this.icon = in.readString(); this.uid = in.readString(); this.link = in.readString(); this.sourceTitle = in.readString(); this.tags = in.readString(); } public static Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() { public Article createFromParcel(Parcel source) { return new Article(source); } public Article[] newArray(int size) { return new Article[size]; } }; }
package io.scrollback.app; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GcmIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GcmIntentService() { super("GcmIntentService"); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM * will be extended in the future with new message types, just ignore * any message types you're not interested in, or that you don't * recognize. */ if (GoogleCloudMessaging. MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Log.i("GCM Error", "Send error: " + extras.toString()); } else if (GoogleCloudMessaging. MESSAGE_TYPE_DELETED.equals(messageType)) { Log.i("GCM Error", "Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging. MESSAGE_TYPE_MESSAGE.equals(messageType)) { Log.d("gcm_payload", extras.toString()); Log.d("gcm_title", extras.getString("title", "default title")); Log.d("gcm_subtitle", extras.getString("subtitle", "default message")); Log.d("gcm_path", extras.getString("path", "default message")); Notification notif = new Notification(); notif.setTitle(extras.getString("title", "default")); notif.setMessage(extras.getString("subtitle", "default message")); notif.setPath("/"+extras.getString("path", "me")); // Post notification of received message. sendNotification(notif); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GCMBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(Notification n) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent i = new Intent(this, MainActivity.class); i.putExtra("scrollback_path", n.getPath()); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(n.getTitle()) .setStyle(new NotificationCompat.BigTextStyle() .bigText(n.getMessage())) .setContentText(n.getMessage()); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
package it.unical.mat.embasp.asp; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class ASPMapper { private static ASPMapper mapper; private Map<String,Class<?>> predicateClass; private Map<Class, Map<String,Method>> classSetterMethod; private ASPMapper(){ predicateClass = new HashMap<>(); classSetterMethod = new HashMap<>(); } public static ASPMapper getInstance(){ if(mapper == null){ mapper = new ASPMapper(); } return mapper; } public Class<?> getClass(String predicate){ return predicateClass.get(predicate); } public String getString(Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalTermException { String predicate=registerClass(obj.getClass()); String atom=predicate+"("; HashMap<Integer, Object> mapTerm=new HashMap<>(); for(Field field:obj.getClass().getDeclaredFields()){ if(field.isAnnotationPresent(Term.class)){ Object value=obj.getClass().getMethod("get"+ Character.toUpperCase(field.getName().charAt(0))+field.getName().substring(1)).invoke(obj); mapTerm.put(field.getAnnotation(Term.class).value(), value); } } for(int i=0;i<mapTerm.size();i++){ if(i!=0) atom+=","; Object objectTerm=mapTerm.get(i); if(objectTerm==null)throw new IllegalTermException("Wrong term number of class "+obj.getClass().getName()); if(objectTerm instanceof Integer){ atom+=objectTerm+""; }else atom+="\""+objectTerm.toString()+"\""; } atom+=")"; return atom; } public Object getObject(String atom) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException { // TODO String predicate; int indexOf=atom.indexOf("("); if(indexOf==-1) { //Arity 0 predicate = atom; }else predicate=atom.substring(0,(atom.indexOf("("))); Class<?> cl=getClass(predicate); // Not exist mapping between the predicate and the class if(cl==null)return null; Object obj=cl.newInstance(); //Term with arity 0 return obj if(indexOf==-1) return obj; //FIXME Not work with "a("asd,"). fix the split String[] paramiter=atom.substring(atom.indexOf("(")+1, atom.lastIndexOf(")")).split(","); for(Field field:cl.getDeclaredFields()){ if(field.isAnnotationPresent(Term.class)){ int term=field.getAnnotation(Term.class).value(); String nameMethod="set"+ Character.toUpperCase(field.getName().charAt(0))+field.getName().substring(1); Method method=classSetterMethod.get(cl).get(nameMethod); if(method.getParameterTypes()[0].getName().equals(int.class.getName()) || method.getParameterTypes()[0].getName().equals(Integer.class.getName())) method.invoke(obj, Integer.valueOf(paramiter[term])); else method.invoke(obj, paramiter[term]); } } return obj; } }
package org.chaos.fx.cnbeta.net; import org.chaos.fx.cnbeta.net.model.ArticleSummary; import org.chaos.fx.cnbeta.net.model.Comment; import org.chaos.fx.cnbeta.net.model.HotComment; import org.chaos.fx.cnbeta.net.model.NewsContent; import org.chaos.fx.cnbeta.net.model.Topic; import java.util.List; import retrofit.Call; /** * @author Chaos * 2015/11/03. */ public class CnBetaUtil { public static String getTypeString(int type) { return type == CnBetaApi.TYPE_COMMENTS ? "comments" : type == CnBetaApi.TYPE_COUNTER ? "counter" : "dig"; } public static Call<CnBetaApi.Result<List<ArticleSummary>>> articles(CnBetaApi api) { long timestamp = System.currentTimeMillis(); return api.articles(timestamp, CnBetaSignUtil.articlesSign(timestamp)); } Call<CnBetaApi.Result<List<ArticleSummary>>> topicArticles(CnBetaApi api, String topicId) { long timestamp = System.currentTimeMillis(); return api.topicArticles( timestamp, CnBetaSignUtil.topicArticlesSign(timestamp, topicId), topicId); } Call<CnBetaApi.Result<List<ArticleSummary>>> newArticles(CnBetaApi api, String topicId, String startSid) { long timestamp = System.currentTimeMillis(); return api.newArticles( timestamp, CnBetaSignUtil.newArticlesSign(timestamp, topicId, startSid), topicId, startSid); } Call<CnBetaApi.Result<List<ArticleSummary>>> oldArticles(CnBetaApi api, String topicId, String endSid) { long timestamp = System.currentTimeMillis(); return api.oldArticles( timestamp, CnBetaSignUtil.oldArticlesSign(timestamp, topicId, endSid), topicId, endSid); } Call<CnBetaApi.Result<NewsContent>> articleContent(CnBetaApi api, String sid) { long timestamp = System.currentTimeMillis(); return api.articleContent( timestamp, CnBetaSignUtil.articleContentSign(timestamp, sid), sid); } Call<CnBetaApi.Result<List<Comment>>> comments(CnBetaApi api, String sid, int page) { long timestamp = System.currentTimeMillis(); return api.comments( timestamp, CnBetaSignUtil.commentsSign(timestamp, sid, page), sid, page); } Call<CnBetaApi.Result<Object>> addComment(CnBetaApi api, String sid, String content) { long timestamp = System.currentTimeMillis(); return api.addComment( timestamp, CnBetaSignUtil.addCommentSign(timestamp, sid, content), sid, content); } Call<CnBetaApi.Result<Object>> replyComment(CnBetaApi api, String sid, String pid, String content) { long timestamp = System.currentTimeMillis(); return api.replyComment( timestamp, CnBetaSignUtil.replyCommentSign(timestamp, sid, pid, content), sid, pid, content); } Call<CnBetaApi.Result<String>> supportComment(CnBetaApi api, String sid) { long timestamp = System.currentTimeMillis(); return api.supportComment( timestamp, CnBetaSignUtil.supportCommentSign(timestamp, sid), sid); } Call<CnBetaApi.Result<String>> againstComment(CnBetaApi api, String sid) { long timestamp = System.currentTimeMillis(); return api.againstComment( timestamp, CnBetaSignUtil.againstCommentSign(timestamp, sid), sid); } Call<CnBetaApi.Result<List<HotComment>>> hotComment(CnBetaApi api) { long timestamp = System.currentTimeMillis(); return api.hotComment(timestamp, CnBetaSignUtil.hotCommentSign(timestamp)); } Call<CnBetaApi.Result<List<ArticleSummary>>> todayRank(CnBetaApi api, String type) { long timestamp = System.currentTimeMillis(); return api.todayRank( timestamp, CnBetaSignUtil.todayRankSign(timestamp, type), type); } Call<CnBetaApi.Result<List<ArticleSummary>>> top10(CnBetaApi api) { long timestamp = System.currentTimeMillis(); return api.top10(timestamp, CnBetaSignUtil.top10Sign(timestamp)); } Call<CnBetaApi.Result<List<Topic>>> topics(CnBetaApi api) { long timestamp = System.currentTimeMillis(); return api.topics(timestamp, CnBetaSignUtil.topicsSign(timestamp)); } }
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; public class Background { Bitmap bitmap; int x, y, dy; public Background(Bitmap bmp){ bitmap = bmp; x = 0; y = 0; dy = GamePanel.speed; } public void draw(Canvas canvas){ if(canvas != null) canvas.drawBitmap(bitmap, x, y, null); if(y > 0) canvas.drawBitmap(bitmap, x, y-1400, null); } public void update(){ y+=dy; if(y > 1400) { y = 0; GamePanel.speed += 1; } } }
package com.me.mylolgame; // TODO: Separate Controls into Inputs and Outputs // TODO: replace flipped hack with forward and backward animations // TODO: add a way to have multiple screens in the introduction to a level // TODO: should we have multiple GestureActions for a level, e.g., to handle multiple flings? // TODO: programatically pause/unpause timers? // TODO: add a moveDirectional button that takes an angle and a velocity? // TODO: make sure all angles use same untis (degrees or radians) // TODO: Add obstacle/obstacle, enemy/enemy, and */SVG callbacks // TODO: better truck demo? // TODO: clean up 87 and 88 // TODO: scale x and y of backgrounds import com.badlogic.gdx.math.Vector2; import edu.lehigh.cse.lol.Animation; import edu.lehigh.cse.lol.Background; import edu.lehigh.cse.lol.ChooserConfiguration; import edu.lehigh.cse.lol.Controls; import edu.lehigh.cse.lol.Destination; import edu.lehigh.cse.lol.Enemy; import edu.lehigh.cse.lol.Facts; import edu.lehigh.cse.lol.Goodie; import edu.lehigh.cse.lol.HelpLevel; import edu.lehigh.cse.lol.Hero; import edu.lehigh.cse.lol.Level; import edu.lehigh.cse.lol.Lol; import edu.lehigh.cse.lol.LolConfiguration; import edu.lehigh.cse.lol.Media; import edu.lehigh.cse.lol.Obstacle; import edu.lehigh.cse.lol.PauseScene; import edu.lehigh.cse.lol.Physics; import edu.lehigh.cse.lol.PhysicsSprite; import edu.lehigh.cse.lol.PostScene; import edu.lehigh.cse.lol.PreScene; import edu.lehigh.cse.lol.Projectile; import edu.lehigh.cse.lol.ProjectilePool; import edu.lehigh.cse.lol.Route; import edu.lehigh.cse.lol.Score; import edu.lehigh.cse.lol.Splash; import edu.lehigh.cse.lol.Svg; import edu.lehigh.cse.lol.Tilt; import edu.lehigh.cse.lol.Util; public class MyLolGame extends Lol { /** * Configure all the images and sounds used by our game */ @Override public void nameResources() { // load regular (non-animated) images Media.registerImage("greenball.png"); Media.registerImage("mustardball.png"); Media.registerImage("red.png"); Media.registerImage("leftarrow.png"); Media.registerImage("rightarrow.png"); Media.registerImage("backarrow.png"); Media.registerImage("redball.png"); Media.registerImage("blueball.png"); Media.registerImage("purpleball.png"); Media.registerImage("msg1.png"); Media.registerImage("msg2.png"); Media.registerImage("fade.png"); Media.registerImage("greyball.png"); Media.registerImage("leveltile.png"); Media.registerImage("audio_on.png"); Media.registerImage("audio_off.png"); // load the image we show on the main screen Media.registerImage("splash.png"); // load the image we show on the chooser screen Media.registerImage("chooser.png"); // load background images Media.registerImage("mid.png"); Media.registerImage("front.png"); Media.registerImage("back.png"); // load animated images (a.k.a. Sprite Sheets) Media.registerAnimatableImage("stars.png", 8, 1); Media.registerAnimatableImage("flystar.png", 2, 1); Media.registerAnimatableImage("starburst.png", 4, 1); Media.registerAnimatableImage("colorstar.png", 8, 1); // load sounds Media.registerSound("hipitch.ogg"); Media.registerSound("lowpitch.ogg"); Media.registerSound("losesound.ogg"); Media.registerSound("slowdown.ogg"); Media.registerSound("woowoowoo.ogg"); Media.registerSound("fwapfwap.ogg"); Media.registerSound("winsound.ogg"); // load background music Media.registerMusic("tune.ogg", true); } /** * Describe how to draw the first scene that displays when the game app is * started */ @Override public void configureSplash() { // Describe the regions of the screen that correspond to the play, help, // quit, and mute buttons. If you are having trouble figuring these out, // note that clicking on the splash screen will display xy coordinates // in the Console to help Splash.drawPlayButton(192, 91, 93, 52); Splash.drawHelpButton(48, 93, 80, 40); Splash.drawQuitButton(363, 93, 69, 39); Splash.drawMuteButton(455, 0, 25, 26, "audio_on.png", "audio_off.png"); // Provide a name for the background image Splash.setBackground("splash.png"); // Provide a name for the music file Splash.setMusic("tune.ogg"); } /** * Describe how to draw the initial state of each level of our game * * @param whichLevel * The level to be drawn */ @Override public void configureLevel(int whichLevel) { /* * In this level, all we have is a hero (the green ball) who needs to * make it to the destination (a mustard colored ball). The game is * configured to use tilt to control the hero. */ if (whichLevel == 1) { // set the screen to 48 meters wide by 32 meters high... this is // important, because Config.java says the screen is 480x320, and // LOL likes a 10:1 pixel to meter ratio. If we went smaller than // 48x32, things would get really weird. And, of course, if you make // your screen resolution higher in Config.java, these numbers would // need to get bigger. // Level.configure MUST BE THE FIRST LINE WHEN DRAWING A LEVEL!!! Level.configure(48, 32); // there is no default gravitational force Physics.configure(0, 0); // in this level, we'll use tilt to move some things around. The // maximum force that tilt can exert on anything is +/- 10 in the X // dimension, and +/- 10 in the Y dimension Tilt.enable(10, 10); // now let's create a hero, and indicate that the hero can move by // tilting the phone. "greenball.png" must be registered in // the registerMedia() method, which is also in this file. It must // also be in your android game's assets folder. Hero h = Hero.makeAsCircle(4, 17, 3, 3, "greenball.png"); h.setMoveByTilting(); // draw a circular destination, and indicate that the level is won // when the hero reaches the destination. "mustardball.png" must be // registered in registerMedia() Destination.makeAsCircle(29, 26, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); } /* * In this level, we make the play a bit smoother by adding a bounding * box and changing the way that LibLOL interacts with the player */ else if (whichLevel == 2) { // start by setting everything up just like in level 1 Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Hero h = Hero.makeAsCircle(4, 17, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 26, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // add a bounding box so the hero can't fall off the screen Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 0); // change the text that we display when the level is won PostScene.setDefaultWinText("Good job!"); // add a pop-up message that shows for one second at the // beginning of the level. The '50, 50' indicates the bottom left // corner of the text we display. 255,255,255 represents the red, // green, and blue components of the text color (the color will be // white). We'll write our text in the Arial font, with a size of 32 // pt. The "\n" in the middle of the text causes a line break. Note // that "arial.ttf" must be in your android game's assets folder. PreScene.addText("Reach the destination\nto win this level.", 50, 50, 255, 255, 255, "arial.ttf", 32); } /* * In this level, we change the physics from level 2 so that things roll * and bounce a little bit more nicely. */ else if (whichLevel == 3) { // These lines should be familiar after the last two levels Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // give the hero some density and friction, so that it can roll when // it encounters a wall... notice that once it has density, it has // mass, and it moves a lot slower... h.setPhysics(1, 0, 0.6f); // the bounding box now also has nonzero density, elasticity, and // friction... you should check out what happens if the friction // stays at 0. Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // Let's draw our message in the center of the screen this time PreScene.addText("Reach the destination\nto win this level.", 255, 255, 255, "arial.ttf", 32); // And let's say that instead of touching the message to make it go // away, we'll have it go away automatically after 2 seconds PreScene.setExpire(2); // Note that we're going back to the default PostScene text... } /* * It's confusing to have multiple heroes in a level, but we can... this * shows how to have multiple destinations and heroes */ else if (whichLevel == 4) { // standard stuff... Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // now let's draw two heroes who can both move by tilting, and // who both have density and friction. Note that we lower the // density, so they move faster Hero h1 = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h1.setPhysics(.1f, 0, 0.6f); h1.setMoveByTilting(); Hero h2 = Hero.makeAsCircle(14, 7, 3, 3, "greenball.png"); h2.setPhysics(.1f, 0, 0.6f); h2.setMoveByTilting(); // notice that now we will make two destinations, each of which // defaults to only holding ONE hero, but we still need to get two // heroes to destinations in order to complete the level Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Destination.makeAsCircle(29, 26, 2, 2, "mustardball.png"); Score.setVictoryDestination(2); // Let's show msg1.png instead of text. Note that we had to // register it in registerMedia(), and that we're stretching it // slightly, since its dimensions are 460x320 PreScene.addImage("msg1.png", 0, 0, 480, 320); } /* * This level demonstrates that we can have many heroes that can reach * the same destination. It also shows our first sound effect */ else if (whichLevel == 5) { // standard stuff... Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h1 = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h1.setPhysics(.1f, 0, 0.6f); h1.setMoveByTilting(); Hero h2 = Hero.makeAsCircle(14, 7, 3, 3, "greenball.png"); h2.setPhysics(.1f, 0, 0.6f); h2.setMoveByTilting(); PreScene.addText("All heroes must\nreach the destination", 255, 255, 255, "arial.ttf", 32); // now let's make a destination, but indicate that it can hold TWO // heroes Destination d = Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); d.setHeroCount(2); // let's also say that whenever a hero reaches the destination, a // sound will play d.setArrivalSound("hipitch.ogg"); // Notice that this line didn't change from level 4 Score.setVictoryDestination(2); } /* * Tilt can be used to control velocity, instead of applying forces to * the entities on the screen. It doesn't always work well, but it's a * nice option to have... */ else if (whichLevel == 6) { // standard stuff... Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); PreScene.addText("A different way\nto use tilt.", 255, 255, 255, "arial.ttf", 32); // change the behavior or tilt Tilt.setAsVelocity(true); } /* * This level adds an enemy, to demonstrate that we can make it possible * to lose a level */ else if (whichLevel == 7) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // Notice that we changed the font size and color PreScene.addText("Avoid the enemy and\nreach the destination", 25, 255, 255, "arial.ttf", 20); // draw an enemy... we don't need to give it physics for now... Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); // turn off the postscene... whether the player wins or loses, we'll // just start the appropriate level. Be sure to test the game by // losing *and* winning! PostScene.disable(); } /* * This level explores a bit more of what we can do with enemies, by * having an enemy with a fixed path. */ else if (whichLevel == 8) { // configure a basic level, just like the start of level 2: Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 27, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); PreScene.addText("Avoid the enemy and\nreach the destination", 255, 255, 255, "arial.ttf", 20); // put some extra text on the PreScene PreScene.addText("(the enemy is red)", 5, 5, 50, 200, 122, "arial.ttf", 10); // draw an enemy Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); // attach a path to the enemy. It starts at (25, 25) and moves to // (25, 2). This means it has *2* points on its route. Notice that // since it loops, it is not going to gracefully move back to its // starting point. Also note that the first point is the same as the // enemy's original position. If it wasn't, then there would be an // odd glitch at the beginning of the level. e.setRoute(new Route(2).to(25, 25).to(25, 2), 10, true); // Note that when the level is lost, the default lose text will be // displayed on a PostScene } /* * This level explores a bit more of what we can do with paths. */ else if (whichLevel == 9) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); PreScene.addText("Avoid the enemy and\nreach the destination", 50, 50, 255, 255, 255, "arial.ttf", 20); // draw an enemy that can move Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); // This time, we add a third point, which is the same as the // starting point. This will give us a nicer sort of movement. Also // note the diagonal movement. e.setRoute(new Route(3).to(25, 25).to(12, 2).to(25, 25), 2, true); // note that any number of points is possible... you could have // extremely complex Routes! } /* * We can make enemies move via tilt. We can also configure some other * kinds of sounds */ else if (whichLevel == 10) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(0.1f, 0, 0.6f); h.setMoveByTilting(); PreScene.addImage("msg2.png", 10, 10, 460, 320); // let's make the destination rotate: Destination d = Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); d.setRotationSpeed(1); Score.setVictoryDestination(1); // draw an enemy who moves via tilt Enemy e3 = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e3.setPhysics(1.0f, 0.3f, 0.6f); e3.setMoveByTilting(); // configure some sounds to play on win and lose. Of course, all // these sounds must be registered! PostScene.setWinSound("winsound.ogg"); PostScene.setLoseSound("losesound.ogg"); // set background music Level.setMusic("tune.ogg"); // custom text for when the level is lost PostScene.setDefaultLoseText("Better luck next time..."); } /* * This shows that it is possible to make a level that is larger than a * screen. It also shows that there is a "heads up display" that can be * used for providing information and touchable controls */ else if (whichLevel == 11) { // make the level really big Level.configure(400, 300); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 400, 300, "red.png", 0, 0, 0); // put the hero and destination far apart Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(329, 281, 10, 10, "mustardball.png"); Score.setVictoryDestination(1); // We want to be sure that no matter what, the player can see the // hero. We achieve this by having the camera follow the hero: Level.setCameraChase(h); // add zoom buttons. We are using blank images, which means that the // buttons will be invisible... that's nice, because we can make the // buttons big (covering the left and right halves of the screen). // When debug rendering is turned on, we'll be able to see a red // outline of the two rectangles. You could also use images (that // you registered, of course), but if you did, you'd either need to // make them small, or make them semi-transparent. Controls.addZoomOutButton(0, 0, 240, 320, "", 8); Controls.addZoomInButton(240, 0, 240, 320, "", .25f); PreScene.addText("Press left to zoom out\nright to zoom in", 255, 255, 255, "arial.ttf", 32); } /* * this level introduces obstacles, and also shows the difference * between "box" and "circle" physics */ else if (whichLevel == 12) { // configure a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // add a hero and destination Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // let's draw an obstacle whose underlying shape is a box, but whose // picture is a circle. This can be odd... our hero can roll around // an invisible corner on this obstacle. When debug rendering is // turned on (in Config.java), you'll be able to see the true shape // of the obstacle. Obstacle o1 = Obstacle.makeAsBox(0, 0, 3.5f, 3.5f, "purpleball.png"); o1.setPhysics(1, 0, 1); // now let's draw an obstacle whose shape and picture are both // circles. The hero rolls around this nicely. Obstacle o2 = Obstacle.makeAsCircle(10, 10, 3.5f, 3.5f, "purpleball.png"); o2.setPhysics(1, 0, 1); // draw a wall using circle physics and a stretched rectangular // picture. This wall will do really funny things Obstacle o3 = Obstacle.makeAsCircle(20, 25, 6, 0.5f, "red.png"); o3.setPhysics(1, 0, 1); // draw a rectangular wall the right way, as a box Obstacle o4 = Obstacle.makeAsBox(34, 2, 0.5f, 20, "red.png"); o4.setPhysics(1, 0, 1); PreScene.addText("An obstacle's appearance may\nnot match its physics", 255, 255, 255, "arial.ttf", 32); } /* * this level just plays around with physics a little bit, to show how * friction and elasticity can do interesting things. */ else if (whichLevel == 13) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("These obstacles have\ndifferent physics\nparameters", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // Colliding the hero with these obstacles can have interesting // effects Obstacle o1 = Obstacle.makeAsCircle(0, 0, 3.5f, 3.5f, "purpleball.png"); o1.setPhysics(0, 100, 0); Obstacle o2 = Obstacle.makeAsCircle(10, 10, 3.5f, 3.5f, "purpleball.png"); o2.setPhysics(10, 0, 100); } /* * This level introduces goodies. Goodies are something that we collect. * We can make the collection of goodies lead to changes in the behavior * of the game, and in this example, the collection of goodies "enables" * a destination. */ else if (whichLevel == 14) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); PreScene.addText("You must collect\ntwo blue balls", 255, 255, 255, "arial.ttf", 32); // Add some stationary goodies. Note that the default is // for goodies to not cause a change in the hero's behavior at the // time when a collision occurs... this is often called being a // "sensor"... it means that collisions are still detected by the // code, but they don't cause changes in momentum // Note that LibLOL allows goodies to have one of 4 "types". By // default, collecting a goodie increases the "type 1" score by 1. Goodie.makeAsCircle(0, 30, 2, 2, "blueball.png"); Goodie.makeAsCircle(0, 15, 2, 2, "blueball.png"); // here we create a destination. Note that we now set its activation // score to 2, so that you must collect two goodies before the // destination will "work" Destination d = Destination.makeAsCircle(29, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // we must provide an activation score for each of the 4 types of // goodies d.setActivationScore(2, 0, 0, 0); // let's put a display on the screen to see how many type-1 goodies // we've collected. Since the second parameter is "2", we'll display // the count as "X/2 Goodies" instead of "X Goodies" Controls.addGoodieCount(1, 2, "Goodies", 220, 280, "arial.ttf", 255, 0, 255, 20); } /* * earlier, we saw that enemies could move along a Route. So can any * other entity, so we'll move destinations, goodies, and obstacles, * too. */ else if (whichLevel == 15) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Every entity can move...", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(44, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // make a destination that moves, and that requires one goodie to be // collected before it works Destination d = Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); d.setActivationScore(1, 0, 0, 0); d.setRoute(new Route(3).to(29, 6).to(29, 26).to(29, 6), 4, true); Score.setVictoryDestination(1); // make an obstacle that moves Obstacle o = Obstacle.makeAsBox(0, 0, 3.5f, 3.5f, "purpleball.png"); o.setPhysics(0, 100, 0); o.setRoute(new Route(3).to(0, 0).to(10, 10).to(0, 0), 2, true); // make a goodie that moves Goodie g = Goodie.makeAsCircle(5, 5, 2, 2, "blueball.png"); g.setRoute(new Route(5).to(5, 5).to(5, 25).to(25, 25).to(9, 9).to(5, 5), 10, true); // draw a goodie counter in light blue (60, 70, 255) with a 12-point // font Controls.addGoodieCount(1, 0, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); } /* * Sometimes, we don't want a destination, we just want to say that the * player wins by collecting enough goodies. This level also shows that * we can set a time limit for the level, and we can pause the game. */ else if (whichLevel == 16) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Collect all\nblue balls\nto win", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 20, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // draw 5 goodies Goodie.makeAsCircle(.5f, .5f, 2, 2, "blueball.png"); Goodie.makeAsCircle(5.5f, 1.5f, 2, 2, "blueball.png"); Goodie.makeAsCircle(10.5f, 2.5f, 2, 2, "blueball.png"); Goodie.makeAsCircle(15.5f, 3.5f, 2, 2, "blueball.png"); Goodie.makeAsCircle(20.5f, 4.5f, 2, 2, "blueball.png"); // indicate that we win by collecting enough goodies Score.setVictoryGoodies(5, 0, 0, 0); // put the goodie count on the screen Controls.addGoodieCount(1, 5, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); // put a simple countdown on the screen Controls.addCountdown(15, "Time Up!", 400, 50); // let's also add a screen for pausing the game. In a real game, // every level should have a button for pausing the game, and the // pause scene should have a button for going back to the main // menu... we'll show how to do that later. PauseScene.addText("Game Paused", 255, 255, 255, "arial.ttf", 32); Controls.addPauseButton(0, 300, 20, 20, "red.png"); } /* * This level shows how "obstacles" need not actually impede the hero's * movement. Here, we attach "damping factors" to the hero, which let us * make the hero speed up or slow down based on interaction with the * obstacle. This level also adds a stopwatch. Stopwatches don't have * any meaning, but they are nice to have anyway... */ else if (whichLevel == 17) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Obstacles as zoom\nstrips, friction pads\nand repellers", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // add a stopwatch... note that there are two ways to add a // stopwatch, the other of which allows for configuring the font Controls.addStopwatch(50, 50); // Create a pause scene that has a back button on it, and a button // for pausing the level PauseScene.addText("Game Paused", 255, 255, 255, "arial.ttf", 32); PauseScene.addBackButton("red.png", 0, 300, 20, 20); Controls.addPauseButton(0, 300, 20, 20, "red.png"); // now draw three obstacles. Note that they have different dampening // factors. one important thing to notice is that since we place // these on the screen *after* we place the hero on the screen, the // hero will go *under* these things. // this obstacle's dampening factor means that on collision, the // hero's velocity is multiplied by -1... he bounces off at an // angle. Obstacle o = Obstacle.makeAsCircle(10, 10, 3.5f, 3.5f, "purpleball.png"); o.setDamp(-1); // this obstacle accelerates the hero... it's like a turbo booster o = Obstacle.makeAsCircle(20, 10, 3.5f, 3.5f, "purpleball.png"); o.setDamp(5); // this obstacle slows the hero down... it's like running on // sandpaper. Note that the hero only slows down on initial // collision, not while going under it. o = Obstacle.makeAsBox(30, 10, 3.5f, 3.5f, "purpleball.png"); o.setRotationSpeed(2); o.setDamp(0.2f); } /* * This level shows that it is possible to give heroes and enemies * different strengths, so that a hero doesn't disappear after a single * collision. It also shows that when an enemy defeats a hero, we can * customize the message that prints */ else if (whichLevel == 18) { // set up a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The hero can defeat \nup to two enemies...", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // draw a hero and give it strength of 10. The default is for // enemies to have "2" units of damage, and heroes to have "1" unit // of strength, so that any collision defeats the hero without // removing the enemy. Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); h.setStrength(10); // draw a strength meter to show this hero's strength Controls.addStrengthMeter("Strength", 220, 280, h); // our first enemy stands still: Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); e.setDamage(4); // this text will be displayed if this enemy defeats the hero e.setDefeatHeroText("How did you hit me?"); // our second enemy moves along a path e = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRoute(new Route(3).to(35, 25).to(15, 25).to(35, 25), 10, true); e.setDamage(4); e.setDefeatHeroText("Stay out of my way"); // our third enemy moves with tilt, which makes it hardest to avoid e = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e.setPhysics(.1f, 0.3f, 0.6f); e.setMoveByTilting(); e.setDamage(4); e.setDefeatHeroText("You can't hide!"); // be sure when testing this level to lose, with each enemy being // the last the hero collides with, so that you can see the // different messages } /* * This level shows that we can win a level by defeating all enemies */ else if (whichLevel == 19) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("You have 10 seconds\nto defeat the enemies", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // give the hero enough strength that this will work... Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setStrength(10); h.setMoveByTilting(); // draw a few enemies, and change their "damage" (the amount by // which they decrease the hero's strength) Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); e.setDamage(4); e = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e.setPhysics(.1f, 0.3f, 0.6f); e.setMoveByTilting(); e.setDamage(4); // put a countdown on the screen Controls.addCountdown(10, "Time Up!", 200, 25); // indicate that defeating all of the enemies is the way to win this // level Score.setVictoryEnemyCount(); } /* * This level shows that a goodie can change the hero's strength, and * that we can win by defeating a specific number of enemies, instead of * all enemies. */ else if (whichLevel == 20) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Collect blue balls\nto increse strength", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // our default hero only has "1" strength Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // our default enemy has "2" damage Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); e.setDisappearSound("slowdown.ogg"); // a second enemy e = Enemy.makeAsCircle(35, 15, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); // this goodie gives an extra "5" strength: Goodie g = Goodie.makeAsCircle(0, 30, 2, 2, "blueball.png"); g.setStrengthBoost(5); g.setDisappearSound("woowoowoo.ogg"); // Display the hero's strength Controls.addStrengthMeter("Strength", 220, 280, h); // win by defeating one enemy Score.setVictoryEnemyCount(1); PostScene.setDefaultWinText("Good enough..."); } /* * this level introduces the idea of invincibility. Collecting the * goodie makes the hero invincible for a little while... */ else if (whichLevel == 21) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The blue ball will\nmake you invincible\nfor 15 seconds", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // draw a few enemies, and make them rotate for (int i = 0; i < 5; ++i) { Enemy e = Enemy.makeAsCircle(5 * i + 1, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); } // this goodie makes us invincible Goodie g = Goodie.makeAsCircle(30, 30, 2, 2, "blueball.png"); g.setInvincibilityDuration(15); g.setRoute(new Route(3).to(30, 30).to(10, 10).to(30, 30), 5, true); g.setRotationSpeed(0.25f); // we'll still say you win by reaching the destination. Defeating // enemies is just for fun... Destination.makeAsCircle(29, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // display a goodie count for type-1 goodies Controls.addGoodieCount(1, 0, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); // put a frames-per-second display on the screen. This is going to // look funny, because when debug mode is set (in Config.java), a // FPS will be shown on every screen anyway Controls.addFPS(400, 15, "arial.ttf", 200, 200, 100, 12); } /* * Some goodies can "count" for more than one point... they can even * count for negative points. */ else if (whichLevel == 22) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Collect 'the right' \nblue balls to\nactivate destination", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination d = Destination.makeAsCircle(29, 1, 2, 2, "mustardball.png"); d.setActivationScore(7, 0, 0, 0); Score.setVictoryDestination(1); // create some goodies with special scores. Note that we're still // only dealing with type-1 scores Goodie g1 = Goodie.makeAsCircle(0, 30, 2, 2, "blueball.png"); g1.setScore(-2, 0, 0, 0); Goodie g2 = Goodie.makeAsCircle(0, 15, 2, 2, "blueball.png"); g2.setScore(7, 0, 0, 0); // create some regular goodies Goodie.makeAsCircle(30, 30, 2, 2, "blueball.png"); Goodie.makeAsCircle(35, 30, 2, 2, "blueball.png"); // print a goodie count to show how the count goes up and down Controls.addGoodieCount(1, 0, "Progress", 220, 280, "arial.ttf", 60, 70, 255, 12); } /* * this level demonstrates that we can drag entities (in this case, * obstacles), and that we can make rotated obstacles. The latter could * be useful for having angled walls in a maze */ else if (whichLevel == 23) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Rotating oblong obstacles\nand draggable obstacles", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // draw obstacles that we can drag Obstacle o = Obstacle.makeAsBox(0, 0, 3.5f, 3.5f, "purpleball.png"); o.setPhysics(0, 100, 0); o.setCanDrag(true); Obstacle o2 = Obstacle.makeAsBox(7, 0, 3.5f, 3.5f, "purpleball.png"); o2.setPhysics(0, 100, 0); o2.setCanDrag(true); // draw an obstacle that is oblong (due to its width and height) and // that is rotated. Note that this should be a box, or it will not // have the right underlying shape. o = Obstacle.makeAsBox(12, 12, 3.5f, .5f, "purpleball.png"); o.setRotation(45); } /* * this level shows how we can use "poking" to move obstacles. In this * case, pressing an obstacle selects it, and pressing the screen moves * the obstacle to that location. Double-tapping an obstacle removes it. */ else if (whichLevel == 24) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); PreScene.addText("Touch the obstacle\nto select, then" + "\ntouch to move it", 255, 255, 255, "arial.ttf", 32); // draw a picture on the default plane (0)... there are actually 5 // planes (-2 through 2). Everything drawn on the same plane will be // drawn in order, so if we don't put this before the hero, the hero // will appear to go "under" the picture. Util.drawPicture(0, 0, 48, 32, "greenball.png", 0); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a pokeable obstacle Obstacle o = Obstacle.makeAsBox(0, 0, 3.5f, 3.5f, "purpleball.png"); o.setPhysics(0, 100, 0); // '250' is a number of milliseconds. Two presses within 250 // milliseconds will cause this obstacle to disappear, forever. Make // the number 0 if you want it to never disappear due to // double-touch. o.setPokeToPlace(250); } /* * In this level, the enemy chases the hero */ else if (whichLevel == 25) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The enemy will chase you", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // create an enemy who chases the hero Enemy e3 = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e3.setPhysics(.1f, 0.3f, 0.6f); e3.setChaseSpeed(8, h, true, true); // draw a picture late within this block of code, but still cause // the picture to be drawn behind everything else by giving it a z // index of -1 Util.drawPicture(0, 0, 48, 32, "greenball.png", -2); // We can change the z-index of anything... let's move the enemy to // -2. Since we do this after drawing the picture, it will still be // drawn on top of the picture, but we should also be able to see it // go under the destination. e3.setZIndex(-2); } /* * We can make obstacles play sounds either when we collide with them, * or touch them */ else if (whichLevel == 26) { // set up a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Touch the purple ball \nor collide with it", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up our obstacle so that collision and touch make it play // sounds Obstacle o = Obstacle.makeAsCircle(10, 10, 3.5f, 3.5f, "purpleball.png"); o.setPhysics(1, 0, 1); o.setTouchSound("lowpitch.ogg"); o.setCollideSound("hipitch.ogg", 2000); } /* * this hero rotates so that it faces in the direction of movement. This * can be useful in games where the perspective is from overhead, and * the hero is moving in any X or Y direction */ else if (whichLevel == 27) { // set up a big screen Level.configure(4 * 48, 2 * 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The star rotates in\nthe direction of movement", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 4 * 48, 2 * 32, "red.png", 1, 0, 1); Destination.makeAsCircle(29, 60, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a hero who rotates in the direction of movement Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setRotationByDirection(); h.setMoveByTilting(); Level.setCameraChase(h); } /* * This level shows two things. The first is that a custom motion path * can allow things to violate the laws of physics and pass through * other things. The second is that motion paths can go off-screen. */ else if (whichLevel == 28) { // set up a regular level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Reach the destination\nto win the game.", 255, 255, 255, "arial.ttf", 20); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(21.5f, 29, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(21.5f, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // this enemy starts from off-screen Enemy e = Enemy.makeAsCircle(1, -20, 44, 44, "redball.png"); e.setDefeatHeroText("Ha Ha Ha"); e.setRoute(new Route(3).to(1, -90).to(1, 26).to(1, -20), 30, true); } /* * This level shows that we can draw on the screen to create obstacles. * In truth, you'll probably want to change the code for this a lot, but * at least you'll know where to start! */ else if (whichLevel == 29) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Draw on the screen\nto make obstacles appear", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(21.5f, 29, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(21.5f, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // turn on 'scribble mode'. Be sure to play with the last two // parameters Level.setScribbleMode("purpleball.png", 3, 1.5f, 1.5f, 0, 0, 0, true, 10); } /* * This level shows that we can "flick" things to move them. Notice that * we do not enable tilt! Instead, we specified that there is a default * gravity in the Y dimension pushing everything down. This is much like * gravity on earth. The only way to move things, then, is via flicking * them. */ else if (whichLevel == 30) { // create a level with a constant force downward in the Y dimension Level.configure(48, 32); Physics.configure(0, -10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(30, 10, 2.5f, 2.5f, "mustardball.png"); Score.setVictoryDestination(1); // create a hero who we can flick Hero h = Hero.makeAsCircle(4, 27, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setFlickable(1f); h.disableRotation(); } /* * this level introduces a new concept: side-scrolling games. Just like * in level 30, we have a constant force in the negative Y direction. * However, in this level, we say that tilt can produce forces in X but * not in Y. Thus we can tilt to move the hero left/right. Note, too, * that the hero will fall to the floor, since there is a constant * downward force, but there is not any mechanism to apply a Y force to * make it move back up. */ else if (whichLevel == 31) { // make a long level but not a tall level, and provide a constant // downward force: Level.configure(3 * 48, 32); Physics.configure(0, -10); // turn on tilt, but only in the X dimension Tilt.enable(10, 0); PreScene.addText("Side scroller / tilt demo", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Level.setCameraChase(h); } /* * In the previous level, it was hard to see that the hero was moving. * We can make a background layer to remedy this situation. Notice that * the background uses transparency to show the blue color for part of * the screen */ else if (whichLevel == 32) { // start by repeating the previous level: Level.configure(30 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Side scroller / tilt demo", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 30 * 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(30 * 48 - 5, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Level.setCameraChase(h); // now paint the background blue Background.setColor(23, 180, 255); // put in a picture that scrolls at half the speed of the hero in // the x direction. Note that background "layers" are all drawn // *before* anything that is drawn with a z index... so the // background will be behind the hero Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // make an obstacle that hovers in a fixed place. Note that hovering // and zoom do not work together nicely. Obstacle o = Obstacle.makeAsCircle(10, 10, 5, 5, "blueball.png"); o.setHover(100, 100); // Add a meter to show how far the hero has traveled Controls.addDistanceMeter(" m", 5, 300, "arial.ttf", 255, 255, 255, 16, h); // Add some text about the previous best score. If you look in the // onLevelCompleteCallback() code (far below in this file), you'll // see that when this level ends, we save the best score. Once the // score is saved, it is saved permanently on the phone, though // every re-execution on the desktop resets the best score. Util.drawText(30, 30, "best: " + Score.readPersistent("HighScore", 0) + "M", 0, 0, 0, "arial.ttf", 12, 0); } /* * this level adds multiple background layers, and it also allows the * hero to jump via touch */ else if (whichLevel == 33) { // set up a standard side scroller with tilt: Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press the hero to\nmake it jump", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a hero Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Level.setCameraChase(h); // this says that touching makes the hero jump h.setTouchToJump(); // this is the force of a jump. remember that up is positive. h.setJumpImpulses(0, 10); // the sound to play when we jump h.setJumpSound("fwapfwap.ogg"); // set up our background again, but add a few more layers Background.setColor(23, 180, 255); // this layer has a scroll factor of 0... it won't move Background.addHorizontalLayer(0, 1, "back.png", 0); // this layer moves at half the speed of the hero Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // this layer is faster than the hero Background.addHorizontalLayer(1.25f, 1, "front.png", 20); } /* * tilt doesn't always work so nicely in side scrollers. An alternative * is for the hero to have a fixed rate of motion. Another issue was * that you had to touch the hero itself to make it jump. Now, we use an * invisible button so touching any part of the screen makes the hero * jump. */ else if (whichLevel == 34) { // set up a side scroller, but don't turn on tilt Level.configure(3 * 48, 32); Physics.configure(0, -10); PreScene.addText("Press anywhere to jump", 255, 255, 255, "arial.ttf", 32); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // note: the bounding box does not have friction, and neither does // the hero Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 0, 0, 0); // make a hero, and ensure that it doesn't rotate Hero h = Hero.makeAsCircle(2, 0, 3, 7, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0); // give the hero a fixed velocity h.addVelocity(25, 0, false); // center the camera a little ahead of the hero, so he is not // centered h.setCameraOffset(15, 0); // enable jumping h.setJumpImpulses(0, 10); Level.setCameraChase(h); // set up the background Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // draw a jump button that covers the whole screen Controls.addJumpButton(0, 0, 480, 320, "", h); // if the hero jumps over the destination, we have a problem. To fix // it, let's put an invisible enemy right after the destination, so // that if the hero misses the destination, it hits the enemy and we // can start over. Of course, we could just do the destination like // this instead, but this is more fun... Enemy.makeAsBox(130, 0, .5f, 32, ""); } /* * the default is that once a hero jumps, it can't jump again until it * touches an obstacle (floor or wall). Here, we enable multiple jumps. * Coupled with a small jump impulse, this makes jumping feel more like * swimming or controlling a helicopter. */ else if (whichLevel == 35) { Level.configure(3 * 48, 38); Physics.configure(0, -10); PreScene.addText("Multi-jump is enabled", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 38, "red.png", 1, 0, 0); Hero h = Hero.makeAsBox(2, 0, 3, 7, "greenball.png"); h.disableRotation(); h.setPhysics(1, 0, 0); h.addVelocity(5, 0, false); Level.setCameraChase(h); h.setCameraOffset(15, 0); // the hero now has multijump, with small jumps: h.setMultiJumpOn(); h.setJumpImpulses(0, 6); // this is all the same as before, to include the invisible enemy Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); Controls.addJumpButton(0, 0, 480, 320, "", h); Destination.makeAsCircle(120, 31, 2, 2, "mustardball.png"); Enemy.makeAsBox(130, 0, .5f, 38, ""); Score.setVictoryDestination(1); } /* * This level shows that we can make a hero move based on how we touch * the screen */ else if (whichLevel == 36) { Level.configure(3 * 48, 32); Physics.configure(0, 0); PreScene.addText("Press screen borders\nto move the hero", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 0, 3, 3, "stars.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); Level.setCameraChase(h); // this lets the hero flip its image when it moves backwards h.setCanFaceBackwards(); Destination.makeAsCircle(120, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // let's draw an enemy, just in case anyone wants to try to go to // the top left corner Enemy.makeAsCircle(3, 27, 3, 3, "redball.png"); // draw some buttons for moving the hero Controls.addLeftButton(0, 50, 50, 220, "", 15, h); Controls.addRightButton(430, 50, 50, 220, "", 15, h); Controls.addUpButton(50, 270, 380, 50, "", 15, h); Controls.addDownButton(50, 0, 380, 50, "", 15, h); } /* * In the last level, we had complete control of the hero's movement. * Here, we give the hero a fixed velocity, and only control its up/down * movement. */ else if (whichLevel == 37) { Level.configure(3 * 48, 32); Physics.configure(0, 0); PreScene.addText("Press screen borders\nto move up and down", 255, 255, 255, "arial.ttf", 32); // The box and hero should not have friction Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 0); Destination.makeAsCircle(120, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0); h.addVelocity(10, 0, false); Level.setCameraChase(h); // draw an enemy to avoid, and one at the end Enemy.makeAsCircle(53, 28, 3, 3, "redball.png"); Enemy.makeAsBox(130, 0, .5f, 32, ""); // draw the up/down controls Controls.addDownButton(50, 0, 380, 50, "", 15, h); Controls.addUpButton(50, 270, 380, 50, "", 15, h); } /* * this level demonstrates crawling heroes. We can use this to simulate * crawling, ducking, rolling, spinning, etc. Note, too, that we can use * it to make the hero defeat certain enemies via crawl. */ else if (whichLevel == 38) { Level.configure(3 * 48, 32); Physics.configure(0, -10); PreScene.addText("Press the screen\nto crawl", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 0); Destination.makeAsCircle(120, 0, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Hero h = Hero.makeAsBox(2, 1, 3, 7, "greenball.png"); h.setPhysics(.1f, 0, 0); h.addVelocity(5, 0, false); Level.setCameraChase(h); // to enable crawling, we just draw a crawl button on the screen Controls.addCrawlButton(0, 0, 480, 320, "", h); // make an enemy who we can defeat by colliding with it while // crawling Enemy e = Enemy.makeAsCircle(110, 1, 5, 5, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setDefeatByCrawl(); } /* * We can make a hero start moving only when it is pressed. This can * even let the hero hover until it is pressed. We could also use this * to have a game where the player puts obstacles in place, then starts * the hero moving. */ else if (whichLevel == 39) { Level.configure(3 * 48, 32); Physics.configure(0, -10); PreScene.addText("Press the hero\nto start moving\n", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 0); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); Destination.makeAsCircle(120, 0, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a hero who doesn't start moving until it is touched // note that this hero is a box, and the hero is "norotate". You // will probably get strange behaviors if you choose any other // options Hero h = Hero.makeAsBox(2, 1, 3, 7, "greenball.png"); h.disableRotation(); h.setPhysics(1, 0, 0); h.setTouchAndGo(10, 0); Level.setCameraChase(h); } /* * LibLOL has limited support for SVG. If you draw a picture in Inkscape * or another SVG tool, and it only consists of lines, then you can * import it into your game as an obstacle. Drawing a picture on top of * the obstacle is probably a good idea, though we don't bother in this * level */ else if (whichLevel == 40) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); Tilt.setAsVelocity(true); PreScene.addText("Obstacles can\nbe drawn from SVG\nfiles", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 1); // make a hero who can jump Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setJumpImpulses(0, 20); h.setTouchToJump(); h.setMoveByTilting(); Level.setCameraChase(h); // draw an obstacle from SVG Svg.importLineDrawing("shape.svg", 1, 0, 0, 2f, .5f, 25f, 15f); // notice that we can only get to the destination by jumping from // *on top of* the obstacle Destination.makeAsCircle(120, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); } /* * In a side-scrolling game, it is useful to be able to change the * hero's speed either permanently or temporarily. In LibLOL, we can use * a collision between a hero and an obstacle to achieve this effect. */ else if (whichLevel == 41) { Level.configure(10 * 48, 32); Physics.configure(0, 0); PreScene.addText("Speed boosters and reducers", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 10 * 480, 320, "", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 0, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); h.addVelocity(10, 0, false); Level.setCameraChase(h); Destination.makeAsCircle(450, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // place a speed-up obstacle that lasts for 2 seconds Obstacle o1 = Obstacle.makeAsCircle(40, 1, 4, 4, "purpleball.png"); o1.setSpeedBoost(20, 0, 2); // place a slow-down obstacle that lasts for 3 seconds Obstacle o2 = Obstacle.makeAsCircle(120, 1, 4, 6, "purpleball.png"); o2.setSpeedBoost(-9, 0, 3); // place a permanent +3 speedup obstacle... the -1 means "forever" Obstacle o3 = Obstacle.makeAsCircle(240, 1, 4, 4, "purpleball.png"); o3.setSpeedBoost(20, 0, -1); } /* * this is a very gross level, which exists just to show that * backgrounds can scroll vertically. */ else if (whichLevel == 42) { // set up a level where tilt only makes the hero move up and down Level.configure(48, 4 * 32); Physics.configure(0, 0); Tilt.enable(0, 10); PreScene.addText("Vertical scroller demo", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 4 * 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 120, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Level.setCameraChase(h); Destination.makeAsBox(0, 2, 48, 1, "mustardball.png"); Score.setVictoryDestination(1); // set up vertical scrolling backgrounds Background.setColor(255, 0, 255); Background.addVerticalLayer(1, 0, "back.png", 0); Background.addVerticalLayer(1, .5f, "mid.png", 0); Background.addVerticalLayer(1, 1, "front.png", 0); } /* * the next few levels demonstrate support for throwing projectiles. In * this level, we throw projectiles by touching the hero. Here, the * projectile always goes in the same direction */ else if (whichLevel == 43) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Press the hero\nto make it throw\nprojectiles", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // create a hero, and indicate that touching it makes it throw // projectiles Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); // when the hero is touched, a projectile will // fly straight up, out of the top of the hero. h.setTouchToThrow(h, 1.5f, 3, 0, 10); h.setMoveByTilting(); // configure a pool of projectiles. We say that there can be no more // than 3 projectiles in flight at any time. ProjectilePool.configure(3, 1, 1, "greyball.png", 1, 0, true); } /* * This is another demo of how throwing projectiles works. Like the * previous demo, it doesn't actually use projectiles for anything, it * is just to show how to get some different behaviors in terms of how * the projectiles move. In this case, we show that we can limit the * distance that projectiles travel, and that we can put a control on * the HUD for throwing projectiles */ else if (whichLevel == 44) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press anywhere\nto throw a gray\nball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 30, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(120, 0, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a pool of projectiles, but now once the projectiles travel // more than 25 meters, they disappear ProjectilePool.configure(100, 1, 1, "greyball.png", 1, 0, true); ProjectilePool.setRange(25); // add a button for throwing projectiles. Notice that this butotn // keeps throwing as long as it is held, but we've capped it to // throw no more than once per 100 milliseconds Controls.addThrowButton(0, 0, 480, 320, "", h, 100, 3, 1.5f, 30, 0); Level.setCameraChase(h); } /* * this level demonstrates that we can defeat enemies by throwing * projectiles at them */ else if (whichLevel == 45) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); PreScene.addText("Defeat all enemies\nto win", 255, 255, 255, "arial.ttf", 32); Hero h = Hero.makeAsCircle(4, 27, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // set up our projectiles... note that now projectiles each do 2 // units of damage ProjectilePool.configure(3, .4f, .1f, "greyball.png", 2, 0, true); // draw a few enemies... note that they have different amounts of // damage, so it takes different numbers of projectiles to defeat // them. Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); for (int i = 1; i < 20; i += 5) { Enemy ee = Enemy.makeAsCircle(i, i + 5, 2, 2, "redball.png"); ee.setPhysics(1.0f, 0.3f, 0.6f); ee.setDamage(i); } // win by defeating enemies, of course! Score.setVictoryEnemyCount(); // this button only throws one projectile per press... Controls.addSingleThrowButton(0, 0, 480, 320, "", h, .2f, -.5f, 0, 10); } /* * This level shows how to throw projectiles in a variety of directions. */ else if (whichLevel == 46) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press anywhere\nto throw a ball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Level.setCameraChase(h); Destination.makeAsCircle(120, 0, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // draw a button for throwing projectiles in many directions... // again, note that if we hold the button, it keeps throwing Controls.addVectorThrowButton(0, 0, 480, 320, "", h, 0, 0, 0); // set up our pool of projectiles. The main challenge here is that // the farther from the hero we press, the faster the projectile // goes, so we multiply the velocity by .8 to slow it down a bit ProjectilePool.configure(100, 1, 1, "greyball.png", 1, 0, true); ProjectilePool.setProjectileVectorDampeningFactor(.8f); ProjectilePool.setRange(30); } /* * this level shows that with the "vector" projectiles, we can still * have gravity affect the projectiles. This is very good for * basketball-style games. */ else if (whichLevel == 47) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press anywhere\nto throw a ball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(0, 0, 0.6f); h.setMoveByTilting(); Level.setCameraChase(h); Destination.makeAsCircle(120, 0, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // we use a "single throw" button so that holding doesn't throw more // projectiles. Controls.addVectorSingleThrowButton(0, 0, 480, 320, "", h, 1.5f, 1.5f); // we turn on projectile gravity, and then we enable collisions for // projectiles. This means that when a projectile collides with // something, it will transfer its momentum to that thing, if that // thing is moveable. This is a step toward our goal of being able // to bounce a basketball off of a backboard, but it's not quite // enough... ProjectilePool.configure(100, 1, 1, "greyball.png", 1, 0, true); ProjectilePool.setProjectileVectorDampeningFactor(.8f); ProjectilePool.setRange(40); ProjectilePool.setProjectileGravityOn(); ProjectilePool.enableCollisionsForProjectiles(); // This next line is interesting... it lets projectiles collide with // each other without disappearing ProjectilePool.setCollisionOk(); // Draw an obstacle... this is like our backboard, but we're putting // it in a spot that's more useful for testing than for playing a // game Obstacle o = Obstacle.makeAsBox(10, 20, 2, 2, "red.png"); // now comes the tricky part... we want to make it so that when the // ball hits the obstacle (the backboard), it doesn't disappear. The // only time a projectile does not disappear when hitting an // obstacle is when you provide custom code to run on a // projectile/obstacle collision... in that case, you are // responsible for removing the projectile (or for not removing it). // That being the case, we can set a "callback" to run custom code // when the projectile and obstacle collide, and then just have the // custom code do nothing. // this line says when a projectile and obstacle collide, if the // goodie counts are at least 0,0,0,0, then run the // "onProjectileCollideCallback()" method that appears later in this // file. When onProjectileCollideCallback() runs, it will have an id // of 7, because we arbitrarily picked 7 as the id... for this // simple example, our use of an id isn't important, but for more // complex games, having different ids can be really useful. o.setProjectileCollisionCallback(7, 0, 0, 0, 0); } /* * This level shows how we can attach a timer to an enemy. When the * timer runs out, if the enemy is still visible, then some custom code * will run. We can use this to simulate cancer cells or fire on a * building. The value of attaching the timer to the enemy is that we * can change the game state at the position where the enemy is. One * team even had an enemy that dropped goodies at its current location. * Note that the timer only runs once... you'll need to make a new timer * from within the code that runs when the timer expires. */ else if (whichLevel == 48) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 0); PreScene.addText("Throw balls at \nthe enemies before\nthey reproduce", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setTouchToThrow(h, 2, -.5f, 0, 10); h.setMoveByTilting(); // configure a pool of projectiles... now we have a sound that plays // when a projectile is thrown, and another for when it disappears ProjectilePool.configure(100, .5f, .5f, "greyball.png", 1, 0, true); ProjectilePool.setThrowSound("fwapfwap.ogg"); ProjectilePool.setProjectileDisappearSound("slowdown.ogg"); // draw an enemy that makes a sound when it disappears Enemy e = Enemy.makeAsCircle(23, 20, 1, 1, "redball.png"); e.setDisappearSound("lowpitch.ogg"); // request that in 2 seconds, if the enemy is still visible, // onTimerCallback() will run, with id == 2. Be sure to look at // the onTimerCallback code (below) for more information. Note that // there are two versions of the function, and this uses the second! Level.setTimerCallback(2, 2, e); // win by defeating enemies Score.setVictoryEnemyCount(); // put a count of defeated enemies on the screen Controls.addDefeatedCount(0, "Enemies Defeated", 20, 20); } /* * This level shows that we can have moveable enemies that reproduce. Be * careful... it is possible to make a lot of enemies, really quickly */ else if (whichLevel == 49) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("These enemies are\nreally tricky", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 29, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make our initial enemy Enemy e = Enemy.makeAsCircle(23, 2, 1, 1, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setMoveByTilting(); // set a timer callback on the enemy. warning: "6" is going to lead // to lots of enemies eventually, and there's no way to defeat them // in this level! Again, be sure to look at onEnemyTimerCallback() // below. Level.setTimerCallback(6, 2, e); } /* * this level shows simple animation. Every entity can have a default * animation. */ else if (whichLevel == 50) { // set up a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Make a wish!", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // this hero will be animated: Hero h = Hero.makeAsCircle(4, 7, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // this says that we scroll through the 0, 1, 2, and 3 cells of the // image, and we show each for 200 milliseconds. This is the "easy" // animation mechanism, where every cell is shown for the same // amount of time h.setDefaultAnimation(new Animation("stars.png", 200, true, 0, 1, 2, 3)); } /* * this level introduces jumping animations and disappearance animations */ else if (whichLevel == 51) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press the hero to\nmake it jump", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a hero, and give it two animations: one for when it is in // the air, and another for the rest of the time. Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); h.setJumpImpulses(0, 20); h.setTouchToJump(); h.setMoveByTilting(); Level.setCameraChase(h); // this is the more complex form of animation... we show the // different cells for different lengths of time h.setDefaultAnimation(new Animation("stars.png", 4, true).to(0, 150).to(1, 200).to(2, 300).to(3, 350)); // we can use the complex form to express the simpler animation, of // course h.setJumpAnimation(new Animation("stars.png", 4, true).to(4, 200).to(5, 200).to(6, 200).to(7, 200)); // create a goodie that has a disappearance animation. When the // goodie is ready to disappear, we'll remove it, and then we'll run // the disappear animation. That means that we can make it have any // size we want, but we need to offset it from the (defunct) // goodie's position. Note, too, that the final cell is blank, so // that we don't leave a residue on the screen. Goodie g = Goodie.makeAsCircle(15, 9, 5, 5, "stars.png"); g.setDisappearAnimation(new Animation("starburst.png", 4, false).to(2, 200).to(1, 200).to(0, 200) .to(3, 200), 1, 0, 5, 5); } /* * this level shows that projectiles can be animated, and that we can * animate the hero while it throws a projectile */ else if (whichLevel == 52) { // set up a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Press the hero\nto make it\nthrow a ball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up our hero Hero h = Hero.makeAsCircle(4, 7, 3, 3, "colorstar.png"); h.setPhysics(1, 0, 0.6f); h.setTouchToThrow(h, 0, -.5f, 0, 10); h.setMoveByTilting(); // set up an animation when the hero throws: h.setThrowAnimation(new Animation("colorstar.png", 2, false).to(3, 100).to(4, 500)); // make a projectile pool and give an animation pattern for the // projectiles ProjectilePool.configure(100, 1, 1, "flystar.png", 1, 0, true); ProjectilePool.setAnimation(new Animation("flystar.png", 100, true, 0, 1)); } /* * This level explores invincibility animation. While we're at it, we * make some enemies that aren't affected by invincibility, and some * that can even damage the hero while it is invincible. */ else if (whichLevel == 53) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The blue ball will\nmake you invincible\nfor 15 seconds", 50, 50, 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Destination.makeAsCircle(29, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make an animated hero, and give it an invincibility animation Hero h = Hero.makeAsCircle(2, 2, 3, 3, "colorstar.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); h.setDefaultAnimation(new Animation("colorstar.png", 4, true).to(0, 300).to(1, 300).to(2, 300).to(3, 300)); h.setInvincibleAnimation(new Animation("colorstar.png", 4, true).to(4, 100).to(5, 100).to(6, 100) .to(7, 100)); // make some enemies for (int i = 0; i < 5; ++i) { Enemy e = Enemy.makeAsCircle(5 * i + 1, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); e.setDamage(4); e.setDisappearSound("hipitch.ogg"); // The first enemy we create will harm the hero even if the hero // is invincible if (i == 0) e.setImmuneToInvincibility(); // the second enemy will not be harmed by invincibility, but // won't harm an invincible hero if (i == 1) e.setResistInvincibility(); } // neat trick: this enemy does zero damage, but slows the hero down. Enemy e = Enemy.makeAsCircle(30, 20, 2, 2, "redball.png"); e.setPhysics(10, 0.3f, 0.6f); e.setMoveByTilting(); e.setDamage(0); // add a goodie that makes the hero invincible Goodie g = Goodie.makeAsCircle(30, 30, 2, 2, "blueball.png"); g.setInvincibilityDuration(15); g.setRoute(new Route(3).to(30, 30).to(10, 10).to(30, 30), 5, true); g.setRotationSpeed(0.25f); Controls.addGoodieCount(1, 0, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); // draw a picture when the level is won, and don't print text... // this particular picture isn't very useful PostScene.addWinImage("fade.png", 0, 0, 480, 320); PostScene.setDefaultWinText(""); } /* * demonstrate crawl animation, and also show that on multitouch phones, * we can "crawl" in the air while jumping. */ else if (whichLevel == 54) { Level.configure(3 * 48, 32); Physics.configure(0, -10); PreScene.addText("Press the left side of\nthe screen to crawl\n" + "or the right side\nto jump.", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 0); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a hero with fixed velocity, and give it crawl and jump // animations Hero h = Hero.makeAsBox(2, 1, 3, 7, "stars.png"); h.setPhysics(1, 0, 0); h.addVelocity(15, 0, false); h.setCrawlAnimation(new Animation("stars.png", 4, true).to(0, 100).to(1, 300).to(2, 300).to(3, 100)); h.setJumpAnimation(new Animation("stars.png", 4, true).to(4, 200).to(5, 200).to(6, 200).to(7, 200)); // enable hero jumping and crawling h.setJumpImpulses(0, 15); Controls.addJumpButton(0, 0, 240, 320, "", h); Controls.addCrawlButton(241, 0, 480, 320, "", h); // add an enemy we can defeat via crawling, just for fun. It should // be defeated even by a "jump crawl" Enemy e = Enemy.makeAsCircle(110, 1, 5, 5, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setDefeatByCrawl(); // include a picture on the "try again" screen PostScene.addLoseImage("fade.png", 0, 0, 480, 320); PostScene.setDefaultLoseText("Oh well..."); Level.setCameraChase(h); } /* * This isn't quite the same as animation, but it's nice. We can * indicate that a hero's image changes depending on its strength. This * can, for example, allow a hero to change (e.g., get healthier) by * swapping through images as goodies are collected, or allow the hero * to switch its animation depending on how many enemies it has collided * with */ else if (whichLevel == 55) { // set up a basic level with a bunch of goodies Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // Since colorstar.png has 8 frames, and we're displaying frame 0 as // "health == 0", let's add 7 more goodies, each of which adds 1 to // the hero's strength. for (int i = 0; i < 7; ++i) { Goodie g = Goodie.makeAsCircle(5 + 2 * i, 5 + 2 * i, 2, 2, "blueball.png"); g.setStrengthBoost(1); } Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make 8 enemies, each with strength == 1. This means we can lose // the level, and that we can test moving our strength all the way // up to 7, and all the way back down to 0. for (int i = 0; i < 8; ++i) { Enemy e = Enemy.makeAsCircle(5 + 2 * i, 1 + 2 * i, 2, 2, "redball.png"); e.setDamage(1); } // Note: colorstar.png has 8 cells... Hero h = Hero.makeAsCircle(4, 27, 3, 3, "colorstar.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // Be sure to look at onStrengthChangeCallback. As the hero's // strength moves up and down, its image will change. } /* * demonstrate that obstacles can defeat enemies, and that we can use * this feature to have obstacles that only defeat certain "marked" * enemies */ else if (whichLevel == 56) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); // increase the speed at which tilt affects velocity Tilt.setGravityMultiplier(3); PreScene.addText("You can defeat\ntwo enemies with\nthe blue ball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(1, 0, 0.6f); h.setMoveByTilting(); // put an enemy defeated count on the screen, in red with a small // font Controls.addDefeatedCount(2, "Enemies Defeated", 20, 20, "arial.ttf", 255, 0, 0, 10); // make a moveable obstacle that can defeat enemies Obstacle o = Obstacle.makeAsCircle(10, 2, 4, 4, "blueball.png"); o.setPhysics(.1f, 0, 0.6f); o.setMoveByTilting(); // this says that we don't need to collect any goodies before this // obstacle defeats enemies (0,0,0,0), and that when this obstacle // collides with any enemy, the onEnemyCollideCallback() code will // run, with id == 14. Notice, too, that there will be a half second // delay before the code runs. o.setEnemyCollisionCallback(14, 0, 0, 0, 0, .5f); // make a small obstacle that can also defeat enemies, but doesn't // disappear Obstacle o2 = Obstacle.makeAsCircle(.5f, .5f, 2, 2, "blueball.png"); o2.setPhysics(1, 0, 0.6f); o2.setMoveByTilting(); o2.setEnemyCollisionCallback(1, 0, 0, 0, 0, 0); // make four enemies Enemy e = Enemy.makeAsCircle(40, 2, 4, 4, "redball.png"); e.setPhysics(1, 0, 0.6f); e.setMoveByTilting(); Enemy e1 = Enemy.makeAsCircle(30, 2, 4, 4, "redball.png"); e1.setPhysics(1, 0, 0.6f); Enemy e2 = Enemy.makeAsCircle(40, 22, 2, 2, "redball.png"); e2.setPhysics(1, 0, 0.6f); e2.setMoveByTilting(); Enemy e3 = Enemy.makeAsCircle(40, 12, 4, 4, "redball.png"); e3.setPhysics(1, 0, 0.6f); e3.setMoveByTilting(); // now let's put a note into e2 and e3 e2.setInfoText("small"); e3.setInfoText("big"); // win by defeating enemies Score.setVictoryEnemyCount(2); // be sure to look at onEnemyCollideCallback to see how this level // will play out. } /* * this level shows an odd way of moving the hero. There's friction on * the floor, so it can only move by tilting while the hero is in the * air */ else if (whichLevel == 57) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press the hero to\nmake it jump", 255, 255, 255, "arial.ttf", 32); // note: the floor has friction Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // make a box hero with friction... it won't roll on the floor, so // it's stuck! Hero h = Hero.makeAsBox(2, 2, 3, 3, "stars.png"); h.disableRotation(); h.setPhysics(.1f, 0, 5); h.setMoveByTilting(); Level.setCameraChase(h); // the hero *can* jump... h.setTouchToJump(); h.setJumpImpulses(0, 15); // draw a background Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); } /* * this level shows that we can put an obstacle on the screen and use it * to make the hero throw projectiles. It also shows that we can make * entities that shrink over time... growth is possible too, with a * negative value. */ else if (whichLevel == 58) { Level.configure(48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 5, 3, 3, "greenball.png"); h.setPhysics(1, 0, 0.6f); h.setMoveByTilting(); // make an obstacle that causes the hero to throw Projectiles when // touched Obstacle o = Obstacle.makeAsCircle(43, 27, 5, 5, "purpleball.png"); o.setCollisionEffect(false); o.setTouchToThrow(h, 1.5f, 1.5f, 0, 15); // set up our projectiles ProjectilePool.configure(3, 1, 1, "colorstar.png", 2, 0, true); ProjectilePool.setNumberOfProjectiles(20); // there are only 20... throw them carefully // Allow the projectile image to be chosen randomly from a sprite // sheet ProjectilePool.setImageSource("colorstar.png"); // show how many shots are left Controls.addProjectileCount("projectiles left", 5, 300, "arial.ttf", 255, 0, 255, 12); // draw a bunch of enemies to defeat Enemy e = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e.setPhysics(1.0f, 0.3f, 0.6f); e.setRotationSpeed(1); for (int i = 1; i < 20; i += 5) Enemy.makeAsCircle(i, i + 8, 2, 2, "redball.png"); // draw a few obstacles that shrink over time, to show that circles // and boxes work, we can shrink the X and Y rates independently, // and we can opt to center things as they shrink or grow Obstacle floor = Obstacle.makeAsBox(2, 3, 42, 3, "red.png"); floor.setShrinkOverTime(1, 1, true); Obstacle roof = Obstacle.makeAsBox(24, 30, 1, 1, "red.png"); roof.setShrinkOverTime(-1, 0, false); Obstacle ball1 = Obstacle.makeAsCircle(40, 8, 8, 8, "purpleball.png"); ball1.setShrinkOverTime(1, 2, true); Obstacle ball2 = Obstacle.makeAsCircle(40, 16, 8, 8, "purpleball.png"); ball2.setShrinkOverTime(2, 1, false); Score.setVictoryEnemyCount(5); } /* * @level: 59 this level shows that we can make a hero in the air * rotate. Rotation doesn't do anything, but it looks nice... */ else if (whichLevel == 59) { // make a simple level Level.configure(48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // warning: this destination is just out of the hero's reach when // the hero // jumps... you'll have to hit the side wall and jump again to reach Destination.makeAsCircle(46, 8, 2.5f, 2.5f, "mustardball.png"); Score.setVictoryDestination(1); // make the hero jumpable, so that we can see it spin in the air Hero h = Hero.makeAsCircle(4, 27, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); h.setJumpImpulses(0, 10); h.setTouchToJump(); // add rotation buttons Controls.addRotateButton(0, 240, 80, 80, "", -.5f, h); Controls.addRotateButton(380, 240, 80, 80, "", .5f, h); } /** * we can attach movement buttons to any moveable entity, so in this * case, we attach it to an obstacle to get an arkanoid-like effect. */ else if (whichLevel == 60) { // make a simple level Level.configure(48, 32); Physics.configure(0, 0); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 0); Destination.makeAsCircle(30, 10, 2.5f, 2.5f, "mustardball.png"); Score.setVictoryDestination(1); // make a hero who is always moving... note there is no friction, // anywhere, and the hero is elastic... it won't ever stop... Hero h = Hero.makeAsCircle(4, 4, 3, 3, "greenball.png"); h.setPhysics(0, 1, 0); h.addVelocity(0, 10, false); // make an obstacle and then connect it to some controls Obstacle o = Obstacle.makeAsBox(2, 30.9f, 4, 1, "red.png"); o.setPhysics(100, 1, 0); Controls.addLeftButton(0, 0, 240, 320, "", 5, o); Controls.addRightButton(240, 0, 240, 320, "", 5, o); } /* * this level demonstrates that things can appear and disappear on * simple timers */ else if (whichLevel == 61) { // set up a basic level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Things will appear \nand disappear...", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // create an enemy that will quietly disappear after 2 seconds Enemy e1 = Enemy.makeAsCircle(25, 25, 2, 2, "redball.png"); e1.setPhysics(1.0f, 0.3f, 0.6f); e1.setRotationSpeed(1); e1.setDisappearDelay(2, true); // create an enemy that will appear after 3 seconds Enemy e2 = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e2.setPhysics(1.0f, 0.3f, 0.6f); e2.setRoute(new Route(3).to(35, 25).to(15, 25).to(35, 25), 3, true); e2.setAppearDelay(3); } /* * This level demonstrates the use of timer callbacks. We can use timers * to make more of the level appear over time. In this case, we'll chain * the timer callbacks together, so that we can get more and more things * to develop. Be sure to look at the onTimerCallback code to see how * the rest of this level works. * * @demonstrates: destinations and goodies with fixed velocities * * @demonstrates: enemy who disappears when it is touched * * @demonstrates: enemy who can be dragged around * * @demonstrates: timer callbacks */ else if (whichLevel == 62) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); PreScene.addText("There's nothing to\ndo... yet", 255, 255, 255, "arial.ttf", 20); // note: there's no destination yet, but we still say it's how to // win... we'll get a destination in this level after a few timers // run... Score.setVictoryDestination(1); // now set a timer callback. after three seconds, the // onTimerCallback() method will run, with level=62 and id=0 Level.setTimerCallback(0, 3); } /* * This level shows callbacks that run on a collision between hero and * obstacle. In this case, it lets us draw out the next part of the * level later, instead of drawing the whole thing right now. In a real * level, we'd draw a few screens at a time, and not put the callback * obstacle at the end of a screen, so that we'd never see the drawing * of stuff taking place, but for this demo, that's actually a nice * effect. Be sure to look at onCollideCallback for more details. */ else if (whichLevel == 63) { Level.configure(3 * 48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Keep going right!", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 29, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Level.setCameraChase(h); Controls.addGoodieCount(1, 0, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); Score.setVictoryDestination(1); // this obstacle is a collision callback... when the hero hits it, // the next part of the level appears, via onHeroCollideCallback(). // Note, too, that it disappears when the hero hits it, so we can // play a sound if we want... Obstacle o = Obstacle.makeAsBox(30, 0, 1, 32, "purpleball.png"); o.setPhysics(1, 0, 1); // the callback id is 0, there is no delay, and no goodies are // needed // before it works o.setHeroCollisionCallback(0, 0, 0, 0, 0, 0); o.setDisappearSound("hipitch.ogg"); } /* * this level demonstrates callbacks that happen when we touch an * obstacle. Be sure to look at the onTouchCallback() method for more * details */ else if (whichLevel == 64) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Activate and then \ntouch the obstacle", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); // make a destination... notice that it needs a lot more goodies // than are on the screen... Destination d = Destination.makeAsCircle(29, 1, 2, 2, "mustardball.png"); d.setActivationScore(3, 0, 0, 0); Score.setVictoryDestination(1); // draw an obstacle, make it a touch callback, and then draw the // goodie we need to get in order to activate the obstacle Obstacle o = Obstacle.makeAsCircle(10, 5, 3, 3, "purpleball.png"); o.setPhysics(1, 0, 1); // we'll give this callback the id "39", just for fun o.setTouchCallback(39, 1, 0, 0, 0, true); o.setDisappearSound("hipitch.ogg"); Goodie g = Goodie.makeAsCircle(0, 30, 2, 2, "blueball.png"); g.setDisappearSound("lowpitch.ogg"); } /* * this level shows how to use enemy defeat callbacks. There are four * ways to defeat an enemy, so we enable all mechanisms in this level, * to see if they all work to cause enemy callbacks to run the * onEnemyCallback code. Another important point here is that the IDs * don't need to be unique for *any* callbacks. We can use the same ID * every time... */ else if (whichLevel == 65) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 0); // give the hero strength, so that we can use him to defeat an enemy // as a test of enemy callbacks Hero h = Hero.makeAsCircle(12, 12, 4, 4, "greenball.png"); h.setStrength(3); h.setMoveByTilting(); h.setInvincibleAnimation(new Animation("colorstar.png", 4, true).to(4, 100).to(5, 100).to(6, 100) .to(7, 100)); // a goodie, so we can do defeat by invincibility Goodie g1 = Goodie.makeAsCircle(20, 29, 2, 3, "purpleball.png"); g1.setInvincibilityDuration(15); // enable throwing projectiles, so that we can test enemy callbacks // again h.setTouchToThrow(h, 4, 2, 30, 0); ProjectilePool.configure(100, 1, 1, "greyball.png", 1, 0, true); // add an obstacle that has an enemy collision callback, so it can // defeat enemies Obstacle o = Obstacle.makeAsCircle(30, 10, 5, 5, "blueball.png"); o.setPhysics(1000, 0, 0); o.setCanDrag(false); o.setEnemyCollisionCallback(0, 0, 0, 0, 0, 0); // now draw our enemies... we need enough to be able to test that // all four defeat mechanisms work. Enemy e1 = Enemy.makeAsCircle(5, 5, 1, 1, "redball.png"); e1.setDefeatCallback(0); Enemy e2 = Enemy.makeAsCircle(5, 5, 2, 2, "redball.png"); e2.setDefeatCallback(0); e2.setInfoText("weak"); Enemy e3 = Enemy.makeAsCircle(40, 3, 1, 1, "redball.png"); e3.setDefeatCallback(0); Enemy e4 = Enemy.makeAsCircle(25, 25, 1, 1, "redball.png"); e4.setDefeatCallback(0); e4.setDisappearOnTouch(); Enemy e5 = Enemy.makeAsCircle(25, 29, 1, 1, "redball.png"); e5.setDefeatCallback(0); // win by defeating enemies Score.setVictoryEnemyCount(); } /* * This level shows that we can resize a hero on the fly, and change its * image. We use a collision callback to cause the effect. Furthermore, * we can increment scores inside of the callback code, which lets us * activate the destination on an obstacle collision */ else if (whichLevel == 66) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Only stars can reach\nthe destination", 255, 255, 255, "arial.ttf", 20); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 29, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Controls.addGoodieCount(1, 0, "Goodies", 220, 280, "arial.ttf", 60, 70, 255, 12); // the destination won't work until some goodies are collected... Destination d = Destination.makeAsBox(46, 2, 2, 2, "colorstar.png"); d.setActivationScore(4, 1, 3, 0); Score.setVictoryDestination(1); // Colliding with this star will make the hero into a star... see // onHeroCollideCallback for details Obstacle o = Obstacle.makeAsBox(30, 0, 3, 3, "stars.png"); o.setPhysics(1, 0, 1); o.setHeroCollisionCallback(0, 0, 0, 0, 0, 1); } /* * This level shows how to use countdown timers to win a level, tests * some color features, and introduces a vector throw mechanism with * fixed velocity */ else if (whichLevel == 67) { Level.configure(48, 32); Physics.configure(0, -10); PreScene.addText("Press anywhere\nto throw a ball", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // Here's a simple pause button and pause scene PauseScene.addText("Game Paused", 255, 255, 255, "arial.ttf", 32); Controls.addPauseButton(0, 300, 20, 20, "red.png"); // draw a hero, and a button for throwing projectiles in many // directions. Note that this is going to look like an "asteroids" // game, with a hero covering the bottom of the screen, so that // anything that falls to the bottom counts against the player Hero h = Hero.makeAsBox(1, 0, 46, 1, "greenball.png"); Controls.addVectorThrowButton(0, 0, 480, 320, "", h, 100, 0, 1); // set up our pool of projectiles, then set them to have a fixed // velocity when using the vector throw mechanism ProjectilePool.configure(100, 1, 1, "greyball.png", 1, 0, true); ProjectilePool.setRange(50); ProjectilePool.setFixedVectorThrowVelocity(5); // we're going to win by "surviving" for 25 seconds... with no // enemies, that shouldn't be too hard Controls.addWinCountdown(25, 28, 250, "arial.ttf", 192, 192, 192, 16); // just to play it safe, let's say that we win on destination... // this ensures that collecting goodies or defeating enemies won't // accidentally cause us to win. Of course, with no destination, // there's no way to win now, except surviving. Score.setVictoryDestination(1); } /* * We can make a hero hover, and then have it stop hovering when it is * flicked or moved via "touchToMove". This demonstrates the effect via * flick. It also shows that an enemy (or obstacle/goodie/destination) * can fall due to gravity. */ else if (whichLevel == 68) { Level.configure(48, 32); Physics.configure(0, -10); PreScene.addText("Flick the hero into the destination", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsBox(21, 23, 3, 3, "greenball.png"); h.setHover(21, 23); h.setFlickable(0.7f); // place an enemy, let it fall Enemy e = Enemy.makeAsCircle(31, 25, 3, 3, "redball.png"); e.setCanFall(); Destination.makeAsCircle(25, 25, 5, 5, "mustardball.png"); Score.setVictoryDestination(1); } /* * The default behavior is for a hero to be able to jump any time it * collides with an obstacle. This isn't, of course, the smartest way to * do things, since a hero in the air shouldn't jump. One way to solve * the problem is by altering the presolve code in Physics.java. Another * approach, which is much simpler, is to mark some walls so that the * hero doesn't have jump re-enabled upon a collision. */ else if (whichLevel == 69) { Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press the hero to\nmake it jump", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.5f, 0, 0.6f); h.setMoveByTilting(); h.setTouchToJump(); h.setJumpImpulses(0, 15); Level.setCameraChase(h); // hero can jump while on this obstacle Obstacle.makeAsBox(10, 3, 10, 1, "red.png"); // hero can't jump while on this obstacle Obstacle o = Obstacle.makeAsBox(40, 3, 10, 1, "red.png"); o.setReJump(false); } /* * When something chases an entity, we might not want it to chase in * both the X and Y dimensions... this shows how we can chase in a * single direction. */ else if (whichLevel == 70) { // set up a simple level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("You can walk through the wall", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setMoveByTilting(); Destination.makeAsCircle(42, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // These obstacles chase the hero, but only in one dimension Obstacle e = Obstacle.makeAsCircle(0, 0, 1, 1, "red.png"); e.setChaseSpeed(15, h, false, true); e.setCollisionEffect(true); Obstacle e2 = Obstacle.makeAsCircle(0, 0, 1, 1, "red.png"); e2.setChaseSpeed(15, h, true, false); e2.setCollisionEffect(true); // Here's a wall, and a movable round obstacle Obstacle o = Obstacle.makeAsBox(40, 1, .5f, 20, "red.png"); Obstacle o2 = Obstacle.makeAsCircle(8, 8, 2, 2, "blueball.png"); o2.setMoveByTilting(); // The hero can pass through this wall, because both have the same // passthrough value h.setPassThrough(7); o.setPassThrough(7); } /* * PokeToPlace is nice, but sometimes it's nicer to use Poke to cause * movement to the destination, instead of an immediate jump. */ else if (whichLevel == 71) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 0); PreScene.addText("Poke the hero, then\n where you want it\nto go.", 255, 255, 255, "arial.ttf", 32); // This hero moves via poking. the "false" means that we don't have // to poke hero, poke location, poke hero, poke location, ... // Instead, we can poke hero, poke location, poke location. the // first "true" means that as we drag our finger, the hero will // change its direction of travel. The second "true" means the hero // will stop immediately when we release our finger. Hero h = Hero.makeAsCircle(4, 7, 3, 3, "stars.png"); h.setCanFaceBackwards(); h.setPokePath(4, false); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // sometimes a control needs to have a large touchable area, but a // small image. One way to do it is to make an invisible control, // then put a picture on top of it. This next line shows how to draw // a picture on the HUD Controls.addImage(40, 40, 40, 40, "red.png"); } /* * It can be useful to make a Hero stick to an obstacle. As an example, * if the hero should stand on a platform that moves along a route, then * we will want the hero to "stick" to it, even as the platform moves * downward. */ else if (whichLevel == 72) { Level.configure(48, 32); Physics.configure(0, -10); PreScene.addText("Press screen borders\nto move the hero", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setJumpImpulses(0, 15); h.setTouchToJump(); // give a little friction, to help the hero stick to platforms h.setPhysics(2, 0, .5f); // create a destination Destination.makeAsCircle(20, 15, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // This obstacle is sticky on top... Jump onto it and watch what // happens Obstacle o = Obstacle.makeAsBox(10, 5, 8, .5f, "red.png"); o.setRoute(new Route(5).to(10, 5).to(5, 15).to(10, 25).to(15, 15).to(10, 5), 5, true); o.setPhysics(100, 0, .1f); o.setSticky(true, false, false, false); // This obstacle is not sticky... it's not nearly as much fun Obstacle o2 = Obstacle.makeAsBox(30, 5, 8, .5f, "red.png"); o2.setRoute(new Route(5).to(30, 5).to(25, 15).to(30, 25).to(45, 15).to(30, 5), 5, true); o2.setPhysics(100, 0, 1f); // draw some buttons for moving the hero Controls.addLeftButton(0, 50, 50, 220, "", 5, h); Controls.addRightButton(430, 50, 50, 220, "", 5, h); } /* * When using "vector" projectiles, if the projectile isn't a circle we * might want to rotate it in the direction of travel. Also, this level * shows how to do walls that can be passed through in one direction. */ else if (whichLevel == 73) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Press anywhere\nto shoot a laserbeam", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(42, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // draw a button for throwing projectiles in many directions. It // only covers half the screen, to show how such an effect would // behave Controls.addVectorThrowButton(0, 0, 240, 320, "", h, 100, 0, 0); // set up a pool of projectiles with fixed velocity, and with // rotation ProjectilePool.configure(100, .1f, 3, "red.png", 1, 0, false); ProjectilePool.setFixedVectorThrowVelocity(10); ProjectilePool.setRotateVectorThrow(); // create a box that is easy to fall into, but hard to get out of, // by making its sides each "one-sided" Obstacle bottom = Obstacle.makeAsBox(10, 10, 10, .2f, "red.png"); bottom.setOneSided(2); Obstacle left = Obstacle.makeAsBox(10, 10, .2f, 10, "red.png"); left.setOneSided(1); Obstacle right = Obstacle.makeAsBox(20, 10, .2f, 10, "red.png"); right.setOneSided(3); Obstacle top = Obstacle.makeAsBox(10, 25, 10, .2f, "red.png"); top.setOneSided(0); } /* * This level shows how to use multiple types of goodie scores */ else if (whichLevel == 74) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Green, Red, and Grey\nballs are goodies", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setMoveByTilting(); // the destination requires lots of goodies of different types Destination d = Destination.makeAsCircle(42, 31, 2, 2, "mustardball.png"); d.setActivationScore(1, 1, 3, 0); Score.setVictoryDestination(1); Controls.addGoodieCount(1, 0, "blue", 10, 110, "arial.ttf", 0, 255, 255, 16); Controls.addGoodieCount(2, 0, "green", 10, 140, "arial.ttf", 0, 255, 255, 16); Controls.addGoodieCount(3, 0, "red", 10, 170, "arial.ttf", 0, 255, 255, 16); Controls.addCountdown(100, "", 250, 30); // draw the goodies for (int i = 0; i < 3; ++i) { Goodie b = Goodie.makeAsCircle(10 * i, 30, 2, 2, "blueball.png"); b.setScore(1, 0, 0, 0); Goodie g = Goodie.makeAsCircle(10 * i + 2.5f, 30, 1, 1, "greenball.png"); g.setScore(0, 1, 0, 0); Goodie r = Goodie.makeAsCircle(10 * i + 6, 30, 1, 1, "redball.png"); r.setScore(0, 0, 1, 0); } // When the hero collides with this obstacle, we'll increase the // time remaining. See onHeroCollideCallback() Obstacle o = Obstacle.makeAsBox(40, 0, 5, 200, "red.png"); o.setHeroCollisionCallback(0, 1, 1, 1, 0, 0); } /* * this level shows passthrough objects and chase again, to help * demonstrate how chase works */ else if (whichLevel == 75) { // set up a simple level Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("You can walk through the wall", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setMoveByTilting(); h.setPassThrough(7); // make sure obstacle has same value // the destination requires lots of goodies of different types Destination.makeAsCircle(42, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // the enemy chases the hero, but can't get through the wall Enemy e = Enemy.makeAsCircle(42, 1, 5, 4, "red.png"); e.setChaseSpeed(1, h, true, true); Obstacle o = Obstacle.makeAsBox(40, 1, .5f, 20, "red.png"); o.setPassThrough(7); } /* * We can have a control that increases the hero's speed while pressed, * and decreases it upon release */ else if (whichLevel == 76) { Level.configure(3 * 48, 32); Physics.configure(0, 10); PreScene.addText("Press anywhere to speed up", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 0); Destination.makeAsCircle(120, 31, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Hero h = Hero.makeAsBox(2, 25, 3, 7, "greenball.png"); h.disableRotation(); h.setPhysics(1, 0, 0); // give the hero a fixed velocity h.addVelocity(4, 0, false); // center the camera a little ahead of the hero h.setCameraOffset(15, 0); Level.setCameraChase(h); // set up the background Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // draw a turbo boost button that covers the whole screen... make // sure its "up" speeds match the hero velocity Controls.addTurboButton(0, 0, 480, 320, "", 15, 0, 4, 0, h); } /* * Sometimes, we want to make the hero move when we press a control, but * when we release we don't want an immediate stop. This shows how to * get that effect. */ else if (whichLevel == 77) { Level.configure(3 * 48, 32); Physics.configure(0, -10); PreScene.addText("Press anywhere to start moving", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 0); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); Hero h = Hero.makeAsBox(2, 1, 3, 7, "greenball.png"); h.setCameraOffset(15, 0); Level.setCameraChase(h); Background.setColor(23, 180, 255); Background.addHorizontalLayer(.5f, 1, "mid.png", 0); // This control has a dampening effect, so that on release, the hero // slowly stops Controls.addDampenedMotionButton(0, 0, 480, 320, "", 10, 0, 4, h); } /* * One-sided obstacles can be callback obstacles. This allows, among * other things, games like doodle jump. This level shows how it all * interacts. */ else if (whichLevel == 78) { Level.configure(48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("One-sided + Callbacks", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(.1f, 0, 0); h.setMoveByTilting(); h.setJumpImpulses(0, 15); h.setTouchToJump(); Destination.makeAsCircle(42, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // create a platform that we can jump through from above Obstacle platform = Obstacle.makeAsBox(10, 5, 10, .2f, "red.png"); platform.setOneSided(2); // Set a callback, then re-enable the platform's collision effect. // Be sure to check onHeroCollideCallback platform.setHeroCollisionCallback(0, 0, 0, 0, 0, 0); platform.setCollisionEffect(true); // make the z index of the platform -1, so that the hero (index 0) // will be drawn on top of the box, not under it platform.setZIndex(-1); } /* * This level fleshes out some more poke-to-move stuff. Now we'll say * that once a hero starts moving, the player must re-poke the hero * before it can be given a new destination. Also, the hero will keep * moving after the screen is released. We will also show the Fact * interface. */ else if (whichLevel == 79) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 0); PreScene.addText("Poke the hero, then\n where you want it\nto go.", 255, 255, 255, "arial.ttf", 32); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setMoveByTilting(); h.setFingerChase(4, false, true); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // A callback control is a way to run arbitrary code whenever the // control is pressed. This is something of a catch-all for any sort // of behavior we might want. See onControlPressCallback(). Controls.addCallbackControl(40, 40, 40, 40, "red.png", 747); Controls.addLevelFact("level test", 240, 40, "arial.ttf", 0, 0, 0, 12, "-", "."); Controls.addSessionFact("session test", 240, 80, "arial.ttf", 0, 0, 0, 12, "-", "."); Controls.addGameFact("game test", 240, 120, "arial.ttf", 0, 0, 0, 12, "-", "."); Controls.addCallbackControl(40, 90, 40, 40, "red.png", 748); Controls.addCallbackControl(40, 140, 40, 40, "red.png", 749); Controls.addCallbackControl(40, 190, 40, 40, "red.png", 750); } /* * Sometimes we need to manually force an entity to be immune to * gravity. */ else if (whichLevel == 80) { Level.configure(48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Testing Gravity Defy?", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setPhysics(1, 0, 0.6f); h.setMoveByTilting(); h.setJumpImpulses(0, 15); h.setTouchToJump(); Destination d = Destination.makeAsCircle(42, 14, 2, 2, "mustardball.png"); // note: it must not be immune to physics (third parameter true), or // it will pass through the bounding box, but we do want it to move // and not fall downward d.setAbsoluteVelocity(-2, 0, false); d.setGravityDefy(); Score.setVictoryDestination(1); } /* * Test to show that we can have obstacles with a polygon shape */ else if (whichLevel == 81) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Testing Polygons", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.disableRotation(); h.setMoveByTilting(); Destination.makeAsCircle(42, 14, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // create a polygon obstacle Obstacle o = Obstacle.makeAsPolygon(10, 10, 2, 5, "blueball.png", -1, 2, -1, 0, 0, -3, 1, 0, 1, 1); o.setShrinkOverTime(1, 1, true); } /* * A place for playing with a side-scrolling platformer that has lots of * features */ else if (whichLevel == 82) { // set up a standard side scroller with tilt: Level.configure(3 * 48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); PreScene.addText("Press the hero to\nmake it jump", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 3 * 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(120, 1, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a simple jumping hero Hero h = Hero.makeAsBox(5, 0, 2, 6, "greenball.png"); h.setJumpImpulses(0, 15); h.setTouchToJump(); h.setMoveByTilting(); Level.setCameraChase(h); // This enemy can be defeated by jumping. Note that the hero's // bottom must be higher than the enemy's middle point, or the jump // won't defeat the enemy. Enemy e = Enemy.makeAsCircle(15, 0, 5, 5, "redball.png"); e.setDefeatByJump(); } /* * Demonstrate the ability to set up paddles that rotate back and forth */ else if (whichLevel == 83) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Avoid revolving obstacles", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, 0, 1); Hero h = Hero.makeAsCircle(5, 0, 2, 6, "greenball.png"); h.setMoveByTilting(); // Note: you must give density to the revolving part... Obstacle revolving = Obstacle.makeAsBox(20, 10, 2, 8, "red.png"); revolving.setPhysics(1, 0, 0); Obstacle anchor = Obstacle.makeAsBox(20, 19, 2, 2, "blueball.png"); // TODO: play with timers to change direction of velocity? revolving.setRevoluteJoint(anchor, 0, 0, 0, 6); revolving.setRevoluteJointLimits(1.7f, -1.7f); revolving.setRevoluteJointMotor(4, Float.POSITIVE_INFINITY); Destination.makeAsCircle(40, 30, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); } /* * Demonstrate panning to view more of the level */ else if (whichLevel == 84) { // set up a big screen Level.configure(4 * 48, 2 * 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The star rotates in\nthe direction of movement", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 4 * 48, 2 * 32, "red.png", 1, 0, 1); Destination.makeAsCircle(29, 60, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a hero who rotates in the direction of movement Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setRotationByDirection(); h.setMoveByTilting(); Level.setCameraChase(h); // zoom buttons Controls.addZoomOutButton(0, 0, 240, 320, "", 8); Controls.addZoomInButton(240, 0, 240, 320, "", .25f); // turn on panning Controls.addPanControl(0, 0, 480, 320, ""); } /* * Demonstrate pinch-to-zoom, and also demonstrate one-time callback * controls */ else if (whichLevel == 85) { // set up a big screen Level.configure(4 * 48, 2 * 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("The star rotates in\nthe direction of movement", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 4 * 48, 2 * 32, "red.png", 1, 0, 1); Destination.makeAsCircle(29, 60, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a hero who rotates in the direction of movement Hero h = Hero.makeAsCircle(2, 2, 3, 3, "stars.png"); h.setPhysics(.1f, 0, 0.6f); h.setRotationByDirection(); h.setMoveByTilting(); Level.setCameraChase(h); // turn on pinch zoomg Controls.addPinchZoomControl(0, 0, 480, 320, "", 8, .25f); // add a one-time callback control Controls.addOneTimeCallbackControl(40, 40, 40, 40, "blueball.png", "greenball.png", 992); } /* * Demonstrate some advanced controls */ else if (whichLevel == 86) { // set up a screen Level.configure(48, 32); Physics.configure(0, 0); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(29, 30, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a hero who rotates in the direction of movement Hero h = Hero.makeAsCircle(2, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); Level.setCameraChase(h); // when the hero stops, we'll run code that turns the hero red h.setStopCallback(99); // add some new controls for setting the rotation of the hero and // making the hero move based on a speed Controls.addRotator(215, 135, 50, 50, "stars.png", 2, 72, h); Controls.addVerticalBar(470, 0, 10, 320, "greenball.png", 71, h); } /* * Weld joints */ else if (whichLevel == 87) { // set up a screen Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, 0, 1); Destination.makeAsCircle(29, 30, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // set up a hero and fuse an obstacle to it Hero h = Hero.makeAsCircle(4, 2, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Obstacle o = Obstacle.makeAsCircle(1, 1, 1, 1, "blueball.png"); o.setCanFall(); h.setWeldJoint(o, 3, 0, 0, 0, 45); } /* * Demonstrate that we can have callback buttons on PauseScenes */ else if (whichLevel == 88) { Level.configure(48, 32); Physics.configure(0, 0); Tilt.enable(10, 10); PreScene.addText("Interactive Pause Scenes\n(click the red square)", 255, 255, 255, "arial.ttf", 32); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); Hero h = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h.setPhysics(.1f, 0, 0.6f); h.setMoveByTilting(); Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // Demonstrate the ability to chase while keeping existing velocity // in one direction Obstacle o = Obstacle.makeAsCircle(15, 15, 2, 2, "purpleball.png"); o.setAbsoluteVelocity(5, 1, false); o.setChaseFixedMagnitude(h, 3, 0, false, true); // Create a pause scene that has a back button on it, and a button // for pausing the level PauseScene.addText("Game Paused", 255, 255, 255, "arial.ttf", 32); PauseScene.addBackButton("red.png", 0, 300, 20, 20); PauseScene.addCallbackButton(5, 5, 10, 10, 1); PauseScene.addCallbackButton(95, 95, 10, 10, 2); PauseScene.suppressClearClick(); Controls.addPauseButton(0, 300, 20, 20, "red.png"); } /* * Use multiple heroes to combine positive and negative results */ else if (whichLevel == 89) { Level.configure(48, 32); Physics.configure(0, -10); Tilt.enable(10, 0); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 1, .3f, 1); // now let's draw two heroes who can both move by tilting, and // who both have density and friction. Note that we lower the // density, so they move faster Hero h1 = Hero.makeAsCircle(4, 7, 3, 3, "greenball.png"); h1.setPhysics(.1f, 0, 0.6f); h1.setMoveByTilting(); h1.setJumpImpulses(0, 10); h1.setTouchToJump(); h1.setMustSurvive(); Hero h2 = Hero.makeAsBox(0, 0, 48, .1f, ""); h2.setMustSurvive(); h1.setPassThrough(1); h2.setPassThrough(1); Enemy e1 = Enemy.makeAsCircle(29, 29, 1, 1, "redball.png"); e1.setAbsoluteVelocity(0, -1, true); // notice that now we will make two destinations, each of which // defaults to only holding ONE hero, but we still need to get two // heroes to destinations in order to complete the level Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); } /* * Demonstrate that we can save entities so that we can access them from * a callback */ else if (whichLevel == 90) { Level.configure(48, 32); Physics.configure(0, -10); Util.drawBoundingBox(0, 0, 48, 32, "red.png", 0, 0, 5); PreScene.addText("Keep pressing until\na hero makes it to\nthe destination", 255, 255, 255, "arial.ttf", 32); for (int i = 0; i < 10; ++i) { Hero h = Hero.makeAsBox(4 * i + 2, 0.1f, 2, 2, "greenball.png"); h.setPhysics(1, 1, 5); Facts.putLevelEntity("" + i, h); } Destination.makeAsCircle(29, 16, 2, 2, "mustardball.png"); Score.setVictoryDestination(1); // A callback control is a way to run arbitrary code whenever the // control is pressed. This is something of a catch-all for any sort // of behavior we might want. See onControlPressCallback(). Controls.addCallbackControl(0, 0, 480, 320, "", 0); } } /** * Describe how each help scene ought to be drawn. Every game must implement * this method to describe how each help scene should appear. Note that you * *must* specify the maximum number of help scenes for your game in the * Config.java file. If you specify "0", then you can leave this code blank. * * @param whichScene * The help scene being drawn. The game engine will set this * value to indicate which scene needs to be drawn. */ @Override public void configureHelpScene(int whichScene) { // Note: this is not very good help right now. It's just a demo // Our first scene describes the color coding that we use for the // different entities in the game if (whichScene == 1) { HelpLevel.configure(0, 0, 0); HelpLevel.drawText(50, 240, "The levels of this game\ndemonstrate LOL features"); HelpLevel.drawPicture(50, 200, 30, 30, "greenball.png"); HelpLevel.drawText(100, 200, "You control the hero"); HelpLevel.drawPicture(50, 160, 30, 30, "blueball.png"); HelpLevel.drawText(100, 160, "Collect these goodies"); HelpLevel.drawPicture(50, 120, 30, 30, "redball.png"); HelpLevel.drawText(100, 120, "Avoid or defeat enemies"); HelpLevel.drawPicture(50, 80, 30, 30, "mustardball.png"); HelpLevel.drawText(100, 80, "Reach the destination"); HelpLevel.drawPicture(50, 40, 30, 30, "purpleball.png"); HelpLevel.drawText(100, 40, "These are walls"); HelpLevel.drawPicture(50, 0, 30, 30, "greyball.png"); HelpLevel.drawText(100, 0, "Throw projectiles"); } // Our second help scene is just here to show that it is possible to // have more than one help scene. else if (whichScene == 2) { HelpLevel.configure(255, 255, 0); HelpLevel.drawText(100, 150, "Be sure to read the MyLolGame.java code\n" + "while you play, so you can see\n" + "how everything works", 55, 110, 165, "arial.ttf", 14); } } /** * If a game uses Obstacles that are callbacks, it must provide this to * specify what to do when such an obstacle is hit by a hero. The idea * behind this mechanism is that it allows the creation of more things in * the game, but only after the game has reached a particular state. The * most obvious example is 'infinite' levels. There, it is impossible to * draw the entire scene, so instead one can place an invisible, full-length * CallbackObstacle at some point in the scene, and then when that obstacle * is hit, this code will run. * * @param id * The ID of the obstacle that was hit by the hero * @param whichLevel * The current level * @param obstacle * The obstacle that the hero just collided with * @param hero * The hero who collided with the obstacle */ @Override public void onHeroCollideCallback(int id, int whichLevel, Obstacle obstacle, Hero hero) { // Code to run on level 63 for hero/obstacle collisions: if (whichLevel == 63) { // the first callback just causes us to make a new obstacle a little // farther out if (id == 0) { // get rid of the obstacle we just collided with obstacle.remove(false); // make a goodie Goodie.makeAsCircle(45, 1, 2, 2, "blueball.png"); // make an obstacle that is a callback, but that doesn't work // until the goodie count is 1 Obstacle oo = Obstacle.makeAsBox(60, 0, 1, 32, "purpleball.png"); oo.setHeroCollisionCallback(1, 1, 0, 0, 0, 0); } // The second callback works the same way else if (id == 1) { obstacle.remove(false); Goodie.makeAsCircle(75, 21, 2, 2, "blueball.png"); Obstacle oo = Obstacle.makeAsBox(90, 0, 1, 32, "purpleball.png"); oo.setHeroCollisionCallback(2, 2, 0, 0, 0, 0); } // same for the third callback else if (id == 2) { obstacle.remove(false); Goodie.makeAsCircle(105, 1, 2, 2, "blueball.png"); Obstacle oo = Obstacle.makeAsBox(120, 0, 1, 32, "purpleball.png"); oo.setHeroCollisionCallback(3, 3, 0, 0, 0, 0); } // The fourth callback draws the destination else if (id == 3) { obstacle.remove(false); // print a message and pause the game, via PauseScene PauseScene.addText("The destination is\nnow available", 255, 255, 255, "arial.ttf", 32); Destination.makeAsCircle(120, 20, 2, 2, "mustardball.png"); } } // in level 66, we use obstacle/hero collisions to change the goodie // count, and change the hero appearance else if (whichLevel == 66) { // here's a simple way to increment a goodie count Score.incrementGoodiesCollected2(); // here's a way to set a goodie count Score.setGoodiesCollected3(3); // here's a way to read and write a goodie count Score.setGoodiesCollected1(4 + Score.getGoodiesCollected1()); // get rid of the star, so we know it's been used obstacle.remove(true); // resize the hero, and change its image hero.resize(hero.getXPosition(), hero.getYPosition(), 5, 5); hero.setImage("stars.png", 0); } // on level 74, we use a collision as an excuse to add more time before // time's up. else if (whichLevel == 74) { // add 15 seconds to the timer Score.updateTimerExpiration(15); obstacle.remove(true); } // on level 78, we make the hero jump by giving it an upward velocity. // Note that the obstacle is one-sided, so this will only run when the // hero comes down onto the platform, not when he goes up through it. else if (whichLevel == 78) { hero.setAbsoluteVelocity(hero.getXVelocity(), 5, false); return; } } /** * If a game uses entities that are touch callbacks, it must provide this to * specify what to do when such an entity is touched by the user. The idea * behind this mechanism is that it allows the creation of more interactive * games, since there can be items to unlock, treasure chests to open, and * other such behaviors. * * @param id * The ID of the obstacle that was hit by the hero * @param whichLevel * The current level * @param entity * The entity that was touched */ @Override public void onTouchCallback(int id, int whichLevel, PhysicsSprite entity) { // In level 64, we draw a bunch of goodies when the obstacle is touched. // This is supposed to be like having a treasure chest open up. if (whichLevel == 64) { if (id == 39) { // note: we could draw a picture of an open chest in the // obstacle's place, or even use a disappear animation whose // final frame looks like an open treasure chest. entity.remove(false); for (int i = 0; i < 3; ++i) Goodie.makeAsCircle(9 * i, 20 - i, 2, 2, "blueball.png"); } } } /** * If a game uses timer callbacks, it must provide this to specify what to * do when a timer expires. * * @param id * The ID of the timer * @param whichLevel * The current level */ @Override public void onTimerCallback(int id, int whichLevel) { // here's the code for level 62 if (whichLevel == 62) { // after first callback, print a message, draw an enemy, register a // new timer if (id == 0) { // put up a pause scene to interrupt gameplay PauseScene.addText("Ooh... a draggable enemy", 255, 255, 0, "arial.ttf", 12); PauseScene.show(); // make a draggable enemy Enemy e3 = Enemy.makeAsCircle(35, 25, 2, 2, "redball.png"); e3.setPhysics(1.0f, 0.3f, 0.6f); e3.setCanDrag(true); // set up a new timer, with id == 1 Level.setTimerCallback(1, 3); } // after second callback, draw an enemy who disappears on touch, // and register a new timer else if (id == 1) { // clear the pause scene, then put new text on it PauseScene.reset(); PauseScene.addText("Touch the enemy and it will go away", 255, 0, 255, "arial.ttf", 12); PauseScene.show(); // add an enemy that is touch-to-defeat Enemy e4 = Enemy.makeAsCircle(35, 5, 2, 2, "redball.png"); e4.setPhysics(1.0f, 0.3f, 0.6f); e4.setDisappearOnTouch(); // set another timer with id == 2 Level.setTimerCallback(2, 3); } // after third callback, draw an enemy, a goodie, and a destination, // all with fixed velocities else if (id == 2) { PauseScene.reset(); PauseScene.addText("Now you can see the rest of the level", 255, 255, 0, "arial.ttf", 12); PauseScene.show(); Destination d = Destination.makeAsCircle(29, 6, 2, 2, "mustardball.png"); d.addVelocity(-.5f, -1, false); Enemy e5 = Enemy.makeAsCircle(35, 15, 2, 2, "redball.png"); e5.setPhysics(1.0f, 0.3f, 0.6f); e5.addVelocity(4, 4, false); Goodie gg = Goodie.makeAsCircle(10, 10, 2, 2, "blueball.png"); gg.addVelocity(5, 5, false); } } } /** * If you want to have timercallbacks with attached entityes, then you must * override this to define what happens when the timer expires * * @param id * The id that was assigned to the timer that exired * @param whichLevel * The current level * @param ps * The PhysicsSprite that was connected to the timer */ @Override public void onTimerCallback(int id, int whichLevel, PhysicsSprite ps) { // Code for level 48's EnemyTimerCallback if (whichLevel == 48) { // we're simulating cancer cells that can reproduce a fixed number // of times. The ID here represents the number of remaining // reproductions for the current enemy (e), so that we don't // reproduce forever (note that we could, if we wanted to...) // make an enemy just like "e", but to the left Enemy left = Enemy.makeAsCircle(ps.getXPosition() - 2 * id, ps.getYPosition() + 2 * id, ps.getWidth(), ps.getHeight(), "redball.png"); left.setDisappearSound("lowpitch.ogg"); // make an enemy just like "e", but to the right Enemy right = Enemy.makeAsCircle(ps.getXPosition() + 2 * id, ps.getYPosition() + 2 * id, ps.getWidth(), ps.getHeight(), "redball.png"); right.setDisappearSound("lowpitch.ogg"); // if there are reproductions left, then have e and its two new // children all reproduce in 2 seconds if (id > 0) { Level.setTimerCallback(id - 1, 2, left); Level.setTimerCallback(id - 1, 2, ps); Level.setTimerCallback(id - 1, 2, right); } } // Code for level 49's EnemyTimerCallback else if (whichLevel == 49) { // in this case, every enemy will produce one offspring on each // timer Enemy e2 = Enemy.makeAsCircle(ps.getXPosition(), ps.getYPosition(), ps.getWidth(), ps.getHeight(), "redball.png"); e2.setPhysics(1.0f, 0.3f, 0.6f); e2.setMoveByTilting(); // make more enemies? if (id > 0) { Level.setTimerCallback(id - 1, 2, ps); Level.setTimerCallback(id - 1, 2, e2); } } } /** * If a game has Enemies that have 'defeatCallback' set, then when any of * those enemies are defeated, this code will run * * @param id * The ID of the enemy that was defeated by the hero * @param whichLevel * The current level * @param enemy * The enemy that was defeated */ @Override public void onEnemyDefeatCallback(int id, int whichLevel, Enemy enemy) { // in level 65, whenever we defeat an enemy, we pause the game, print a // message, and then put a goodie at a random location if (whichLevel == 65) { // always reset the pausescene, in case it has something on it from // before... PauseScene.reset(); PauseScene.addText("good job, here's a prize", 88, 226, 160, "arial.ttf", 16); PauseScene.show(); // use random numbers to figure out where to draw a goodie as a // reward... picking in the range 0-46,0-30 ensures that with width // and height of 2, the goodie stays on screen Goodie.makeAsCircle(Util.getRandom(46), Util.getRandom(30), 2, 2, "blueball.png"); } } /** * If you want to have EnemyCollide callbacks, then you must override this * to define what happens when an enemy hits the obstacle * * @param id * The ID of the callback * @param whichLevel * The current level * @param obstacle * The obstacle involved in the collision * @param enemy * The enemy involved in the collision */ @Override public void onEnemyCollideCallback(int id, int whichLevel, Obstacle obstacle, Enemy enemy) { // this is the code for level 56, to handle collisions between obstacles // and enemies if (whichLevel == 56) { // only the small obstacle can defeat small enemies if (enemy.getInfoText() == "small" && id == 1) { enemy.defeat(true); } // both obstacles can defeat big enemies, but the big obstacle will // disappear if (enemy.getInfoText() == "big") { enemy.defeat(true); if (id == 14) { obstacle.remove(true); } } } // this is the code for level 65... if the obstacle collides with the // "weak" enemy, we defeat the enemy. else if (whichLevel == 65) { if (enemy.getInfoText() == "weak") { enemy.defeat(true); } } } /** * If you want to have Obstacle/Projectile callbacks, then you must override * this to define what happens when a projectile hits the obstacle * * @param id * The ID of the callback * @param whichLevel * The current level * @param obstacle * The obstacle involved in the collision * @param projectile * The projectile involved in the collision */ @Override public void onProjectileCollideCallback(int id, int whichLevel, Obstacle obstacle, Projectile projectile) { if (whichLevel == 47) { if (id == 7) { // don't do anything... we want the projectile to stay on the // screen! } else { // the ID is not 7... remove the projectile without making a // projectile disappear sound. projectile.remove(true); } } } /** * If you want to do something when the level ends (like record a high * score), you will need to override this method * * @param whichLevel * The current level * @param win * true if the level was won, false otherwise */ @Override public void onLevelCompleteCallback(int whichLevel, boolean win) { // if we are on level 32, see if this is the farthest the hero has ever // traveled, and if so, update the persistent score if (whichLevel == 32) { int oldBest = Score.readPersistent("HighScore", 0); if (oldBest < Score.getDistance()) { Score.savePersistent("HighScore", Score.getDistance()); } } } /** * If you use CallbackControls, you must override this to define what * happens when the control is pressed * * @param id * The id that was assigned to the Control * @param whichLevel * The current level */ @Override public void onControlPressCallback(int id, int whichLevel) { // for lack of anything better to do, we'll just pause the game if (whichLevel == 79) { if (id == 747) { PauseScene.addText("Current score " + Score.getGoodiesCollected1(), 255, 255, 255, "arial.ttf", 20); PauseScene.show(); } else if (id == 748) { Facts.putLevelFact("level test", 1 + Facts.getLevelFact("level test")); } else if (id == 749) { Facts.putSessionFact("session test", 1 + Facts.getSessionFact("session test")); } else if (id == 750) { Facts.putGameFact("game test", 1 + Facts.getGameFact("game test")); } } else if (whichLevel == 85) { if (id == 992) { PauseScene.addText("you can only pause once...", 255, 255, 255, "arial.ttf", 20); PauseScene.show(); } } else if (whichLevel == 90) { for (int i = 0; i < 10; ++i) { PhysicsSprite p = Facts.getLevelEntity("" + i); p.setAbsoluteVelocity(5 - Util.getRandom(10), 10, false); } } } /** * If you use EntityCallbackControls, you must override this to define what * happens when the control is pressed * * @param id * The id that was assigned to the Control * @param whichLevel * The current level */ @Override public void onControlPressEntityCallback(int id, float val, PhysicsSprite entity, int whichLevel) { // for lack of anything better to do, we'll just pause the game if (whichLevel == 86) { if (id == 71) { // vertical bar... make the entity move int rotation = Facts.getLevelFact("rotation") / 100; // create a unit vector Vector2 v = new Vector2(1, 0); v.scl(val); v.rotate(rotation + 90); entity.setDamping(2f); entity.setAbsoluteVelocity(v.x, v.y, false); } else if (id == 72) { // rotator... save the rotation and rotate the hero entity.setRotation(val * (float) Math.PI / 180); // multiply float val by 100 to preserve some decimal places Facts.putLevelFact("rotation", (int) (100 * val)); } } } /** * Whenever a hero's strength changes due to a collision with a goodie or * enemy, this is called. The most common use is to change the hero's * appearance. * * @param whichLevel * The current level * @param h * The hero involved in the collision */ @Override public void onStrengthChangeCallback(int whichLevel, Hero h) { if (whichLevel == 55) { // get the hero's strength. Since the hero isn't dead, the strength // is at least 1. Since there are 7 strength booster goodies, the // strength is at most 8. int s = h.getStrength(); // set the hero's image index to (s-1), i.e., one of the indices in // the range 0..7, depending on strength h.setImage("colorstar.png", s - 1); } } /** * When an entity stops moving, this code runs */ @Override public void onStopCallback(int id, int whichLevel, PhysicsSprite o) { if (whichLevel == 86) { if (id == 99) { o.setImage("red.png", 0); } } } /** * When a PauseScene button is pressed, this code will run. * * @param whichLevel * The current level * @param id * The number assigned to this PauseScene button */ @Override public void onPauseSceneCallback(int whichLevel, int id) { if (whichLevel == 88) { if (id == 1) { Score.winLevel(); } if (id == 2) { Score.loseLevel(); } } } /** * Mandatory method. Don't change this. */ @Override public LolConfiguration lolConfig() { return new LolConfig(); } /** * Mandatory method. Don't change this. */ @Override public ChooserConfiguration chooserConfig() { return new ChooserConfig(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jme3test.bullet; import com.jme3.asset.AssetManager; import com.jme3.bullet.PhysicsSpace; import com.jme3.bullet.PhysicsTickListener; import com.jme3.bullet.collision.PhysicsCollisionEvent; import com.jme3.bullet.collision.PhysicsCollisionListener; import com.jme3.bullet.collision.PhysicsCollisionObject; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.bullet.collision.shapes.SphereCollisionShape; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.bullet.objects.PhysicsGhostObject; import com.jme3.bullet.objects.PhysicsRigidBody; import com.jme3.effect.EmitterSphereShape; import com.jme3.effect.ParticleEmitter; import com.jme3.effect.ParticleMesh.Type; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import java.io.IOException; import java.util.Iterator; /** * * @author normenhansen */ public class BombControl extends RigidBodyControl implements PhysicsCollisionListener, PhysicsTickListener { private float explosionRadius = 10; private PhysicsGhostObject ghostObject; private Vector3f vector = new Vector3f(); private Vector3f vector2 = new Vector3f(); private float forceFactor = 1; private ParticleEmitter effect; private float fxTime = 0.5f; private float curTime = -1.0f; public BombControl(CollisionShape shape, float mass) { super(shape, mass); createGhostObject(); } public BombControl(AssetManager manager, CollisionShape shape, float mass) { super(shape, mass); createGhostObject(); prepareEffect(manager); } public void setPhysicsSpace(PhysicsSpace space) { super.setPhysicsSpace(space); if (space != null) { space.addCollisionListener(this); } } private void prepareEffect(AssetManager assetManager) { int COUNT_FACTOR = 1; float COUNT_FACTOR_F = 1f; effect = new ParticleEmitter("Flame", Type.Triangle, 32 * COUNT_FACTOR); effect.setSelectRandomImage(true); effect.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F))); effect.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f)); effect.setStartSize(1.3f); effect.setEndSize(2f); effect.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f)); effect.setParticlesPerSec(0); effect.setGravity(-5f); effect.setLowLife(.4f); effect.setHighLife(.5f); effect.setInitialVelocity(new Vector3f(0, 7, 0)); effect.setVelocityVariation(1f); effect.setImagesX(2); effect.setImagesY(2); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"); mat.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png")); effect.setMaterial(mat); effect.setLocalScale(100); } protected void createGhostObject() { ghostObject = new PhysicsGhostObject(new SphereCollisionShape(explosionRadius)); } public void collision(PhysicsCollisionEvent event) { if (space == null) { return; } if (event.getObjectA() == this || event.getObjectB() == this) { space.add(ghostObject); ghostObject.setPhysicsLocation(getPhysicsLocation(vector)); space.addTickListener(this); if (effect != null && spatial.getParent() != null) { curTime = 0; effect.setLocalTranslation(spatial.getLocalTranslation()); spatial.getParent().attachChild(effect); effect.emitAllParticles(); } space.remove(this); spatial.removeFromParent(); } } public void prePhysicsTick(PhysicsSpace space, float f) { space.removeCollisionListener(this); } public void physicsTick(PhysicsSpace space, float f) { //get all overlapping objects and apply impulse to them for (Iterator<PhysicsCollisionObject> it = ghostObject.getOverlappingObjects().iterator(); it.hasNext();) { PhysicsCollisionObject physicsCollisionObject = it.next(); if (physicsCollisionObject instanceof PhysicsRigidBody) { PhysicsRigidBody rBody = (PhysicsRigidBody) physicsCollisionObject; rBody.getPhysicsLocation(vector2); vector2.subtractLocal(vector); float force = explosionRadius - vector2.length(); force *= forceFactor; force = force > 0 ? force : 0; vector2.normalizeLocal(); vector2.multLocal(force); ((PhysicsRigidBody) physicsCollisionObject).applyImpulse(vector2, Vector3f.ZERO); } } space.removeTickListener(this); space.remove(ghostObject); } @Override public void update(float tpf) { super.update(tpf); if (enabled && curTime >= 0) { curTime += tpf; if (curTime > fxTime) { curTime = -1; effect.removeFromParent(); } } } /** * @return the explosionRadius */ public float getExplosionRadius() { return explosionRadius; } /** * @param explosionRadius the explosionRadius to set */ public void setExplosionRadius(float explosionRadius) { this.explosionRadius = explosionRadius; createGhostObject(); } @Override public void read(JmeImporter im) throws IOException { throw new UnsupportedOperationException("Reading not supported."); } @Override public void write(JmeExporter ex) throws IOException { throw new UnsupportedOperationException("Saving not supported."); } }
//@author A0116538A package bakatxt.test; import static java.awt.event.KeyEvent.*; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import bakatxt.core.BakaProcessor; import bakatxt.gui.BakaUI; import bakatxt.gui.UIHelper; /** * This class is a helper class to automate test cases for JUnit on the GUI. * */ public class BakaBot extends Robot { // places to store and backup our test files private static final Path TEST_FILE = new File("./mytestfile.txt").toPath(); private static final Path TEST_FILE_SAVE = new File("./mytestfile.txt.bak").toPath(); // commands public static final String ADD = "add "; public static final String DELETE = "delete "; public static final String EDIT = "edit "; public static final String DISPLAY = "display "; public static final int WAIT_SHORT = 25; public static final int WAIT_MEDIUM = 200; public static final int WAIT_LONG = 2000; // some sample strings public static final String SAMPLE_FOX = "the quick brown fox jumps over " + "the lazy dog 1234567890"; public static final String SAMPLE_ZOMBIES = "PAINFUL ZOMBIES QUICKLY WATCH A" + "JINXED GRAVEYARD"; public BakaBot() throws AWTException { super(); } /** * Call this in the @BeforeClass method in your JUnit test. Sets up the files * for testing while retaining the old files. * @throws IOException */ public static void botOneTimeSetUp() throws IOException { saveOldFile(); initializeTestFile(); } /** * Call this in the @AfterClass method in your JUnit test. Restores the old * task database file used before the test. * @throws IOException */ public static void botOneTimeTearDown() throws IOException { restoreTestFile(); } /** * Call this in the @Before method in your JUnit test. Starts the GUI and * reinitializes the test files if needed. * @throws IOException */ public static void botSetUp() throws IOException { BakaUI.startGui(new BakaProcessor()); initializeTestFile(); } /** * Call this in the @After method in your JUnit test. Pauses for 2 seconds * between each test to prevent interference between each test. */ public static void botTearDown() { waitAWhile(WAIT_LONG); } /** * moves the cursor to the input box and simulate a keyboard typing the string * s * @param s is the string to be typed */ public void inputThisString(String s) { typeThis(s); waitAWhile(WAIT_SHORT); enter(); } /** * moves the cursor to the BakaTxt input box and clicks it */ public void mouseToInputBox() { mouseMove(UIHelper.WINDOW_LOCATION.x + 60, UIHelper.WINDOW_LOCATION.y + 20); mousePress(InputEvent.BUTTON1_DOWN_MASK); waitAWhile(WAIT_SHORT); mouseRelease(InputEvent.BUTTON1_DOWN_MASK); } /** * Tells the process to wait waitTime milliseconds * @param waitTime is the time in miliseconds to wait */ public static void waitAWhile(final int waitTime) { try{ Thread.sleep(waitTime); } catch (InterruptedException e) { } } /** * Simulates an enter key being pressed */ public void enter() { typeThis("\n"); } /** * Types a string using keyboard inputs * @param toBeTyped is the string to be typed */ public void typeThis(CharSequence toBeTyped) { for (int i = 0; i < toBeTyped.length(); i++) { char character = toBeTyped.charAt(i); typeThisChar(character); waitAWhile(WAIT_SHORT); } } private static void saveOldFile() throws IOException { Files.deleteIfExists(TEST_FILE_SAVE); if(Files.exists(TEST_FILE)) { Files.copy(TEST_FILE, TEST_FILE_SAVE); } } private static void initializeTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); Files.createFile(TEST_FILE); } private static void restoreTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); if(Files.exists(TEST_FILE_SAVE)) { Files.copy(TEST_FILE_SAVE, TEST_FILE); } Files.deleteIfExists(TEST_FILE_SAVE); } /** * types a character, note, only what is on a standard keyboard layout, no unicode * @param character is the character to be typed */ private void typeThisChar(char character) { switch (character) { case 'a' : typingThisChar(VK_A); break; case 'b' : typingThisChar(VK_B); break; case 'c' : typingThisChar(VK_C); break; case 'd' : typingThisChar(VK_D); break; case 'e' : typingThisChar(VK_E); break; case 'f' : typingThisChar(VK_F); break; case 'g' : typingThisChar(VK_G); break; case 'h' : typingThisChar(VK_H); break; case 'i' : typingThisChar(VK_I); break; case 'j' : typingThisChar(VK_J); break; case 'k' : typingThisChar(VK_K); break; case 'l' : typingThisChar(VK_L); break; case 'm' : typingThisChar(VK_M); break; case 'n' : typingThisChar(VK_N); break; case 'o' : typingThisChar(VK_O); break; case 'p' : typingThisChar(VK_P); break; case 'q' : typingThisChar(VK_Q); break; case 'r' : typingThisChar(VK_R); break; case 's' : typingThisChar(VK_S); break; case 't' : typingThisChar(VK_T); break; case 'u' : typingThisChar(VK_U); break; case 'v' : typingThisChar(VK_V); break; case 'w' : typingThisChar(VK_W); break; case 'x' : typingThisChar(VK_X); break; case 'y' : typingThisChar(VK_Y); break; case 'z' : typingThisChar(VK_Z); break; case 'A' : typingThisChar(VK_SHIFT, VK_A); break; case 'B' : typingThisChar(VK_SHIFT, VK_B); break; case 'C' : typingThisChar(VK_SHIFT, VK_C); break; case 'D' : typingThisChar(VK_SHIFT, VK_D); break; case 'E' : typingThisChar(VK_SHIFT, VK_E); break; case 'F' : typingThisChar(VK_SHIFT, VK_F); break; case 'G' : typingThisChar(VK_SHIFT, VK_G); break; case 'H' : typingThisChar(VK_SHIFT, VK_H); break; case 'I' : typingThisChar(VK_SHIFT, VK_I); break; case 'J' : typingThisChar(VK_SHIFT, VK_J); break; case 'K' : typingThisChar(VK_SHIFT, VK_K); break; case 'L' : typingThisChar(VK_SHIFT, VK_L); break; case 'M' : typingThisChar(VK_SHIFT, VK_M); break; case 'N' : typingThisChar(VK_SHIFT, VK_N); break; case 'O' : typingThisChar(VK_SHIFT, VK_O); break; case 'P' : typingThisChar(VK_SHIFT, VK_P); break; case 'Q' : typingThisChar(VK_SHIFT, VK_Q); break; case 'R' : typingThisChar(VK_SHIFT, VK_R); break; case 'S' : typingThisChar(VK_SHIFT, VK_S); break; case 'T' : typingThisChar(VK_SHIFT, VK_T); break; case 'U' : typingThisChar(VK_SHIFT, VK_U); break; case 'V' : typingThisChar(VK_SHIFT, VK_V); break; case 'W' : typingThisChar(VK_SHIFT, VK_W); break; case 'X' : typingThisChar(VK_SHIFT, VK_X); break; case 'Y' : typingThisChar(VK_SHIFT, VK_Y); break; case 'Z' : typingThisChar(VK_SHIFT, VK_Z); break; case '0' : typingThisChar(VK_0); break; case '1' : typingThisChar(VK_1); break; case '2' : typingThisChar(VK_2); break; case '3' : typingThisChar(VK_3); break; case '4' : typingThisChar(VK_4); break; case '5' : typingThisChar(VK_5); break; case '6' : typingThisChar(VK_6); break; case '7' : typingThisChar(VK_7); break; case '8' : typingThisChar(VK_8); break; case '9' : typingThisChar(VK_9); break; case '-' : typingThisChar(VK_MINUS); break; case '@' : typingThisChar(VK_AT); break; case '\n' : typingThisChar(VK_ENTER); break; case '/' : typingThisChar(VK_SLASH); break; case ' ' : typingThisChar(VK_SPACE); break; default : throw new IllegalArgumentException("Cannot type: " + character); } } /** * Types the char based on what keypresses are needed to type it * * @param keyCodes is the keyCodes needed to be activated */ private void typingThisChar(int... keyCodes) { for (int i = 0; i < keyCodes.length; i++) { keyPress(keyCodes[i]); } waitAWhile(WAIT_SHORT); for (int i = 0; i < keyCodes.length; i++) { keyRelease(keyCodes[i]); } } }
/* Mnemonic.java */ import java.util.Arrays; /** * A class to define constant ints to represent mnemonics, and to * provide conversion methods between int and String representations. */ public class Mnemonic { /** * The heart of the class - an array of mnemonics. * NOTE: must be lexicographically ordered. */ private static String[] mnemonicList = {"CAL", "INC", "JIF", "JMP", "LCI", "LCR", "LCS", "LDA", "LDI", "LDU", "LDV", "MST", "OPR", "RDI", "RDR", "REH", "SIG", "STI", "STO"}; public static final int CAL = mnemonicToInt("CAL"); public static final int INC = mnemonicToInt("INC"); public static final int JIF = mnemonicToInt("JIF"); public static final int JMP = mnemonicToInt("JMP"); public static final int LCI = mnemonicToInt("LCI"); public static final int LCR = mnemonicToInt("LCR"); public static final int LCS = mnemonicToInt("LCS"); public static final int LDA = mnemonicToInt("LDA"); public static final int LDI = mnemonicToInt("LDI"); public static final int LDU = mnemonicToInt("LDU"); public static final int LDV = mnemonicToInt("LDV"); public static final int MST = mnemonicToInt("MST"); public static final int OPR = mnemonicToInt("OPR"); public static final int RDI = mnemonicToInt("RDI"); public static final int RDR = mnemonicToInt("RDR"); public static final int REH = mnemonicToInt("REH"); public static final int SIG = mnemonicToInt("SIG"); public static final int STI = mnemonicToInt("STI"); public static final int STO = mnemonicToInt("STO"); public static int mnemonicToInt(String m) { return Arrays.binarySearch(mnemonicList, m); } public static String intToMnemonic(int i) { if(i < mnemonicList.length && i >= 0) return mnemonicList[i]; return "XXX"; } }
package convwatch; // imports import java.util.Enumeration; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import com.sun.star.lang.XMultiServiceFactory; import convwatch.DirectoryHelper; import convwatch.OfficePrint; import convwatch.ConvWatchException; import convwatch.EnhancedComplexTestCase; import convwatch.PropertyName; import helper.OfficeProvider; * more is found in qadevOOo/runner/convwatch/* */ public class DocumentConverter extends EnhancedComplexTestCase { // The first of the mandatory functions: /** * Return the name of the test. * In this case it is the actual name of the service. * @return The tested service. */ public String getTestObjectName() { return "DocumentConverter runner"; } // The second of the mandatory functions: return all test methods as an // array. There is only one test function in this example. /** * Return all test methods. * @return The test methods. */ public String[] getTestMethodNames() { return new String[]{"convert"}; } // This test is fairly simple, so there is no need for before() or after() // methods. public void before() { // System.out.println("before()"); } public void after() { // System.out.println("after()"); } // The test method itself. private String m_sInputPath = ""; private String m_sReferencePath = ""; private boolean m_bIncludeSubdirectories = true; void initMember() { // MUST PARAMETER String sINPATH = (String)param.get( PropertyName.DOC_COMPARATOR_INPUT_PATH ); boolean bQuit = false; String sError = ""; if (sINPATH == null || sINPATH.length() == 0) { log.println("Please set input path (path to documents) " + PropertyName.DOC_COMPARATOR_INPUT_PATH + "=path."); bQuit = true; } else { log.println("found " + PropertyName.DOC_COMPARATOR_INPUT_PATH + " " + sINPATH); m_sInputPath = sINPATH; } String sREF = (String)param.get( PropertyName.DOC_COMPARATOR_REFERENCE_PATH ); if (sREF == null || sREF.length() == 0) { log.println("Please set output path (path to a directory, where the references should stay) " + PropertyName.DOC_COMPARATOR_REFERENCE_PATH + "=path."); bQuit = true; } else { log.println("found " + PropertyName.DOC_COMPARATOR_REFERENCE_PATH + " " + sREF); m_sReferencePath = sREF; } if (bQuit == true) { // log.println("must quit."); assure("Must quit, Parameter problems.", false); } if (m_sInputPath.startsWith("file:") || m_sReferencePath.startsWith("file:")) { assure("We can't handle file: URL right, use system path instead.", false); } } /** * Function returns a List of software which must accessable as an external executable */ protected Object[] mustInstalledSoftware() { ArrayList aList = new ArrayList(); // aList.add("perl -version"); return aList.toArray(); } public void convert() { GlobalLogWriter.set(log); // check if all need software is installed and accessable checkEnvironment(mustInstalledSoftware()); // test_removeFirstDirectorysAndBasenameFrom(); // Get the MultiServiceFactory. // XMultiServiceFactory xMSF = (XMultiServiceFactory)param.getMSF(); GraphicalTestArguments aGTA = getGraphicalTestArguments(); if (aGTA == null) { assure("Must quit", false); } initMember(); File aInputPath = new File(m_sInputPath); if (aInputPath.isDirectory()) { String fs = System.getProperty("file.separator"); String sRemovePath = aInputPath.getAbsolutePath(); // a whole directory FileFilter aFileFilter = aGTA.getFileFilter(); Object[] aList = DirectoryHelper.traverse(m_sInputPath, aGTA.getFileFilter(), aGTA.includeSubDirectories()); for (int i=0;i<aList.length;i++) { String sEntry = (String)aList[i]; String sNewReferencePath = m_sReferencePath + fs + FileHelper.removeFirstDirectorysAndBasenameFrom(sEntry, m_sInputPath); log.println("- next file is: log.println(sEntry); if (aGTA.checkIfUsable(sEntry)) { runGDC(sEntry, sNewReferencePath); } } } else { if (aGTA.checkIfUsable(m_sInputPath)) { runGDC(m_sInputPath, m_sReferencePath); } } } void runGDC(String _sInputFile, String _sReferencePath) { // first do a check if the reference not already exist, this is a big speedup, due to the fact, // we don't need to start a new office. GraphicalTestArguments aGTA_local = getGraphicalTestArguments(); // if (GraphicalDifferenceCheck.isReferenceExists(_sInputFile, _sReferencePath, aGTA_local) == false) // start a fresh Office OfficeProvider aProvider = null; if (aGTA_local.restartOffice()) { aProvider = new OfficeProvider(); XMultiServiceFactory xMSF = (XMultiServiceFactory) aProvider.getManager(param); param.put("ServiceFactory", xMSF); } GraphicalTestArguments aGTA = getGraphicalTestArguments(); if (aGTA.getOfficeProgram().toLowerCase().equals("msoffice")) { // ReferenceType is MSOffice GlobalLogWriter.get().println("USE MSOFFICE AS EXPORT FORMAT."); MSOfficePrint a = new MSOfficePrint(); try { String sInputFileBasename = FileHelper.getBasename(_sInputFile); String fs = System.getProperty("file.separator"); FileHelper.makeDirectories("", _sReferencePath); String sOutputFile = _sReferencePath; if (sOutputFile.endsWith(fs)) { sOutputFile += sInputFileBasename; } else { sOutputFile += fs + sInputFileBasename; } a.storeToFileWithMSOffice(aGTA, _sInputFile, sOutputFile); } catch(ConvWatchCancelException e) { GlobalLogWriter.get().println(e.getMessage()); } catch(java.io.IOException e) { GlobalLogWriter.get().println(e.getMessage()); } } else { try { OfficePrint.convertDocument(_sInputFile, _sReferencePath, aGTA); } catch(ConvWatchCancelException e) { assure(e.getMessage(), false); } catch(ConvWatchException e) { assure(e.getMessage(), false); } } if (aGTA.restartOffice()) { // Office shutdown aProvider.closeExistingOffice(param, true); } } }
package com.vrg.rapid; import com.google.common.annotations.VisibleForTesting; import com.google.common.net.HostAndPort; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.SettableFuture; import com.vrg.rapid.pb.BatchedLinkUpdateMessage; import com.vrg.rapid.pb.ConsensusProposal; import com.vrg.rapid.pb.ConsensusProposalResponse; import com.vrg.rapid.pb.JoinMessage; import com.vrg.rapid.pb.JoinResponse; import com.vrg.rapid.pb.MembershipServiceGrpc; import com.vrg.rapid.pb.MembershipServiceGrpc.MembershipServiceFutureStub; import com.vrg.rapid.pb.ProbeMessage; import com.vrg.rapid.pb.ProbeResponse; import com.vrg.rapid.pb.Response; import io.grpc.Channel; import io.grpc.ClientInterceptor; import io.grpc.ClientInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.internal.ManagedChannelImpl; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; /** * MessagingServiceGrpc client. */ final class RpcClient { private static final Logger LOG = LoggerFactory.getLogger(RpcClient.class); static boolean USE_IN_PROCESS_CHANNEL = false; private final HostAndPort address; private final List<ClientInterceptor> interceptors; private final Map<HostAndPort, Channel> channelMap = new ConcurrentHashMap<>(); private static final ExecutorService GRPC_EXECUTORS = Executors.newFixedThreadPool(20); private static final ExecutorService BACKGROUND_EXECUTOR = Executors.newFixedThreadPool(20); private final RateLimiter broadcastRateLimiter = RateLimiter.create(100); private boolean shuttingDown = false; RpcClient(final HostAndPort address) { this(address, Collections.emptyList()); } RpcClient(final HostAndPort address, final List<ClientInterceptor> interceptors) { this.address = address; this.interceptors = interceptors; } /** * Send a protobuf ProbeMessage to a remote host. * * @param remote Remote host to send the message to * @param probeMessage Probing message for the remote node's failure detector module. * @return A future that returns a ProbeResponse if the call was successful. */ ListenableFuture<ProbeResponse> sendProbeMessage(final HostAndPort remote, final ProbeMessage probeMessage) { Objects.requireNonNull(remote); Objects.requireNonNull(probeMessage); final MembershipServiceFutureStub stub = getFutureStub(remote); return stub.withDeadlineAfter(Conf.RPC_PROBE_TIMEOUT, TimeUnit.MILLISECONDS).receiveProbe(probeMessage); } /** * Create and send a protobuf JoinMessage to a remote host. * * @param remote Remote host to send the message to * @param sender The node sending the join message * @return A future that returns a JoinResponse if the call was successful. */ ListenableFuture<JoinResponse> sendJoinMessage(final HostAndPort remote, final HostAndPort sender, final UUID uuid) { Objects.requireNonNull(remote); Objects.requireNonNull(sender); Objects.requireNonNull(uuid); final JoinMessage.Builder builder = JoinMessage.newBuilder(); final JoinMessage msg = builder.setSender(sender.toString()) .setUuid(uuid.toString()) .build(); final Supplier<ListenableFuture<JoinResponse>> call = () -> { final MembershipServiceFutureStub stub = getFutureStub(remote) .withDeadlineAfter(Conf.RPC_TIMEOUT_MS * 5, TimeUnit.MILLISECONDS); return stub.receiveJoinMessage(msg); }; return callWithRetries(call, remote, Conf.RPC_DEFAULT_RETRIES); } /** * Create and send a protobuf JoinPhase2Message to a remote host. * * @param remote Remote host to send the message to. This node is expected to initiate LinkUpdate-UP messages. * @param msg The JoinMessage for phase two. * @return A future that returns a JoinResponse if the call was successful. */ ListenableFuture<JoinResponse> sendJoinPhase2Message(final HostAndPort remote, final JoinMessage msg) { Objects.requireNonNull(remote); Objects.requireNonNull(msg); final Supplier<ListenableFuture<JoinResponse>> call = () -> { final MembershipServiceFutureStub stub = getFutureStub(remote) .withDeadlineAfter(Conf.RPC_JOIN_PHASE_2_TIMEOUT, TimeUnit.MILLISECONDS); return stub.receiveJoinPhase2Message(msg); }; return callWithRetries(call, remote, Conf.RPC_DEFAULT_RETRIES); } /** * Sends a consensus proposal to a remote node * * @param remote Remote host to send the message to. * @param msg Consensus proposal message */ void sendConsensusProposal(final HostAndPort remote, final ConsensusProposal msg) { Objects.requireNonNull(msg); BACKGROUND_EXECUTOR.execute(() -> { final Supplier<ListenableFuture<ConsensusProposalResponse>> call = () -> { broadcastRateLimiter.acquire(); final MembershipServiceFutureStub stub = getFutureStub(remote) .withDeadlineAfter(Conf.RPC_TIMEOUT_MS, TimeUnit.MILLISECONDS); return stub.receiveConsensusProposal(msg); }; callWithRetries(call, remote, Conf.RPC_DEFAULT_RETRIES); }); } /** * Sends a link update message to a remote node * * @param remote Remote host to send the message to. * @param msg A BatchedLinkUpdateMessage that contains one or more LinkUpdateMessages */ void sendLinkUpdateMessage(final HostAndPort remote, final BatchedLinkUpdateMessage msg) { Objects.requireNonNull(msg); BACKGROUND_EXECUTOR.execute(() -> { final Supplier<ListenableFuture<Response>> call = () -> { broadcastRateLimiter.acquire(); final MembershipServiceFutureStub stub = getFutureStub(remote) .withDeadlineAfter(Conf.RPC_TIMEOUT_MS, TimeUnit.MILLISECONDS); return stub.receiveLinkUpdateMessage(msg); }; callWithRetries(call, remote, Conf.RPC_DEFAULT_RETRIES); }); } /** * Clear all existing cached stubs and prepare new ones for a set of nodes. * * @param nodeSet set of nodes to prepare a long lived connection for */ void updateLongLivedConnections(final Set<HostAndPort> nodeSet) { // TODO: We need smarter policies to clear out channels we don't need. } /** * Create new long-lived channels for a set of nodes. * * @param nodeSet set of nodes to prepare a long lived connection for */ void createLongLivedConnections(final Set<HostAndPort> nodeSet) { } /** * Recover resources. For future use in case we provide custom GRPC_EXECUTORS for the ManagedChannels. */ void shutdown() { shuttingDown = true; channelMap.keySet().forEach(this::shutdownChannel); } private <T> ListenableFuture<T> callWithRetries(final Supplier<ListenableFuture<T>> call, final HostAndPort remote, final int retries) { final SettableFuture<T> settable = SettableFuture.create(); startCallWithRetry(call, remote, settable, retries); return settable; } @SuppressWarnings("checkstyle:illegalcatch") private <T> void startCallWithRetry(final Supplier<ListenableFuture<T>> call, final HostAndPort remote, final SettableFuture<T> signal, final int retries) { ListenableFuture<T> callFuture; if (shuttingDown) { return; } try { callFuture = call.get(); } catch (final Exception e) { handleFailure(call, remote, signal, retries, e); return; } Futures.addCallback(callFuture, new FutureCallback<T>() { @Override public void onSuccess(@Nullable final T result) { signal.set(result); } @Override public void onFailure(final Throwable throwable) { LOG.trace("Retrying call {}"); handleFailure(call, remote, signal, retries, throwable); } }, BACKGROUND_EXECUTOR); } private <T> void handleFailure(final Supplier<ListenableFuture<T>> code, final HostAndPort remote, final SettableFuture<T> future, final int retries, final Throwable t) { // GRPC returns an UNAVAILABLE error when the TCP connection breaks and there is no way to recover // from it . We therefore shutdown the channel, and subsequent calls will try to re-establish it. if (t instanceof StatusRuntimeException) { if (((StatusRuntimeException) t).getStatus().getCode().equals(Status.Code.UNAVAILABLE)) { shutdownChannel(remote); } } if (retries > 0) { startCallWithRetry(code, remote, future, retries - 1); } else { future.setException(t); } } private MembershipServiceFutureStub getFutureStub(final HostAndPort remote) { // TODO: allow configuring SSL/TLS Channel channel = channelMap.computeIfAbsent(remote, this::getChannel); if (interceptors.size() > 0) { channel = ClientInterceptors.intercept(channel, interceptors); } return MembershipServiceGrpc.newFutureStub(channel); } private void shutdownChannel(final HostAndPort remote) { final ManagedChannelImpl channel = (ManagedChannelImpl) channelMap.remove(remote); if (channel != null) { channel.shutdown(); } } private Channel getChannel(final HostAndPort remote) { // TODO: allow configuring SSL/TLS Channel channel; LOG.debug("Creating channel from {} to {}", address, remote); if (USE_IN_PROCESS_CHANNEL) { channel = InProcessChannelBuilder .forName(remote.toString()) .executor(GRPC_EXECUTORS) .usePlaintext(true) .idleTimeout(10, TimeUnit.SECONDS) .build(); } else { channel = NettyChannelBuilder .forAddress(remote.getHost(), remote.getPort()) .executor(GRPC_EXECUTORS) .withOption(ChannelOption.SO_REUSEADDR, true) .usePlaintext(true) .idleTimeout(10, TimeUnit.SECONDS) .build(); } return channel; } @VisibleForTesting static class Conf { static int RPC_TIMEOUT_MEDIUM_MS = 5000; static int RPC_TIMEOUT_MS = RPC_TIMEOUT_MEDIUM_MS; static int RPC_DEFAULT_RETRIES = 5; static int RPC_JOIN_PHASE_2_TIMEOUT = 5000; static int RPC_PROBE_TIMEOUT = 5000; } }
package raptor.swt; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import raptor.Quadrant; import raptor.Raptor; import raptor.RaptorWindowItem; import raptor.chat.BugGame; import raptor.chat.Bugger; import raptor.chat.Partnership; import raptor.pref.PreferenceKeys; import raptor.service.BughouseService; import raptor.service.ThreadService; import raptor.service.BughouseService.BughouseServiceListener; public class BugPartnersWindowItem implements RaptorWindowItem { public static final Quadrant[] MOVE_TO_QUADRANTS = { Quadrant.III, Quadrant.IV, Quadrant.V, Quadrant.VI, Quadrant.VII }; protected BughouseService service; protected Composite composite; protected Combo minAvailablePartnersFilter; protected Combo maxAvailablePartnersFilter; protected Table availablePartnersTable; protected Button isUpdating; protected boolean isActive = false; protected TableColumn lastStortedColumn; protected boolean wasLastSortAscending; protected Bugger[] currentBuggers; protected TableColumn ratingColumn; protected TableColumn nameColumn; protected TableColumn statusColumn; protected Runnable timer = new Runnable() { public void run() { if (isActive) { service.refreshUnpartneredBuggers(); ThreadService .getInstance() .scheduleOneShot( Raptor .getInstance() .getPreferences() .getInt( PreferenceKeys.APP_WINDOW_ITEM_POLL_INTERVAL) * 1000, this); } } }; protected BughouseServiceListener listener = new BughouseServiceListener() { public void availablePartnershipsChanged(Partnership[] newPartnerships) { } public void gamesInProgressChanged(BugGame[] newGamesInProgress) { } public void unpartneredBuggersChanged(Bugger[] newUnpartneredBuggers) { synchronized (availablePartnersTable) { Comparator<Bugger> comparator = getComparatorForRefresh(); currentBuggers = newUnpartneredBuggers; Arrays.sort(currentBuggers, comparator); refreshTable(); } } }; public static final String[] getRatings() { return new String[] { "0", "1", "700", "1000", "1100", "1200", "1300", "1400", "1500", "1600", "1700", "1800", "1900", "2000", "2100", "2200", "2300", "2400" }; } public BugPartnersWindowItem(BughouseService service) { this.service = service; service.addBughouseServiceListener(listener); } public void addItemChangedListener(ItemChangedListener listener) { } public void afterQuadrantMove(Quadrant newQuadrant) { } public boolean confirmClose() { return true; } public void dispose() { isActive = false; composite.dispose(); service.removeBughouseServiceListener(listener); } public Control getControl() { return composite; } public Image getImage() { return null; } public Quadrant[] getMoveToQuadrants() { return MOVE_TO_QUADRANTS; } public Quadrant getPreferredQuadrant() { return Raptor.getInstance().getPreferences().getQuadrant( service.getConnector().getShortName() + "-" + PreferenceKeys.BUG_WHO_QUADRANT); } public String getTitle() { return service.getConnector().getShortName() + "(Partners)"; } public Control getToolbar(Composite parent) { return null; } public void init(Composite parent) { composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Composite ratingFilterComposite = new Composite(composite, SWT.NONE); ratingFilterComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ratingFilterComposite.setLayout(new RowLayout()); minAvailablePartnersFilter = new Combo(ratingFilterComposite, SWT.DROP_DOWN | SWT.READ_ONLY); for (String rating : getRatings()) { minAvailablePartnersFilter.add(rating); } minAvailablePartnersFilter.select(Raptor.getInstance().getPreferences() .getInt(PreferenceKeys.BUG_ARENA_PARTNERS_INDEX)); minAvailablePartnersFilter .addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Raptor.getInstance().getPreferences().setValue( PreferenceKeys.BUG_ARENA_PARTNERS_INDEX, minAvailablePartnersFilter.getSelectionIndex()); Raptor.getInstance().getPreferences().save(); refreshTable(); } }); CLabel label = new CLabel(ratingFilterComposite, SWT.LEFT); label.setText(">= Rating <= "); maxAvailablePartnersFilter = new Combo(ratingFilterComposite, SWT.DROP_DOWN | SWT.READ_ONLY); for (String rating : getRatings()) { maxAvailablePartnersFilter.add(rating); } maxAvailablePartnersFilter.select(Raptor.getInstance().getPreferences() .getInt(PreferenceKeys.BUG_ARENA_MAX_PARTNERS_INDEX)); maxAvailablePartnersFilter .addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Raptor.getInstance().getPreferences().setValue( PreferenceKeys.BUG_ARENA_MAX_PARTNERS_INDEX, maxAvailablePartnersFilter.getSelectionIndex()); Raptor.getInstance().getPreferences().save(); refreshTable(); } }); isUpdating = new Button(ratingFilterComposite, SWT.CHECK); isUpdating.setText("Update"); isUpdating .setToolTipText("Toggles whether or not the table is being updated from events. " + "You can uncheck this to select a partner from a list without having to " + "fight the scrollbar then check it again to get a recent list."); isUpdating.setSelection(true); isUpdating.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (isUpdating.getSelection()) { refreshTable(); } } }); Composite tableComposite = new Composite(composite, SWT.NONE); tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tableComposite.setLayout(new FillLayout()); availablePartnersTable = new Table(tableComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); ratingColumn = new TableColumn(availablePartnersTable, SWT.LEFT); nameColumn = new TableColumn(availablePartnersTable, SWT.LEFT); statusColumn = new TableColumn(availablePartnersTable, SWT.LEFT); ratingColumn.setText("Rating"); nameColumn.setText("Name"); statusColumn.setText("Status"); ratingColumn.setWidth(50); nameColumn.setWidth(115); statusColumn.setWidth(90); ratingColumn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { synchronized (availablePartnersTable) { wasLastSortAscending = lastStortedColumn == null ? true : lastStortedColumn == ratingColumn ? !wasLastSortAscending : true; lastStortedColumn = ratingColumn; Arrays.sort(currentBuggers, wasLastSortAscending ? Bugger.BY_RATING_ASCENDING : Bugger.BY_RATING_DESCENDING); refreshTable(); } } }); nameColumn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { synchronized (availablePartnersTable) { wasLastSortAscending = lastStortedColumn == null ? true : lastStortedColumn == nameColumn ? !wasLastSortAscending : true; lastStortedColumn = nameColumn; Arrays.sort(currentBuggers, wasLastSortAscending ? Bugger.BY_NAME_ASCENDING : Bugger.BY_NAME_DESCENDING); refreshTable(); } } }); statusColumn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { synchronized (availablePartnersTable) { wasLastSortAscending = lastStortedColumn == null ? true : lastStortedColumn == statusColumn ? !wasLastSortAscending : true; lastStortedColumn = statusColumn; Arrays.sort(currentBuggers, wasLastSortAscending ? Bugger.BY_STATUS_ASCENDING : Bugger.BY_STATUS_DESCENDING); refreshTable(); } } }); availablePartnersTable.setHeaderVisible(true); Composite buttonsComposite = new Composite(composite, SWT.NONE); buttonsComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false)); buttonsComposite.setLayout(new RowLayout()); Button partnerSelected = new Button(buttonsComposite, SWT.PUSH); partnerSelected.setText("Partner Selected"); partnerSelected.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { int[] selectedIndexes = null; synchronized (availablePartnersTable) { selectedIndexes = availablePartnersTable .getSelectionIndices(); } if (selectedIndexes == null || selectedIndexes.length == 0) { Raptor.getInstance().alert( "You must first some select buggers to partner."); } else { synchronized (availablePartnersTable) { for (int i = 0; i < selectedIndexes.length; i++) { service.getConnector().onPartner( availablePartnersTable.getItem( selectedIndexes[i]).getText(1)); } } } } }); Button partnerAll = new Button(buttonsComposite, SWT.PUSH); partnerAll.setText("Partner All"); partnerAll.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { synchronized (availablePartnersTable) { TableItem[] items = availablePartnersTable.getItems(); for (TableItem item : items) { service.getConnector().onPartner(item.getText(1)); } } } }); if (currentBuggers != null) { Arrays.sort(currentBuggers, getComparatorForRefresh()); refreshTable(); } service.getUnpartneredBuggers(); } public void onActivate() { if (!isActive) { isActive = true; service.getUnpartneredBuggers(); ThreadService .getInstance() .scheduleOneShot( Raptor .getInstance() .getPreferences() .getInt( PreferenceKeys.APP_WINDOW_ITEM_POLL_INTERVAL) * 1000, timer); } } public void onPassivate() { if (isActive) { isActive = false; } } public void removeItemChangedListener(ItemChangedListener listener) { } protected Comparator<Bugger> getComparatorForRefresh() { Comparator<Bugger> comparator = null; if (lastStortedColumn == null) { comparator = Bugger.BY_RATING_DESCENDING; lastStortedColumn = ratingColumn; wasLastSortAscending = false; } else { if (lastStortedColumn == ratingColumn) { comparator = wasLastSortAscending ? Bugger.BY_RATING_ASCENDING : Bugger.BY_RATING_DESCENDING; } else if (lastStortedColumn == nameColumn) { comparator = wasLastSortAscending ? Bugger.BY_NAME_ASCENDING : Bugger.BY_NAME_DESCENDING; } else if (lastStortedColumn == statusColumn) { comparator = wasLastSortAscending ? Bugger.BY_STATUS_ASCENDING : Bugger.BY_STATUS_DESCENDING; } } return comparator; } protected boolean passesFilterCriteria(Bugger bugger) { int minFilterRating = Integer.parseInt(minAvailablePartnersFilter .getText()); int maxFilterRating = Integer.parseInt(maxAvailablePartnersFilter .getText()); if (minFilterRating >= maxFilterRating) { int tmp = maxFilterRating; maxFilterRating = minFilterRating; minFilterRating = tmp; } int buggerRating = bugger.getRatingAsInt(); return buggerRating >= minFilterRating && buggerRating <= maxFilterRating; } protected void refreshTable() { Raptor.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { if (isUpdating.getSelection()) { synchronized (availablePartnersTable) { int[] selectedIndexes = availablePartnersTable .getSelectionIndices(); List<String> selectedNamesBeforeRefresh = new ArrayList<String>( selectedIndexes.length); for (int index : selectedIndexes) { String name = availablePartnersTable.getItem(index) .getText(1); selectedNamesBeforeRefresh.add(name); } TableItem[] items = availablePartnersTable.getItems(); for (TableItem item : items) { item.dispose(); } for (Bugger bugger : currentBuggers) { if (passesFilterCriteria(bugger)) { TableItem tableItem = new TableItem( availablePartnersTable, SWT.NONE); tableItem.setText(new String[] { bugger.getRating(), bugger.getName(), bugger.getStatus().toString() }); } } List<Integer> indexes = new ArrayList<Integer>( selectedNamesBeforeRefresh.size()); TableItem[] newItems = availablePartnersTable .getItems(); for (int i = 0; i < newItems.length; i++) { if (selectedNamesBeforeRefresh.contains(newItems[i] .getText(1))) { indexes.add(i); } } if (indexes.size() > 0) { int[] indexesArray = new int[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { indexesArray[i] = indexes.get(i); } availablePartnersTable.select(indexesArray); } } } } }); } }
package bobby.main; import bobby.state.GameStateManager; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JPanel; /** * * @author Kiarash Korki <kiarash96@users.sf.net> */ public class GamePanel extends JPanel implements Runnable { // TODO: add scale public static final int WIDTH = 1024, HEIGHT = 768; private static final int FPS = 30; // Buffer image private Image image; private GameStateManager gsm; private KeyHandler kHandler; // game thread private Thread thread; private boolean running; public GamePanel() { super(); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setFocusable(true); requestFocus(); image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR); } @Override public void addNotify() { super.addNotify(); if (thread == null) { kHandler = new KeyHandler(); this.addKeyListener(kHandler); thread = new Thread(this); thread.start(); } } @Override public void run() { running = true; gsm = new GameStateManager(); while (running) { long start = System.nanoTime(); // update kHandler.update(); gsm.update(); Graphics g = image.getGraphics(); // clear the buffer g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); // draw on buffer gsm.draw(g); // draw the buffer on the screen this.getGraphics().drawImage(image, 0, 0, null); long elapsed = System.nanoTime() - start; long wait = (long)(Math.max(0.0, 1000.0/FPS - (double)(elapsed)/(1000 * 1000))); try { Thread.sleep(wait); } catch (InterruptedException ex) { Logger.getLogger(GamePanel.class.getName()).log(Level.SEVERE, null, ex); } } } }
/** * The traditional 8x8 chess board with pieces. */ package games.chess; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional import(s) here // <<-- /Creer-Merge: imports -->> /** * The traditional 8x8 chess board with pieces. */ public class Game extends BaseGame { /** * The player whose turn it is currently. That player can send commands. Other players cannot. */ public Player currentPlayer; /** * The current turn number, starting at 0 for the first player's turn. */ public int currentTurn; public String fen; /** * The maximum number of turns before the game will automatically end. */ public int maxTurns; /** * The list of Moves that have occured, in order. */ public List<Move> moves; /** * All the uncaptured Pieces in the game. */ public List<Piece> pieces; /** * List of all the players in the game. */ public List<Player> players; /** * A unique identifier for the game instance that is being played. */ public String session; /** * How many turns until the game ends because no pawn has moved and no Piece has been taken. */ public int turnsToDraw; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /** * Creates a new instance of a Game. Used during game initialization, do not call directly. */ public Game() { super(); this.name = "Chess"; this.moves = new ArrayList<Move>(); this.pieces = new ArrayList<Piece>(); this.players = new ArrayList<Player>(); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional method(s) here. // <<-- /Creer-Merge: methods -->> }
import java.net.*; import java.io.*; import java.util.*; import org.xbill.DNS.*; import org.xbill.DNS.utils.*; /** @author Brian Wellington &lt;bwelling@xbill.org&gt; */ public class update { Message query, response; Resolver res; String server = null; Name origin, zone; int defaultTTL; short defaultClass = DClass.IN; PrintStream log = null; void print(Object o) { System.out.println(o); if (log != null) log.println(o); } public update(InputStream in) throws IOException { Vector inputs = new Vector(); Vector istreams = new Vector(); query = new Message(); query.getHeader().setOpcode(Opcode.UPDATE); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); inputs.addElement(br); istreams.addElement(in); while (true) { try { String line = null; do { InputStream is; is = (InputStream) istreams.lastElement(); br = (BufferedReader)inputs.lastElement(); if (is == System.in) System.out.print("> "); line = Master.readExtendedLine(br); if (line == null) { br.close(); inputs.removeElement(br); istreams.removeElement(is); if (inputs.isEmpty()) return; } } while (line == null); if (log != null) log.println("> " + line); if (line.length() == 0 || line.charAt(0) == ' continue; /* Allows cut and paste from other update sessions */ if (line.charAt(0) == '>') line = line.substring(1); MyStringTokenizer st = new MyStringTokenizer(line); if (!st.hasMoreTokens()) continue; String operation = st.nextToken(); if (operation.equals("server")) { server = st.nextToken(); res = new SimpleResolver(server); } else if (operation.equals("key")) { String keyname = st.nextToken(); String keydata = st.nextToken(); if (res == null) res = new SimpleResolver(server); res.setTSIGKey(keyname, keydata); } else if (operation.equals("edns")) { if (res == null) res = new SimpleResolver(server); res.setEDNS(Short.parseShort(st.nextToken())); } else if (operation.equals("port")) { if (res == null) res = new SimpleResolver(server); res.setPort(Short.parseShort(st.nextToken())); } else if (operation.equals("tcp")) { if (res == null) res = new SimpleResolver(server); res.setTCP(true); } else if (operation.equals("class")) { String s = st.nextToken(); short newClass = DClass.value(s); if (newClass > 0) defaultClass = newClass; else print("Invalid class " + newClass); } else if (operation.equals("ttl")) defaultTTL = TTL.parseTTL(st.nextToken()); else if (operation.equals("origin")) origin = new Name(st.nextToken()); else if (operation.equals("zone")) zone = new Name(st.nextToken()); else if (operation.equals("require")) doRequire(st); else if (operation.equals("prohibit")) doProhibit(st); else if (operation.equals("add")) doAdd(st); else if (operation.equals("delete")) doDelete(st); else if (operation.equals("glue")) doGlue(st); else if (operation.equals("help")) { if (st.hasMoreTokens()) help(st.nextToken()); else help(null); } else if (operation.equals("echo")) print(line.substring(4).trim()); else if (operation.equals("send")) { if (res == null) res = new SimpleResolver(server); sendUpdate(); query = new Message(); query.getHeader().setOpcode(Opcode.UPDATE); } else if (operation.equals("show")) { print(query); } else if (operation.equals("query")) doQuery(st); else if (operation.equals("quit") || operation.equals("q")) { if (log != null) log.close(); Enumeration e = inputs.elements(); while (e.hasMoreElements()) { BufferedReader tbr; tbr = (BufferedReader) e.nextElement(); tbr.close(); } System.exit(0); } else if (operation.equals("file")) doFile(st, inputs, istreams); else if (operation.equals("log")) doLog(st); else if (operation.equals("assert")) { if (doAssert(st) == false) return; } else print("invalid keyword: " + operation); } catch (NullPointerException npe) { System.out.println("Parse error"); } catch (InterruptedIOException iioe) { System.out.println("Operation timed out"); } catch (SocketException se) { System.out.println("Socket error"); } } } void sendUpdate() throws IOException { if (query.getHeader().getCount(Section.UPDATE) == 0) { print("Empty update message. Ignoring."); return; } if (query.getHeader().getCount(Section.ZONE) == 0) { Name updzone; if (zone != null) updzone = zone; else updzone = origin; short dclass = defaultClass; if (updzone == null) { Enumeration updates = query.getSection(Section.UPDATE); if (updates == null) { print("Invalid update"); return; } Record r = (Record) updates.nextElement(); updzone = new Name(r.getName(), 1); dclass = r.getDClass(); } Record soa = Record.newRecord(updzone, Type.SOA, dclass); query.addRecord(soa, Section.ZONE); } response = res.send(query); if (response == null) return; print(response); } /* * <name> [ttl] [class] <type> <data> * Ignore the class, if present. */ Record parseRR(MyStringTokenizer st, short classValue, int TTLValue) throws IOException { Name name = new Name(st.nextToken(), origin); int ttl; short type; String s = st.nextToken(); try { ttl = TTL.parseTTL(s); s = st.nextToken(); } catch (NumberFormatException e) { ttl = TTLValue; } if (DClass.value(s) >= 0) s = st.nextToken(); if ((type = Type.value(s)) < 0) /* Close enough... */ throw new NullPointerException("Parse error"); return Record.fromString(name, type, classValue, ttl, st, origin); } /* * <name> <type> */ Record parseSet(MyStringTokenizer st, short classValue) throws IOException { Name name = new Name(st.nextToken(), origin); short type; if ((type = Type.value(st.nextToken())) < 0) throw new IOException("Parse error"); return Record.newRecord(name, type, classValue, 0); } /* * <name> */ Record parseName(MyStringTokenizer st, short classValue) throws IOException { Name name = new Name(st.nextToken(), origin); return Record.newRecord(name, Type.ANY, classValue, 0); } void doRequire(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.ANY); else if (qualifier.equals("-n")) rec = parseName(st, DClass.ANY); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.PREREQ); print(rec); } } void doProhibit(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.NONE); else if (qualifier.equals("-n")) rec = parseName(st, DClass.NONE); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.PREREQ); print(rec); } } void doAdd(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (!qualifier.startsWith("-")) { st.putBackToken(qualifier); qualifier = "-r"; } if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, defaultTTL); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.UPDATE); print(rec); } } void doDelete(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, DClass.NONE, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.ANY); else if (qualifier.equals("-n")) rec = parseName(st, DClass.ANY); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.UPDATE); print(rec); } } void doGlue(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (!qualifier.startsWith("-")) { st.putBackToken(qualifier); qualifier = "-r"; } if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, defaultTTL); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.ADDITIONAL); print(rec); } } void doQuery(MyStringTokenizer st) throws IOException { Record rec; Name name = null; short type = Type.A, dclass = defaultClass; name = new Name(st.nextToken(), origin); if (st.hasMoreTokens()) { type = Type.value(st.nextToken()); if (type < 0) throw new IOException("Invalid type"); if (st.hasMoreTokens()) { dclass = DClass.value(st.nextToken()); if (dclass < 0) throw new IOException("Invalid class"); } } rec = Record.newRecord(name, type, dclass); Message newQuery = Message.newQuery(rec); if (res == null) res = new SimpleResolver(server); response = res.send(newQuery); print(response); } void doFile(MyStringTokenizer st, Vector inputs, Vector istreams) { String s = st.nextToken(); try { InputStreamReader isr2; if (!s.equals("-")) { FileInputStream fis = new FileInputStream(s); isr2 = new InputStreamReader(fis); istreams.addElement(fis); } else { isr2 = new InputStreamReader(System.in); istreams.addElement(System.in); } BufferedReader br2 = new BufferedReader(isr2); inputs.addElement(br2); } catch (FileNotFoundException e) { print(s + "not found"); } } void doLog(MyStringTokenizer st) { String s = st.nextToken(); try { FileOutputStream fos = new FileOutputStream(s); log = new PrintStream(fos); } catch (Exception e) { print("Error opening " + s); } } boolean doAssert(MyStringTokenizer st) { String field = st.nextToken(); String expected = st.nextToken(); String value = null; boolean flag = true; int section; if (response == null) { print("No response has been received"); return true; } if (field.equalsIgnoreCase("rcode")) { short rcode = response.getHeader().getRcode(); if (rcode != Rcode.value(expected)) { value = Rcode.string(rcode); flag = false; } } else if (field.equalsIgnoreCase("serial")) { Record [] answers = response.getSectionArray(Section.ANSWER); if (answers.length < 1 || !(answers[0] instanceof SOARecord)) print("Invalid response (no SOA)"); else { SOARecord soa = (SOARecord) answers[0]; int serial = soa.getSerial(); if (serial != Integer.parseInt(expected)) { value = new Integer(serial).toString(); flag = false; } } } else if ((section = Section.value(field)) >= 0) { int count = response.getHeader().getCount(section); if (count != Integer.parseInt(expected)) { value = new Integer(count).toString(); flag = false; } } else print("Invalid assertion keyword: " + field); if (flag == false) { print("Expected " + field + " " + expected + ", received " + value); if (st.hasMoreTokens()) print(st.nextToken()); } return flag; } static void help(String topic) { System.out.println(); if (topic == null) System.out.println("The following are supported commands:\n" + "add assert class delete echo file\n" + "glue help log key edns origin\n" + "port prohibit query quit require send\n" + "server show tcp ttl zone else if (topic.equalsIgnoreCase("add")) System.out.println( "add [-r] <name> [ttl] [class] <type> <data>\n\n" + "specify a record to be added\n"); else if (topic.equalsIgnoreCase("assert")) System.out.println( "assert <field> <value> [msg]\n\n" + "asserts that the value of the field in the last\n" + "response matches the value specified. If not,\n" + "the message is printed (if present) and the\n" + "program exits. The field may be any of <rcode>,\n" + "<serial>, <qu>, <an>, <au>, or <ad>.\n"); else if (topic.equalsIgnoreCase("class")) System.out.println( "class <class>\n\n" + "class of the zone to be updated (default: IN)\n"); else if (topic.equalsIgnoreCase("delete")) System.out.println( "delete -r <name> [ttl] [class] <type> <data> \n" + "delete -s <name> <type> \n" + "delete -n <name>\n\n" + "specify a record or set to be deleted, or that\n" + "all records at a name should be deleted\n"); else if (topic.equalsIgnoreCase("echo")) System.out.println( "echo <text>\n\n" + "prints the text\n"); else if (topic.equalsIgnoreCase("file")) System.out.println( "file <file>\n\n" + "opens the specified file as the new input source\n" + "(- represents stdin)\n"); else if (topic.equalsIgnoreCase("glue")) System.out.println( "glue [-r] <name> [ttl] [class] <type> <data>\n\n" + "specify an additional record\n"); else if (topic.equalsIgnoreCase("help")) System.out.println( "help\n" + "help [topic]\n\n" + "prints a list of commands or help about a specific\n" + "command\n"); else if (topic.equalsIgnoreCase("log")) System.out.println( "log <file>\n\n" + "opens the specified file and uses it to log output\n"); else if (topic.equalsIgnoreCase("key")) System.out.println( "key <name> <data>\n\n" + "TSIG key used to sign messages\n"); else if (topic.equalsIgnoreCase("edns")) System.out.println( "edns <level>\n\n" + "EDNS level specified when sending messages\n"); else if (topic.equalsIgnoreCase("origin")) System.out.println( "origin <origin>\n\n" + "default origin of unqualified names (default: .)\n"); else if (topic.equalsIgnoreCase("port")) System.out.println( "port <port>\n\n" + "UDP/TCP port messages are sent to (default: 53)\n"); else if (topic.equalsIgnoreCase("prohibit")) System.out.println( "prohibit -r <name> [ttl] [class] <type> <data> \n" + "prohibit -s <name> <type> \n" + "prohibit -n <name>\n\n" + "require that a record, set, or name is not present\n"); else if (topic.equalsIgnoreCase("query")) System.out.println( "query <name> [type [class]] \n\n" + "issues a query\n"); else if (topic.equalsIgnoreCase("q") || topic.equalsIgnoreCase("quit")) System.out.println( "q/quit\n\n" + "quits the program\n"); else if (topic.equalsIgnoreCase("require")) System.out.println( "require -r <name> [ttl] [class] <type> <data> \n" + "require -s <name> <type> \n" + "require -n <name>\n\n" + "require that a record, set, or name is present\n"); else if (topic.equalsIgnoreCase("send")) System.out.println( "send\n\n" + "sends and resets the current update packet\n"); else if (topic.equalsIgnoreCase("server")) System.out.println( "server <name>\n\n" + "server that receives send updates/queries\n"); else if (topic.equalsIgnoreCase("show")) System.out.println( "show\n\n" + "shows the current update packet\n"); else if (topic.equalsIgnoreCase("tcp")) System.out.println( "tcp\n\n" + "TCP should be used to send all messages\n"); else if (topic.equalsIgnoreCase("ttl")) System.out.println( "ttl <ttl>\n\n" + "default ttl of added records (default: 0)\n"); else if (topic.equalsIgnoreCase("zone")) System.out.println( "zone <zone>\n\n" + "zone to update (default: value of <origin>\n"); else if (topic.equalsIgnoreCase(" System.out.println( "# <text>\n\n" + "a comment\n"); else System.out.println ("Topic " + topic + " unrecognized\n"); } public static void main(String args[]) throws IOException { InputStream in = null; if (args.length == 1) { try { in = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.out.println(args[0] + " not found."); System.exit(-1); } } else in = System.in; update u = new update(in); } }
package com.chrisdmilner.webapp; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import static org.junit.Assert.*; public class AnalyserTest { @org.junit.Test public void analyse() throws Exception { // Create the test data. Fact fbRoot = new Fact<>("Facebook User ID", "100008177116719", null); Fact twRoot = new Fact<>("Twitter Handle", "ChrisDMilner", null); Fact rdRoot = new Fact<>("Reddit User Name", "Radioactive1997", null); FactBook fb = new FactBook(); fb.addFact(new Fact<>("Name", "chrism", twRoot)); fb.addFact(new Fact<>("Name", "Christopher David Milner", fbRoot)); fb.addFact(new Fact<>("Name", "ChrisDMilner97", twRoot)); fb.addFact(new Fact<>("Name", "Chris Milner", twRoot)); fb.addFact(new Fact<>("Name", "Radioactive1997", rdRoot)); fb.addFact(new Fact<>("First Name", "Christopher", fbRoot)); fb.addFact(new Fact<>("Last Name", "Milner", fbRoot)); fb.addFact(new Fact<>("Image URL", "http://example.com/image.png", fbRoot)); try { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); fb.addFact(new Fact<>("Max Birth Date", df.parse("17/08/2005"), fbRoot)); fb.addFact(new Fact<>("Min Birth Date", df.parse("17/08/1995"), fbRoot)); fb.addFact(new Fact<>("Birth Year", df.parse("01/01/1997"), fbRoot)); } catch (ParseException e) { System.err.println("ERROR parsing the test date(s)"); e.printStackTrace(); } // Test that the analyser runs correctly and returns some conclusions. ArrayList<Conclusion> conclusions = Analyser.analyse(fb); assertTrue(conclusions.size() > 0); for (Conclusion c : conclusions) System.out.println(c.toString()); // Test if the generated JSON is valid. String json = Miner.conclusionsToJSON(conclusions); System.out.println(json); new JSONObject(json); } }
import java.util.*; import java.lang.*; import java.io.*; class Test { public int value; public int index; } class TestComparator implements Comparator<Test> { public int compare(Test a, Test b) { if (a.value < b.value) return -1; if (a.value > b.value) return 1; return 0; } } // structure to represent ranges within the array class Range { public int start; public int end; public Range(int start1, int end1) { start = start1; end = end1; } public Range() { start = 0; end = 0; } void set(int start1, int end1) { start = start1; end = end1; } int length() { return end - start; } } class WikiSorter<T> { // use a small cache to speed up some of the operations // since the cache size is fixed, it's still O(1) memory! // just keep in mind that making it too small ruins the point (nothing will fit into it), // and making it too large also ruins the point (so much for "low memory"!) // also, if you change this to dynamically allocate a full-size buffer, // the algorithm seamlessly degenerates into a standard merge sort! private static int cache_size = 512; private T[] cache; public WikiSorter() { @SuppressWarnings("unchecked") T[] cache1 = (T[])new Object[cache_size]; if (cache1 == null) cache_size = 0; else cache = cache1; } public static <T> void sort(T[] array, Comparator<T> comp) { new WikiSorter<T>().Sort(array, comp); } // toolbox functions used by the sorter // 63 -> 32, 64 -> 64, etc. // apparently this comes from Hacker's Delight? static int FloorPowerOfTwo(int value) { int x = value; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x - (x >> 1); } // find the index of the first value within the range that is equal to array[index] int BinaryFirst(T array[], T value, Range range, Comparator<T> comp) { int start = range.start, end = range.end - 1; while (start < end) { int mid = start + (end - start)/2; if (comp.compare(array[mid], value) < 0) start = mid + 1; else end = mid; } if (start == range.end - 1 && comp.compare(array[start], value) < 0) start++; return start; } // find the index of the last value within the range that is equal to array[index], plus 1 int BinaryLast(T array[], T value, Range range, Comparator<T> comp) { int start = range.start, end = range.end - 1; while (start < end) { int mid = start + (end - start)/2; if (comp.compare(value, array[mid]) >= 0) start = mid + 1; else end = mid; } if (start == range.end - 1 && comp.compare(value, array[start]) >= 0) start++; return start; } // n^2 sorting algorithm used to sort tiny chunks of the full array void InsertionSort(T array[], Range range, Comparator<T> comp) { for (int i = range.start + 1; i < range.end; i++) { T temp = array[i]; int j; for (j = i; j > range.start && comp.compare(temp, array[j - 1]) < 0; j array[j] = array[j - 1]; array[j] = temp; } } // reverse a range within the array void Reverse(T array[], Range range) { for (int index = range.length()/2 - 1; index >= 0; index T swap = array[range.start + index]; array[range.start + index] = array[range.end - index - 1]; array[range.end - index - 1] = swap; } } // swap a series of values in the array void BlockSwap(T array[], int start1, int start2, int block_size) { for (int index = 0; index < block_size; index++) { T swap = array[start1 + index]; array[start1 + index] = array[start2 + index]; array[start2 + index] = swap; } } // rotate the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1) void Rotate(T array[], int amount, Range range, boolean use_cache) { if (range.length() == 0) return; int split; if (amount >= 0) split = range.start + amount; else split = range.end + amount; Range range1 = new Range(range.start, split); Range range2 = new Range(split, range.end); if (use_cache) { // if the smaller of the two ranges fits into the cache, it's *slightly* faster copying it there and shifting the elements over if (range1.length() <= range2.length()) { if (range1.length() <= cache_size) { java.lang.System.arraycopy(array, range1.start, cache, 0, range1.length()); java.lang.System.arraycopy(array, range2.start, array, range1.start, range2.length()); java.lang.System.arraycopy(cache, 0, array, range1.start + range2.length(), range1.length()); return; } } else { if (range2.length() <= cache_size) { java.lang.System.arraycopy(array, range2.start, cache, 0, range2.length()); java.lang.System.arraycopy(array, range1.start, array, range2.end - range1.length(), range1.length()); java.lang.System.arraycopy(cache, 0, array, range1.start, range2.length()); return; } } } Reverse(array, range1); Reverse(array, range2); Reverse(array, range); } // standard merge operation using an internal buffer void Merge(T array[], Range buffer, Range A, Range B, Comparator<T> comp) { // if A fits into the cache, use that instead of the internal buffer if (A.length() <= cache_size) { int A_index = 0; int B_index = B.start; int insert_index = A.start; int A_last = A.length(); int B_last = B.end; if (B.length() > 0 && A.length() > 0) { while (true) { if (comp.compare(array[B_index], cache[A_index]) >= 0) { array[insert_index] = cache[A_index]; A_index++; insert_index++; if (A_index == A_last) break; } else { array[insert_index] = array[B_index]; B_index++; insert_index++; if (B_index == B_last) break; } } } // copy the remainder of A into the final array java.lang.System.arraycopy(cache, A_index, array, insert_index, A_last - A_index); } else { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order int A_count = 0, B_count = 0, insert = 0; if (B.length() > 0 && A.length() > 0) { while (true) { if (comp.compare(array[B.start + B_count], array[buffer.start + A_count]) >= 0) { T swap = array[A.start + insert]; array[A.start + insert] = array[buffer.start + A_count]; array[buffer.start + A_count] = swap; A_count++; insert++; if (A_count >= A.length()) break; } else { T swap = array[A.start + insert]; array[A.start + insert] = array[B.start + B_count]; array[B.start + B_count] = swap; B_count++; insert++; if (B_count >= B.length()) break; } } } // swap the remainder of A into the final array BlockSwap(array, buffer.start + A_count, A.start + insert, A.length() - A_count); } } // bottom-up merge sort combined with an in-place merge algorithm for O(1) memory use void Sort(T array[], Comparator<T> comp) { int size = array.length; // reverse any descending ranges in the array, as that will allow them to sort faster Range reverse = new Range(0, 1); for (int index = 1; index < size; index++) { if (comp.compare(array[index], array[index - 1]) < 0) reverse.end++; else { Reverse(array, reverse); reverse.set(index, index + 1); } } Reverse(array, reverse); // if there are 32 or fewer items, just insertion sort the entire array if (size <= 32) { InsertionSort(array, new Range(0, size), comp); return; } // calculate how to scale the index value to the range within the array // (this is essentially fixed-point math, where we manually check for and handle overflow) int power_of_two = FloorPowerOfTwo(size); int fractional_base = power_of_two/16; int fractional_step = size % fractional_base; int decimal_step = size/fractional_base; // first insertion sort everything the lowest level, which is 16-31 items at a time int decimal = 0, fractional = 0; while (decimal < size) { int start = decimal; decimal += decimal_step; fractional += fractional_step; if (fractional >= fractional_base) { fractional -= fractional_base; decimal++; } int end = decimal; InsertionSort(array, new Range(start, end), comp); } // we need to keep track of a lot of ranges during this sort! Range bufferA = new Range(), bufferB = new Range(); Range buffer1 = new Range(), buffer2 = new Range(); Range blockA = new Range(), blockB = new Range(); Range lastA = new Range(), lastB = new Range(); Range firstA = new Range(); Range level1 = new Range(), level2 = new Range(); Range levelA = new Range(), levelB = new Range(); Range A = new Range(), B = new Range(); // then merge sort the higher levels, which can be 32-63, 64-127, 128-255, etc. for (int merge_size = 16; merge_size < power_of_two; merge_size += merge_size) { int block_size = (int)Math.sqrt(decimal_step); int buffer_size = decimal_step/block_size + 1; // as an optimization, we really only need to pull out an internal buffer once for each level of merges // after that we can reuse the same buffer over and over, then redistribute it when we're finished with this level level1.set(0, 0); decimal = fractional = 0; while (decimal < size) { int start = decimal; decimal += decimal_step; fractional += fractional_step; if (fractional >= fractional_base) { fractional -= fractional_base; decimal++; } int mid = decimal; decimal += decimal_step; fractional += fractional_step; if (fractional >= fractional_base) { fractional -= fractional_base; decimal++; } int end = decimal; if (comp.compare(array[end - 1], array[start]) < 0) { // the two ranges are in reverse order, so a simple rotation should fix it Rotate(array, mid - start, new Range(start, end), true); } else if (comp.compare(array[mid], array[mid - 1]) < 0) { // these two ranges weren't already in order, so we'll need to merge them! A.set(start, mid); B.set(mid, end); // try to fill up two buffers with unique values in ascending order if (A.length() <= cache_size) { java.lang.System.arraycopy(array, A.start, cache, 0, A.length()); Merge(array, buffer2, A, B, comp); continue; } // try to fill up two buffers with unique values in ascending order if (level1.length() > 0) { // reuse the buffers we found in a previous iteration bufferA.set(A.start, A.start); bufferB.set(B.end, B.end); buffer1.set(level1.start, level1.end); buffer2.set(level2.start, level2.end); } else { // the first item is always going to be the first unique value, so let's start searching at the next index int count = 1; for (buffer1.start = A.start + 1; buffer1.start < A.end; buffer1.start++) if (comp.compare(array[buffer1.start - 1], array[buffer1.start]) != 0) if (++count == buffer_size) break; buffer1.end = buffer1.start + count; // if the size of each block fits into the cache, we only need one buffer for tagging the A blocks // this is because the other buffer is used as a swap space for merging the A blocks into the B values that follow it, // but we can just use the cache as the buffer instead. this skips some memmoves and an insertion sort if (buffer_size <= cache_size) { buffer2.set(A.start, A.start); if (buffer1.length() == buffer_size) { // we found enough values for the buffer in A bufferA.set(buffer1.start, buffer1.start + buffer_size); bufferB.set(B.end, B.end); buffer1.set(A.start, A.start + buffer_size); } else { // we were unable to find enough unique values in A, so try B bufferA.set(buffer1.start, buffer1.start); buffer1.set(A.start, A.start); // the last value is guaranteed to be the first unique value we encounter, so we can start searching at the next index count = 1; for (buffer1.start = B.end - 2; buffer1.start >= B.start; buffer1.start if (comp.compare(array[buffer1.start], array[buffer1.start + 1]) != 0) if (++count == buffer_size) break; buffer1.end = buffer1.start + count; if (buffer1.length() == buffer_size) { bufferB.set(buffer1.start, buffer1.start + buffer_size); buffer1.set(B.end - buffer_size, B.end); } } } else { // the first item of the second buffer isn't guaranteed to be the first unique value, so we need to find the first unique item too count = 0; for (buffer2.start = buffer1.start + 1; buffer2.start < A.end; buffer2.start++) if (comp.compare(array[buffer2.start - 1], array[buffer2.start]) != 0) if (++count == buffer_size) break; buffer2.end = buffer2.start + count; if (buffer2.length() == buffer_size) { // we found enough values for both buffers in A bufferA.set(buffer2.start, buffer2.start + buffer_size * 2); bufferB.set(B.end, B.end); buffer1.set(A.start, A.start + buffer_size); buffer2.set(A.start + buffer_size, A.start + buffer_size * 2); } else if (buffer1.length() == buffer_size) { // we found enough values for one buffer in A, so we'll need to find one buffer in B bufferA.set(buffer1.start, buffer1.start + buffer_size); buffer1.set(A.start, A.start + buffer_size); // like before, the last value is guaranteed to be the first unique value we encounter, so we can start searching at the next index count = 1; for (buffer2.start = B.end - 2; buffer2.start >= B.start; buffer2.start if (comp.compare(array[buffer2.start], array[buffer2.start + 1]) != 0) if (++count == buffer_size) break; buffer2.end = buffer2.start + count; if (buffer2.length() == buffer_size) { bufferB.set(buffer2.start, buffer2.start + buffer_size); buffer2.set(B.end - buffer_size, B.end); } else buffer1.end = buffer1.start; // failure } else { // we were unable to find a single buffer in A, so we'll need to find two buffers in B count = 1; for (buffer1.start = B.end - 2; buffer1.start >= B.start; buffer1.start if (comp.compare(array[buffer1.start], array[buffer1.start + 1]) != 0) if (++count == buffer_size) break; buffer1.end = buffer1.start + count; count = 0; for (buffer2.start = buffer1.start - 1; buffer2.start >= B.start; buffer2.start if (comp.compare(array[buffer2.start], array[buffer2.start + 1]) != 0) if (++count == buffer_size) break; buffer2.end = buffer2.start + count; if (buffer2.length() == buffer_size) { bufferA.set(A.start, A.start); bufferB.set(buffer2.start, buffer2.start + buffer_size * 2); buffer1.set(B.end - buffer_size, B.end); buffer2.set(buffer1.start - buffer_size, buffer1.start); } else buffer1.end = buffer1.start; // failure } } if (buffer1.length() < buffer_size) { // we failed to fill both buffers with unique values, which implies we're merging two subarrays with a lot of the same values repeated // we can use this knowledge to write a merge operation that is optimized for arrays of repeating values while (A.length() > 0 && B.length() > 0) { // find the first place in B where the first item in A needs to be inserted int split = BinaryFirst(array, array[A.start], B, comp); // rotate A into place int amount = split - A.end; Rotate(array, -amount, new Range(A.start, split), true); // calculate the new A and B ranges B.start = split; A.set(BinaryLast(array, array[A.start + amount], A, comp), B.start); } continue; } // move the unique values to the start of A if needed int length = bufferA.length(); count = 0; for (int index = bufferA.start; count < length; index if (index == A.start || comp.compare(array[index - 1], array[index]) != 0) { Rotate(array, -count, new Range(index + 1, bufferA.start + 1), true); bufferA.start = index + count; count++; } } bufferA.set(A.start, A.start + length); // move the unique values to the end of B if needed length = bufferB.length(); count = 0; for (int index = bufferB.start; count < length; index++) { if (index == B.end - 1 || comp.compare(array[index], array[index + 1]) != 0) { Rotate(array, count, new Range(bufferB.start, index), true); bufferB.start = index - count; count++; } } bufferB.set(B.end - length, B.end); // reuse these buffers next time! level1.set(buffer1.start, buffer1.end); level2.set(buffer2.start, buffer2.end); levelA.set(bufferA.start, bufferA.end); levelB.set(bufferB.start, bufferB.end); } // break the remainder of A into blocks. firstA is the uneven-sized first A block blockA.set(bufferA.end, A.end); firstA.set(bufferA.end, bufferA.end + blockA.length() % block_size); // swap the second value of each A block with the value in buffer1 int index = 0; for (int indexA = firstA.end + 1; indexA < blockA.end; indexA += block_size) { T swap = array[buffer1.start + index]; array[buffer1.start + index] = array[indexA]; array[indexA] = swap; index++; } // start rolling the A blocks through the B blocks! // whenever we leave an A block behind, we'll need to merge the previous A block with any B blocks that follow it, so track that information as well lastA.set(firstA.start, firstA.end); lastB.set(0, 0); blockB.set(B.start, B.start + Math.min(block_size, B.length() - bufferB.length())); blockA.start += firstA.length(); int minA = blockA.start; int indexA = 0; T min_value = array[minA]; if (lastA.length() <= cache_size) java.lang.System.arraycopy(array, lastA.start, cache, 0, lastA.length()); else BlockSwap(array, lastA.start, buffer2.start, lastA.length()); while (true) { // if there's a previous B block and the first value of the minimum A block is <= the last value of the previous B block if ((lastB.length() > 0 && comp.compare(array[lastB.end - 1], min_value) >= 0) || blockB.length() == 0) { // figure out where to split the previous B block, and rotate it at the split int B_split = BinaryFirst(array, min_value, lastB, comp); int B_remaining = lastB.end - B_split; // swap the minimum A block to the beginning of the rolling A blocks BlockSwap(array, blockA.start, minA, block_size); // we need to swap the second item of the previous A block back with its original value, which is stored in buffer1 // since the firstA block did not have its value swapped out, we need to make sure the previous A block is not unevenly sized T swap = array[blockA.start + 1]; array[blockA.start + 1] = array[buffer1.start + indexA]; array[buffer1.start + indexA] = swap; indexA++; // locally merge the previous A block with the B values that follow it, using the buffer as swap space Merge(array, buffer2, lastA, new Range(lastA.end, B_split), comp); // copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway if (block_size <= cache_size) java.lang.System.arraycopy(array, blockA.start, cache, 0, block_size); else BlockSwap(array, blockA.start, buffer2.start, block_size); // this is equivalent to rotating, but faster // the area normally taken up by the A block is either the contents of buffer2, or data we don't need anymore since we memcopied it // either way, we don't need to retain the order of those items, so instead of rotating we can just block swap B to where it belongs BlockSwap(array, B_split, blockA.start + block_size - B_remaining, B_remaining); // now we need to update the ranges and stuff lastA.set(blockA.start - B_remaining, blockA.start - B_remaining + block_size); lastB.set(lastA.end, lastA.end + B_remaining); blockA.start += block_size; if (blockA.length() == 0) break; // search the second value of the remaining A blocks to find the new minimum A block (that's why we wrote unique values to them!) minA = blockA.start + 1; for (int findA = minA + block_size; findA < blockA.end; findA += block_size) if (comp.compare(array[findA], array[minA]) < 0) minA = findA; minA = minA - 1; // decrement once to get back to the start of that A block min_value = array[minA]; } else if (blockB.length() < block_size) { // move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation // (using the cache is disabled since we have the contents of the previous A block in it!) Rotate(array, -blockB.length(), new Range(blockA.start, blockB.end), false); lastB.set(blockA.start, blockA.start + blockB.length()); blockA.start += blockB.length(); blockA.end += blockB.length(); minA += blockB.length(); blockB.end = blockB.start; } else { // roll the leftmost A block to the end by swapping it with the next B block BlockSwap(array, blockA.start, blockB.start, block_size); lastB.set(blockA.start, blockA.start + block_size); if (minA == blockA.start) minA = blockA.end; blockA.start += block_size; blockA.end += block_size; blockB.start += block_size; blockB.end += block_size; if (blockB.end > bufferB.start) blockB.end = bufferB.start; } } // merge the last A block with the remaining B blocks Merge(array, buffer2, lastA, new Range(lastA.end, B.end - bufferB.length()), comp); } } if (level1.length() > 0) { // when we're finished with this step we should have b1 b2 left over, where one of the buffers is all jumbled up // insertion sort the jumbled up buffer, then redistribute them back into the array using the opposite process used for creating the buffer InsertionSort(array, level2, comp); // redistribute bufferA back into the array int level_start = levelA.start; for (int index = levelA.end; levelA.length() > 0; index++) { if (index == levelB.start || comp.compare(array[index], array[levelA.start]) >= 0) { int amount = index - levelA.end; Rotate(array, -amount, new Range(levelA.start, index), true); levelA.start += (amount + 1); levelA.end += amount; index } } // redistribute bufferB back into the array for (int index = levelB.start; levelB.length() > 0; index if (index == level_start || comp.compare(array[levelB.end - 1], array[index - 1]) >= 0) { int amount = levelB.start - index; Rotate(array, amount, new Range(index, levelB.end), true); levelB.start -= amount; levelB.end -= (amount + 1); index++; } } } decimal_step += decimal_step; fractional_step += fractional_step; if (fractional_step >= fractional_base) { fractional_step -= fractional_base; decimal_step += 1; } } } } class MergeSorter<T> { // n^2 sorting algorithm used to sort tiny chunks of the full array void InsertionSort(T array[], Range range, Comparator<T> comp) { for (int i = range.start + 1; i < range.end; i++) { T temp = array[i]; int j; for (j = i; j > range.start && comp.compare(temp, array[j - 1]) < 0; j array[j] = array[j - 1]; array[j] = temp; } } // standard merge sort, so we have a baseline for how well the in-place merge works void SortR(T array[], Range range, Comparator<T> comp, T buffer[]) { if (range.length() < 32) { // insertion sort InsertionSort(array, range, comp); return; } int mid = range.start + (range.end - range.start)/2; Range A = new Range(range.start, mid); Range B = new Range(mid, range.end); SortR(array, A, comp, buffer); SortR(array, B, comp, buffer); // standard merge operation here (only A is copied to the buffer) java.lang.System.arraycopy(array, A.start, buffer, 0, A.length()); int A_count = 0, B_count = 0, insert = 0; while (A_count < A.length() && B_count < B.length()) { if (comp.compare(array[A.end + B_count], buffer[A_count]) >= 0) { array[A.start + insert] = buffer[A_count]; A_count++; } else { array[A.start + insert] = array[A.end + B_count]; B_count++; } insert++; } java.lang.System.arraycopy(buffer, A_count, array, A.start + insert, A.length() - A_count); } void Sort(T array[], Comparator<T> comp) { @SuppressWarnings("unchecked") T[] buffer = (T[]) new Object[array.length]; SortR(array, new Range(0, array.length), comp, buffer); } public static <T> void sort(T[] array, Comparator<T> comp) { new MergeSorter<T>().Sort(array, comp); } } class SortRandom { public static Random rand; public static int nextInt(int max) { // set the seed on the random number generator if (rand == null) rand = new Random(10141985); return rand.nextInt(max); } public static int nextInt() { return nextInt(2147483647); } } class Testing { int value(int index, int total) { return index; } } class TestingPathological extends Testing { int value(int index, int total) { if (index == 0) return 10; else if (index < total/2) return 11; else if (index == total - 1) return 10; return 9; } } class TestingRandom extends Testing { int value(int index, int total) { return SortRandom.nextInt(); } } class TestingMostlyDescending extends Testing { int value(int index, int total) { return total - index + SortRandom.nextInt(5) - 2; } } class TestingMostlyAscending extends Testing { int value(int index, int total) { return index + SortRandom.nextInt(5) - 2; } } class TestingAscending extends Testing { int value(int index, int total) { return index; } } class TestingDescending extends Testing { int value(int index, int total) { return total - index; } } class TestingEqual extends Testing { int value(int index, int total) { return 1000; } } class TestingJittered extends Testing { int value(int index, int total) { return (SortRandom.nextInt(100) <= 90) ? index : (index - 2); } } class TestingMostlyEqual extends Testing { int value(int index, int total) { return 1000 + SortRandom.nextInt(4); } } class WikiSort { static double Seconds() { return System.currentTimeMillis()/1000.0; } static void Verify(Test array[], Range range, TestComparator comp, String msg) { for (int index = range.start + 1; index < range.end; index++) { // if it's in ascending order then we're good // if both values are equal, we need to make sure the index values are ascending if (!(comp.compare(array[index - 1], array[index]) < 0 || (comp.compare(array[index], array[index - 1]) == 0 && array[index].index > array[index - 1].index))) { //for (int index2 = range.start; index2 < range.end; index2++) // System.out.println(array[index2].value + " (" + array[index2].index + ")"); System.out.println("failed with message: " + msg); throw new RuntimeException(); } } } public static void main (String[] args) throws java.lang.Exception { int max_size = 1500000; TestComparator comp = new TestComparator(); Test[] array1; Test[] array2; Testing[] test_cases = { new TestingPathological(), new TestingRandom(), new TestingMostlyDescending(), new TestingMostlyAscending(), new TestingAscending(), new TestingDescending(), new TestingEqual(), new TestingJittered(), new TestingMostlyEqual() }; WikiSorter<Test> Wiki = new WikiSorter<Test>(); MergeSorter<Test> Merge = new MergeSorter<Test>(); System.out.println("running test cases..."); int total = max_size; array1 = new Test[total]; array2 = new Test[total]; for (int test_case = 0; test_case < test_cases.length; test_case++) { for (int index = 0; index < total; index++) { Test item = new Test(); item.value = test_cases[test_case].value(index, total); item.index = index; array1[index] = item; array2[index] = item; } Wiki.Sort(array1, comp); Merge.Sort(array2, comp); Verify(array1, new Range(0, total), comp, "test case failed"); if (total > 0) if (comp.compare(array1[0], array2[0]) != 0) throw new Exception(); for (int index = 1; index < total; index++) { if (comp.compare(array1[index], array2[index]) != 0) throw new Exception(); if (array2[index].index != array1[index].index) throw new Exception(); } } System.out.println("passed!"); double total_time = Seconds(); double total_time1 = 0, total_time2 = 0; for (total = 0; total < max_size; total += 2048 * 16) { array1 = new Test[total]; array2 = new Test[total]; for (int index = 0; index < total; index++) { Test item = new Test(); item.value = SortRandom.nextInt(); item.index = index; array1[index] = item; array2[index] = item; } double time1 = Seconds(); Wiki.Sort(array1, comp); time1 = Seconds() - time1; total_time1 += time1; double time2 = Seconds(); Merge.Sort(array2, comp); time2 = Seconds() - time2; total_time2 += time2; System.out.println("[" + total + "] wiki: " + time1 + ", merge: " + time2 + " (" + time2/time1 * 100 + "%)"); // make sure the arrays are sorted correctly, and that the results were stable System.out.println("verifying..."); Verify(array1, new Range(0, total), comp, "testing the final array"); if (total > 0) if (comp.compare(array1[0], array2[0]) != 0) throw new Exception(); for (int index = 1; index < total; index++) { if (comp.compare(array1[index], array2[index]) != 0) throw new Exception(); if (array2[index].index != array1[index].index) throw new Exception(); } System.out.println("correct!"); } total_time = Seconds() - total_time; System.out.println("tests completed in " + total_time + " seconds"); System.out.println("wiki: " + total_time1 + ", merge: " + total_time2 + " (" + total_time2/total_time1 * 100 + "%)"); } }
package org.batfish.client; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.WriterOutputStream; import org.batfish.common.BfConsts; import org.batfish.common.BatfishLogger; import org.batfish.common.WorkItem; import org.batfish.common.CoordConsts.WorkStatusCode; import jline.console.ConsoleReader; import jline.console.completer.Completer; import jline.console.completer.StringsCompleter; public class Client { private static final String COMMAND_ANSWER = "answer"; private static final String COMMAND_ANSWER_DIFF = "answer-diff"; private static final String COMMAND_CLEAR_SCREEN = "cls"; private static final String COMMAND_GEN_DIFF_DP = "generate-diff-dataplane"; private static final String COMMAND_GEN_DP = "generate-dataplane"; private static final String COMMAND_HELP = "help"; private static final String COMMAND_INIT_DIFF_ENV = "init-diff-environment"; private static final String COMMAND_INIT_TESTRIG = "init-testrig"; private static final String COMMAND_QUIT = "quit"; private static final String COMMAND_SET_DIFF_ENV = "set-diff-environment"; private static final String COMMAND_SET_LOGLEVEL = "set-loglevel"; private static final String COMMAND_SET_TESTRIG = "set-testrig"; private static final Map<String, String> MAP_COMMANDS = initCommands(); private static Map<String, String> initCommands() { Map<String, String> descs = new HashMap<String, String>(); descs.put(COMMAND_ANSWER, COMMAND_ANSWER + " <question-name> <question-file>\n" + "\t Answer the question for the default environment"); descs.put(COMMAND_ANSWER_DIFF, COMMAND_ANSWER_DIFF + " <question-name> <question-file>\n" + "\t Answer the question for the differential environment"); descs.put(COMMAND_CLEAR_SCREEN, COMMAND_CLEAR_SCREEN + "\n" + "\t Clear screen"); descs.put(COMMAND_GEN_DIFF_DP, COMMAND_GEN_DIFF_DP + "\n" + "\t Generate dataplane for the differential environment"); descs.put(COMMAND_GEN_DP, COMMAND_GEN_DP + "\n" + "\t Generate dataplane for the default environment"); descs.put(COMMAND_HELP, "help\n" + "\t Print the list of supported commands"); descs.put(COMMAND_INIT_DIFF_ENV, COMMAND_INIT_DIFF_ENV + " <environment-name> <environment-file>\n" + "\t Initialize the differential environment"); descs.put(COMMAND_INIT_TESTRIG, COMMAND_INIT_TESTRIG + " <environment-name> <environment-file>\n" + "\t Initialize the testrig with default environment"); descs.put(COMMAND_QUIT, COMMAND_QUIT + "\n" + "\t Clear screen"); descs.put(COMMAND_SET_DIFF_ENV, COMMAND_SET_DIFF_ENV + " <environment-name>\n" + "\t Set the current differential environment"); descs.put(COMMAND_SET_LOGLEVEL, COMMAND_SET_LOGLEVEL + " <debug|info|output|warn|error>\n" + "\t Set the loglevel. Default is output"); descs.put(COMMAND_SET_TESTRIG, COMMAND_SET_TESTRIG + " <testrig-name>\n" + "\t Set the current testrig"); return descs; } private String _currDiffEnv = null; private String _currEnv = null; private String _currTestrigName = null; private BatfishLogger _logger; private BfCoordPoolHelper _poolHelper; private BfCoordWorkHelper _workHelper; public Client(Settings settings) { if (settings.getCommandFile() != null) { RunBatchMode(settings); } else { RunInteractiveMode(settings); } } private File createParamsFile(String[] words, int startIndex, int endIndex) throws IOException { String paramsLine = String.join(" ", Arrays.copyOfRange(words, startIndex, endIndex + 1)); File paramFile = Files.createTempFile("params", null).toFile(); _logger.debugf("Creating temporary params file: %s\n", paramFile.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new FileWriter(paramFile)); writer.write("#parameters for the question\n"); writer.write(paramsLine + "\n"); // for (int index = startIndex; index <= endIndex; index++) { // writer.write(words[index] + "\n"); writer.close(); return paramFile; } private boolean execute(WorkItem wItem) throws Exception { wItem.addRequestParam(BfConsts.ARG_LOG_LEVEL, _logger.getLogLevelStr()); _logger.info("work-id is " + wItem.getId() + "\n"); boolean queueWorkResult = _workHelper.queueWork(wItem); _logger.info("Queuing result: " + queueWorkResult + "\n"); if (!queueWorkResult) { return queueWorkResult; } WorkStatusCode status = _workHelper.getWorkStatus(wItem.getId()); while (status != WorkStatusCode.TERMINATEDABNORMALLY && status != WorkStatusCode.TERMINATEDNORMALLY && status != WorkStatusCode.ASSIGNMENTERROR) { _logger.output(". "); _logger.infof("status: %s\n", status); Thread.sleep(1 * 1000); status = _workHelper.getWorkStatus(wItem.getId()); } _logger.output("\n"); _logger.infof("final status: %s\n", status); // get the results String logFileName = wItem.getId() + ".log"; String downloadedFile = _workHelper.getObject(wItem.getTestrigName(), logFileName); if (downloadedFile == null) { _logger.errorf("Failed to get output file %s\n", logFileName); return false; } else { try (BufferedReader br = new BufferedReader(new FileReader( downloadedFile))) { String line = null; while ((line = br.readLine()) != null) { _logger.output(line + "\n"); } } } // TODO: remove the log file? if (status == WorkStatusCode.TERMINATEDNORMALLY) { return true; } else { // _logger.errorf("WorkItem failed: %s", wItem); return false; } } private void printUsage() { for (Map.Entry<String, String> entry : MAP_COMMANDS.entrySet()) { _logger.output(entry.getValue() + "\n\n"); } } private void processCommand(String[] words) { try { switch (words[0]) { // this is almost a hidden command; it should not be invoked through // here case "add-worker": { boolean result = _poolHelper.addBatfishWorker(words[1]); _logger.output("Result: " + result + "\n"); break; } case COMMAND_ANSWER: { String questionName = words[1]; String questionFile = words[2]; if (_currTestrigName == null || _currEnv == null) { _logger .errorf( "Active testrig name or environment is not set: (%s, %s)\n", _currTestrigName, _currEnv); break; } File paramsFile = null; try { paramsFile = createParamsFile(words, 3, words.length - 1); } catch (Exception e) { _logger.error("Could not create params file\n"); break; } // upload the question boolean resultUpload = _workHelper.uploadQuestion(_currTestrigName, questionName, questionFile, paramsFile); if (resultUpload) { _logger .output("Successfully uploaded question. Starting to answer\n"); } else { break; } // delete the temporary params file if (paramsFile != null) { paramsFile.delete(); } // answer the question WorkItem wItemAs = _workHelper.getWorkItemAnswerQuestion( questionName, _currTestrigName, _currEnv, _currDiffEnv); execute(wItemAs); break; } case COMMAND_ANSWER_DIFF: { if (_currTestrigName == null || _currEnv == null || _currDiffEnv == null) { _logger .errorf( "Active testrig, environment, or differential environment is not set (%s, %s, %s)\n", _currTestrigName, _currEnv, _currDiffEnv); break; } String questionName = words[1]; String questionFile = words[2]; if (_currTestrigName == null || _currEnv == null) { _logger .errorf( "Active testrig name or environment is not set: (%s, %s)\n", _currTestrigName, _currEnv); break; } File paramsFile = null; try { paramsFile = createParamsFile(words, 3, words.length - 1); } catch (Exception e) { _logger.error("Could not create params file\n"); break; } // upload the question boolean resultUpload = _workHelper.uploadQuestion(_currTestrigName, questionName, questionFile, paramsFile); if (resultUpload) { _logger .output("Successfully uploaded question. Starting to answer\n"); } else { break; } // delete the temporary params file if (paramsFile != null) { paramsFile.delete(); } // answer the question WorkItem wItemAs = _workHelper.getWorkItemAnswerDiffQuestion( questionName, _currTestrigName, _currEnv, _currDiffEnv); execute(wItemAs); break; } case COMMAND_GEN_DP: { if (_currTestrigName == null || _currEnv == null) { _logger .errorf( "Active testrig name or environment is not set (%s, %s)\n", _currTestrigName, _currEnv); break; } // generate the data plane WorkItem wItemGenDp = _workHelper.getWorkItemGenerateDataPlane( _currTestrigName, _currEnv); boolean resultGenDp = execute(wItemGenDp); if (!resultGenDp) { break; } // get the data plane WorkItem wItemGetDp = _workHelper.getWorkItemGetDataPlane( _currTestrigName, _currEnv); boolean resultGetDp = execute(wItemGetDp); if (!resultGetDp) { break; } break; } case COMMAND_GEN_DIFF_DP: { if (_currTestrigName == null || _currEnv == null || _currDiffEnv == null) { _logger .errorf( "Active testrig, environment, or differential environment is not set (%s, %s, %s)\n", _currTestrigName, _currEnv, _currDiffEnv); break; } // generate the data plane WorkItem wItemGenDdp = _workHelper .getWorkItemGenerateDiffDataPlane(_currTestrigName, _currEnv, _currDiffEnv); boolean resultGenDdp = execute(wItemGenDdp); if (!resultGenDdp) { break; } // get the data plane WorkItem wItemGetDdp = _workHelper.getWorkItemGetDiffDataPlane( _currTestrigName, _currEnv, _currDiffEnv); boolean resultGetDdp = execute(wItemGetDdp); if (!resultGetDdp) { break; } break; } case COMMAND_HELP: { printUsage(); break; } case COMMAND_INIT_DIFF_ENV: { String diffEnvName = words[1]; String diffEnvFile = words[2]; if (_currTestrigName == null) { _logger.errorf("Active testrig is not set\n"); break; } // upload the environment boolean resultUpload = _workHelper.uploadEnvironment( _currTestrigName, diffEnvName, diffEnvFile); if (resultUpload) { _logger.output("Successfully uploaded environment.\n"); } else { break; } _currDiffEnv = diffEnvName; _logger.outputf( "Active differential environment is now set to %s\n", _currDiffEnv); break; } case COMMAND_INIT_TESTRIG: { String testrigName = words[1]; String testrigFile = words[2]; // upload the testrig boolean resultUpload = _workHelper.uploadTestrig(testrigName, testrigFile); if (resultUpload) { _logger .output("Successfully uploaded testrig. Starting parsing\n"); } else { break; } // vendor specific parsing WorkItem wItemPvs = _workHelper .getWorkItemParseVendorSpecific(testrigName); boolean resultPvs = execute(wItemPvs); if (!resultPvs) { break; } // vendor independent parsing WorkItem wItemPvi = _workHelper .getWorkItemParseVendorIndependent(testrigName); boolean resultPvi = execute(wItemPvi); if (!resultPvi) { break; } // upload a default environment boolean resultUploadEnv = _workHelper.uploadEnvironment( testrigName, "default", testrigFile); _logger.info("Result of uploading default environment: " + resultUploadEnv); // set the name of the current testrig _currTestrigName = testrigName; _currEnv = "default"; _logger.outputf( "Active (testrig, environment) is now set to (%s, %s)\n", _currTestrigName, _currEnv); break; } case COMMAND_SET_TESTRIG: { String testrigName = words[1]; _currTestrigName = testrigName; _currEnv = "default"; _logger.outputf( "Active (testrig, environment) is now set to (%s, %s)\n", _currTestrigName, _currEnv); break; } case COMMAND_SET_DIFF_ENV: { String diffEnvName = words[1]; _currDiffEnv = diffEnvName; _logger.outputf( "Active differential environment is now set to %s\n", _currDiffEnv); break; } case COMMAND_SET_LOGLEVEL: { String logLevelStr = words[1]; try { _logger.setLogLevel(logLevelStr); _logger.output("Changed loglevel to " + logLevelStr + "\n"); } catch (Exception e) { _logger.errorf("Undefined loglevel value: %s\n", logLevelStr); } break; } default: _logger.error("Unsupported command " + words[0] + "\n"); _logger.error("Type 'help' to see the list of valid commands\n"); } } catch (Exception e) { e.printStackTrace(); } } private void RunBatchMode(Settings settings) { _logger = new BatfishLogger(settings.getLogLevel(), false, settings.getLogFile(), false); String workMgr = settings.getServiceHost() + ":" + settings.getServiceWorkPort(); String poolMgr = settings.getServiceHost() + ":" + settings.getServicePoolPort(); _workHelper = new BfCoordWorkHelper(workMgr, _logger); _poolHelper = new BfCoordPoolHelper(poolMgr); try (BufferedReader br = new BufferedReader(new FileReader( settings.getCommandFile()))) { String line = null; while ((line = br.readLine()) != null) { if (line.startsWith(" continue; } _logger.output("Doing command: " + line + "\n"); String[] words = line.split("\\s+"); if (words.length > 0) { if (validCommandUsage(words)) { processCommand(words); } } } } catch (FileNotFoundException e) { _logger.errorf("Command file not found: %s\n", settings.getCommandFile()); } catch (Exception e) { _logger.errorf("Exception while reading command file: %s\n", e); } } private void RunInteractiveMode(Settings settings) { try { ConsoleReader reader = new ConsoleReader(); reader.setPrompt("batfish> "); List<Completer> completors = new LinkedList<Completer>(); completors.add(new StringsCompleter("foo", "bar", "baz")); for (Completer c : completors) { reader.addCompleter(c); } String line; PrintWriter pWriter = new PrintWriter(reader.getOutput(), true); OutputStream os = new WriterOutputStream(pWriter); PrintStream ps = new PrintStream(os, true); _logger = new BatfishLogger(settings.getLogLevel(), false, ps); String workMgr = settings.getServiceHost() + ":" + settings.getServiceWorkPort(); String poolMgr = settings.getServiceHost() + ":" + settings.getServicePoolPort(); _workHelper = new BfCoordWorkHelper(workMgr, _logger); _poolHelper = new BfCoordPoolHelper(poolMgr); while ((line = reader.readLine()) != null) { // skip over empty lines if (line.trim().length() == 0) { continue; } if (line.equals(COMMAND_QUIT)) { break; } if (line.equals(COMMAND_CLEAR_SCREEN)) { reader.clearScreen(); continue; } String[] words = line.split("\\s+"); if (words.length > 0) { if (validCommandUsage(words)) { processCommand(words); } } } } catch (Throwable t) { t.printStackTrace(); } } private boolean validCommandUsage(String[] words) { return true; } }
package org.xbill.DNS; /** * DNS Name Compression object. * @see Name * * @author Brian Wellington */ class Compression { private class Entry { Name name; int pos; Entry next; } private static final int TABLE_SIZE = 17; private Entry [] table; private boolean verbose = Options.check("verbosecompression"); /** * Creates a new Compression object. */ public Compression() { table = new Entry[TABLE_SIZE]; } /** Adds a compression entry mapping a name to a position. */ public void add(int pos, Name name) { int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE; Entry entry = new Entry(); entry.name = name; entry.pos = pos; entry.next = table[row]; table[row] = entry; if (verbose) System.err.println("Adding " + name + " at " + pos); } /** * Retrieves the position of the given name, if it has been previously * included in the message. */ public int get(Name name) { int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE; int pos = -1; for (Entry entry = table[row]; entry != null; entry = entry.next) { if (entry.name.equals(name)) pos = entry.pos; } if (verbose) System.err.println("Looking for " + name + ", found " + pos); return pos; } }
package com.stratio.specs; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import com.ning.http.client.Response; import com.stratio.cucumber.converter.ArrayListConverter; import cucumber.api.DataTable; import cucumber.api.Transform; import cucumber.api.java.en.When; public class WhenGSpec extends BaseGSpec { public static final int DEFAULT_TIMEOUT = 1000; /** * Default constructor. * * @param spec */ public WhenGSpec(CommonG spec) { this.commonspec = spec; } /** * Wait seconds. * * @param seconds * @throws InterruptedException */ @When("^I wait '(\\d+?)' seconds?$") public void idleWait(Integer seconds) throws InterruptedException { commonspec.getLogger().info("Idling a while"); Thread.sleep(seconds * DEFAULT_TIMEOUT); } @When("^I drag '([^:]*?):([^:]*?)' and drop it to '([^:]*?):([^:]*?)'$") public void seleniumDrag(String smethod, String source, String dmethod, String destination) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { commonspec.getLogger().info("Dragging element"); Actions builder = new Actions(commonspec.getDriver()); List<WebElement> sourceElement = commonspec.locateElement(smethod, source, 1); List<WebElement> destinationElement = commonspec.locateElement(dmethod, destination, 1); builder.dragAndDrop(sourceElement.get(0), destinationElement.get(0)).perform(); } /** * Click on an numbered {@code url} previously found element. * * @param index */ @When("^I click on the element on index '(\\d+?)'$") public void seleniumClick(Integer index) { commonspec.getLogger().info("Clicking on element with index {}", index); assertThat(commonspec.getPreviousWebElements()).isNotEmpty(); commonspec.getPreviousWebElements().get(index).click(); } /** * Clear the text on a numbered {@code index} previously found element. * * @param index */ @When("^I clear the content on text input at index '(\\d+?)'$") public void seleniumClear(Integer index) { commonspec.getLogger().info("Clearing text on element with index {}", index); assertThat(commonspec.getPreviousWebElements().size()).isGreaterThan(index); assertThat(commonspec.getPreviousWebElements().get(index)).is(commonspec.getTextFieldCondition()); commonspec.getPreviousWebElements().get(index).clear(); } /** * Type a {@code text} on an numbered {@code index} previously found element. * * @param text * @param index */ @When("^I type '(.+?)' on the element on index '(\\d+?)'$") public void seleniumType(String text, Integer index) { commonspec.getLogger().info("Typing on element with index {}", index); String newText = commonspec.replacePlaceholders(text); assertThat(commonspec.getPreviousWebElements()).isNotEmpty(); while (newText.length() > 0) { if (-1 == newText.indexOf("\\n")) { commonspec.getPreviousWebElements().get(index).sendKeys(newText); newText = ""; } else { commonspec.getPreviousWebElements().get(index).sendKeys(newText.substring(0, newText.indexOf("\\n"))); commonspec.getPreviousWebElements().get(index).sendKeys(Keys.ENTER); newText = newText.substring(newText.indexOf("\\n") + 2); } } } /** * Send a {@code strokes} list on an numbered {@code url} previously found element or to the driver. strokes examples are "HOME, END" * or "END, SHIFT + HOME, DELETE". Each element in the stroke list has to be an element from * {@link org.openqa.selenium.Keys} (NULL, CANCEL, HELP, BACK_SPACE, TAB, CLEAR, RETURN, ENTER, SHIFT, LEFT_SHIFT, * CONTROL, LEFT_CONTROL, ALT, LEFT_ALT, PAUSE, ESCAPE, SPACE, PAGE_UP, PAGE_DOWN, END, HOME, LEFT, ARROW_LEFT, UP, * ARROW_UP, RIGHT, ARROW_RIGHT, DOWN, ARROW_DOWN, INSERT, DELETE, SEMICOLON, EQUALS, NUMPAD0, NUMPAD1, NUMPAD2, * NUMPAD3, NUMPAD4, NUMPAD5, NUMPAD6, NUMPAD7, NUMPAD8, NUMPAD9, MULTIPLY, ADD, SEPARATOR, SUBTRACT, DECIMAL, * DIVIDE, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, META, COMMAND, ZENKAKU_HANKAKU) , a plus sign (+), a * comma (,) or spaces ( ) * * @param strokes * @param foo * @param index */ @When("^I send '(.+?)'( on the element on index '(\\d+?)')?$") public void seleniumKeys(@Transform(ArrayListConverter.class) List<String> strokes, String foo, Integer index) { if (index == null) { commonspec.getLogger().info("Sending keys to driver"); } else { commonspec.getLogger().info("Sending keys on element with index {}", index); assertThat(commonspec.getPreviousWebElements().size()).isGreaterThan(index); } assertThat(strokes).isNotEmpty(); for (String stroke : strokes) { if (stroke.contains("+")) { List<Keys> csl = new ArrayList<Keys>(); for (String strokeInChord : stroke.split("\\+")) { csl.add(Keys.valueOf(strokeInChord.trim())); } Keys[] csa = csl.toArray(new Keys[csl.size()]); if (index == null) { new Actions(commonspec.getDriver()).sendKeys(commonspec.getDriver().findElementByXPath("//body"), csa).perform(); } else { commonspec.getPreviousWebElements().get(index).sendKeys(csa); } } else { if (index == null) { new Actions(commonspec.getDriver()).sendKeys(commonspec.getDriver().findElementByXPath("//body"), Keys.valueOf(stroke)).perform(); } else { commonspec.getPreviousWebElements().get(index).sendKeys(Keys.valueOf(stroke)); } } } } /** * Choose an @{code option} from a select webelement found previously * * @param option * @param index */ @When("^I select '(.+?)' on the element on index '(\\d+?)'$") public void elementSelect(String option, Integer index) { commonspec.getLogger().info("Choosing option on select"); String opt = commonspec.replacePlaceholders(option); Select sel = null; sel = new Select(commonspec.getPreviousWebElements().get(index)); sel.selectByVisibleText(opt); } /** * Choose no option from a select webelement found previously * * @param index */ @When("^I de-select every item on the element on index '(\\d+?)'$") public void elementDeSelect(Integer index) { commonspec.getLogger().info("Unselecting everything"); Select sel = null; sel = new Select(commonspec.getPreviousWebElements().get(index)); if (sel.isMultiple()) { sel.deselectAll(); } } /** * Send a request of the type specified * * @param requestType type of request to be sent. Possible values: * GET|DELETE|POST|PUT|CONNECT|PATCH|HEAD|OPTIONS|REQUEST|TRACE * @param endPoint end point to be used * @param foo parameter generated by cucumber because of the optional expression * @param baseData path to file containing the schema to be used * @param element element to read from file (element should contain a json) * @param modifications DataTable containing the modifications to be done to the * base schema element. Syntax will be: * | <key path> | <type of modification> | <new value> | * where: * key path: path to the key to be modified * type of modification: DELETE|ADD|UPDATE * new value: in case of UPDATE or ADD, new value to be used * for example: * if the element read is {"key1": "value1", "key2": {"key3": "value3"}} * and we want to modify the value in "key3" with "new value3" * the modification will be: * | key2.key3 | UPDATE | "new value3" | * being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}} * @throws Exception */ @When("^I send a '(.+?)' request to '(.+?)' based on '([^:]+?)'( as '(json|string)')? with:$") public void sendRequest(String requestType, String endPoint, String baseData, String foo, String type, DataTable modifications) throws Exception { // Retrieve data commonspec.getLogger().info("Retrieving data based on {} as {}", baseData, type); String retrievedData = commonspec.retrieveData(baseData, type); // Modify data commonspec.getLogger().info("Modifying data {} as {}", retrievedData, type); String modifiedData; modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString(); commonspec.getLogger().info("Generating request {} to {} with data {} as {}", requestType, endPoint, modifiedData, type); Future<Response> response = commonspec.generateRequest(requestType, endPoint, modifiedData, type); // Save response commonspec.getLogger().info("Saving response"); commonspec.setResponse(requestType, response.get()); } /** * Same sendRequest, but in this case, we do not receive a data table with modifications. * Besides, the data and request header are optional as well. * In case we want to simulate sending a json request with empty data, we just to avoid baseData * * @param requestType * @param endPoint * @param foo * @param baseData * @param bar * @param type * * @throws Exception */ @When("^I send a '(.+?)' request to '(.+?)'( based on '([^:]+?)')?( as '(json|string)')?$") public void sendRequestNoDataTable (String requestType, String endPoint, String foo, String baseData, String bar, String type) throws Exception { Future<Response> response; if (baseData != null) { // Retrieve data String retrievedData = commonspec.retrieveData(baseData, type); // Generate request response = commonspec.generateRequest(requestType, endPoint, retrievedData, type); } else { // Generate request response = commonspec.generateRequest(requestType, endPoint, "", type); } // Save response commonspec.setResponse(requestType, response.get()); } @When("^I attempt a login to '(.+?)' based on '([^:]+?)' as '(json|string)'$") public void loginUser(String endPoint, String baseData, String type) throws Exception { sendRequestNoDataTable("POST", endPoint, null, baseData, null, type); } @When("^I attempt a login to '(.+?)' based on '([^:]+?)' as '(json|string)' with:$") public void loginUser(String endPoint, String baseData, String type, DataTable modifications) throws Exception { sendRequest("POST", endPoint, baseData, "", type, modifications); } @When("^I attempt a logout to '(.+?)'$") public void logoutUser(String endPoint) throws Exception { sendRequestNoDataTable("GET", endPoint, null, "", null, ""); } }
package cgeo.geocaching.maps.routing; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.Log; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.os.Bundle; import android.util.Xml; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public final class Routing { private static final double UPDATE_MIN_DISTANCE_KILOMETERS = 0.005; private static final double MIN_ROUTING_DISTANCE_KILOMETERS = 0.04; private static final int UPDATE_MIN_DELAY_SECONDS = 3; private static BRouterServiceConnection brouter; private static Geopoint lastDirectionUpdatePoint; @Nullable private static Geopoint[] lastRoutingPoints = null; private static Geopoint lastDestination; private static long timeLastUpdate; private static int connectCount = 0; private static final Map<String, Runnable> REGISTERED_CALLBACKS = new HashMap<>(); private static final Runnable SERVICE_CONNECTED_CALLBACK = () -> { synchronized (Routing.class) { for (Runnable r : REGISTERED_CALLBACKS.values()) { r.run(); } } }; private Routing() { // utility class } public static synchronized void connect() { connect(null, null); } public static synchronized void connect(final String callbackKey, final Runnable onServiceConnectedCallback) { connectCount++; if (callbackKey != null && onServiceConnectedCallback != null) { REGISTERED_CALLBACKS.put(callbackKey, onServiceConnectedCallback); } if (brouter != null && brouter.isConnected()) { //already connected return; } brouter = new BRouterServiceConnection(SERVICE_CONNECTED_CALLBACK); final Intent intent = new Intent(); intent.setClassName("btools.routingapp", "btools.routingapp.BRouterService"); if (!getContext().bindService(intent, brouter, Context.BIND_AUTO_CREATE)) { brouter = null; Log.d("Connecting brouter failed"); } else { Log.d("brouter connected"); } } private static ContextWrapper getContext() { return CgeoApplication.getInstance(); } public static synchronized void disconnect() { disconnect(null); } public static synchronized void disconnect(final String callbackKey) { if (callbackKey != null) { REGISTERED_CALLBACKS.remove(callbackKey); } connectCount if (connectCount <= 0) { connectCount = 0; if (brouter != null && brouter.isConnected()) { getContext().unbindService(brouter); brouter = null; Log.d("brouter disconnected"); } } } /** * Return a valid track (with at least two points, including the start and destination). * In some cases (e.g., destination is too close or too far, path could not be found), * a straight line will be returned. * * @param start the starting point * @param destination the destination point * @return a track with at least two points including the start and destination points */ @NonNull public static Geopoint[] getTrack(final Geopoint start, final Geopoint destination) { if (brouter == null || Settings.getRoutingMode() == RoutingMode.STRAIGHT) { return defaultTrack(start, destination); } // avoid updating to frequently final long timeNow = System.currentTimeMillis(); if ((timeNow - timeLastUpdate) < 1000 * UPDATE_MIN_DELAY_SECONDS) { return ensureTrack(lastRoutingPoints, start, destination); } // Disable routing for huge distances final int maxThresholdKm = Settings.getBrouterThreshold(); final float targetDistance = start.distanceTo(destination); if (targetDistance > maxThresholdKm) { return defaultTrack(start, destination); } // disable routing when near the target if (targetDistance < MIN_ROUTING_DISTANCE_KILOMETERS) { return defaultTrack(start, destination); } // Use cached route if current position has not changed more than 5m and we had a route // TODO: Maybe adjust this to current zoomlevel if (lastDirectionUpdatePoint != null && destination == lastDestination && start.distanceTo(lastDirectionUpdatePoint) < UPDATE_MIN_DISTANCE_KILOMETERS && lastRoutingPoints != null) { return lastRoutingPoints; } // now really calculate a new route lastDestination = destination; lastRoutingPoints = calculateRouting(start, destination); lastDirectionUpdatePoint = start; timeLastUpdate = timeNow; return ensureTrack(lastRoutingPoints, start, destination); } /** * Return a valid track (with at least two points, including the start and destination). * no caching * * @param start the starting point * @param destination the destination point * @return a track with at least two points including the start and destination points */ @NonNull public static Geopoint[] getTrackNoCaching(final Geopoint start, final Geopoint destination) { if (brouter == null || Settings.getRoutingMode() == RoutingMode.STRAIGHT) { return defaultTrack(start, destination); } // Disable routing for huge distances final int maxThresholdKm = Settings.getBrouterThreshold(); final float targetDistance = start.distanceTo(destination); if (targetDistance > maxThresholdKm) { return defaultTrack(start, destination); } // disable routing when near the target if (targetDistance < MIN_ROUTING_DISTANCE_KILOMETERS) { return defaultTrack(start, destination); } // now calculate a new route final Geopoint[] track = calculateRouting(start, destination); return ensureTrack(track, start, destination); } @NonNull private static Geopoint[] ensureTrack(@Nullable final Geopoint[] routingPoints, final Geopoint start, final Geopoint destination) { return routingPoints != null ? routingPoints : defaultTrack(start, destination); } @NonNull private static Geopoint[] defaultTrack(final Geopoint start, final Geopoint destination) { return new Geopoint[] { start, destination }; } @Nullable private static Geopoint[] calculateRouting(final Geopoint start, final Geopoint dest) { final Bundle params = new Bundle(); params.putString("trackFormat", "gpx"); params.putDoubleArray("lats", new double[]{start.getLatitude(), dest.getLatitude()}); params.putDoubleArray("lons", new double[]{start.getLongitude(), dest.getLongitude()}); params.putString("v", Settings.getRoutingMode().parameterValue); final String gpx = brouter == null ? null : brouter.getTrackFromParams(params); if (gpx == null) { Log.i("brouter returned no data"); return null; } if (!gpx.startsWith("<?xml")) { Log.w("brouter returned an error message: " + gpx); return null; } return parseGpxTrack(gpx, dest); } @Nullable private static Geopoint[] parseGpxTrack(@NonNull final String gpx, final Geopoint destination) { try { final LinkedList<Geopoint> result = new LinkedList<>(); Xml.parse(gpx, new DefaultHandler() { @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { if (qName.equalsIgnoreCase("trkpt")) { final String lat = atts.getValue("lat"); if (lat != null) { final String lon = atts.getValue("lon"); if (lon != null) { result.add(new Geopoint(lat, lon)); } } } } }); // artificial straight line from track to target if (destination != null) { result.add(destination); } return result.toArray(new Geopoint[result.size()]); } catch (final SAXException e) { Log.w("cannot parse brouter output of length " + gpx.length() + ", gpx=" + gpx, e); } return null; } public static void invalidateRouting() { lastDirectionUpdatePoint = null; timeLastUpdate = 0; } public static boolean isAvailable() { return brouter != null; } }
package org.digidoc4j.impl; import eu.europa.ec.markt.dss.DSSUtils; import eu.europa.ec.markt.dss.exception.DSSException; import eu.europa.ec.markt.dss.signature.DSSDocument; import eu.europa.ec.markt.dss.signature.asic.ASiCService; import eu.europa.ec.markt.dss.signature.token.Constants; import eu.europa.ec.markt.dss.validation102853.CommonCertificateVerifier; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.digidoc4j.*; import org.digidoc4j.exceptions.*; import org.digidoc4j.signers.ExternalSigner; import org.digidoc4j.signers.PKCS12Signer; import org.junit.AfterClass; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import java.io.*; import java.net.URI; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Date; import java.util.List; import java.util.zip.ZipFile; import static java.util.Arrays.asList; import static org.digidoc4j.Container.*; import static org.digidoc4j.Container.SignatureProfile.*; import static org.digidoc4j.DigestAlgorithm.SHA1; import static org.digidoc4j.DigestAlgorithm.SHA256; import static org.digidoc4j.utils.Helper.deserializer; import static org.digidoc4j.utils.Helper.serialize; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class BDocContainerTest extends DigiDoc4JTestHelper { private PKCS12Signer PKCS12_SIGNER; @Before public void setUp() throws Exception { PKCS12_SIGNER = new PKCS12Signer("testFiles/signout.p12", "test".toCharArray()); } @AfterClass public static void deleteTemporaryFiles() { try { DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(".")); for (Path item : directoryStream) { String fileName = item.getFileName().toString(); if (fileName.endsWith("bdoc") && fileName.startsWith("test")) Files.deleteIfExists(item); } } catch (IOException e) { e.printStackTrace(); } } @Test public void testSetDigestAlgorithmToSHA256() throws Exception { BDocContainer container = new BDocContainer(); SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setDigestAlgorithm(SHA256); container.setSignatureParameters(signatureParameters); assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", container.getDigestAlgorithm().toString()); } @Test public void testSetDigestAlgorithmToSHA1() throws Exception { BDocContainer container = new BDocContainer(); SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setDigestAlgorithm(SHA1); container.setSignatureParameters(signatureParameters); assertEquals("http://www.w3.org/2000/09/xmldsig#sha1", container.getDigestAlgorithm().toString()); } @Test public void testSetDigestAlgorithmToNotImplementedDigest() throws Exception { BDocContainer container = new BDocContainer(); SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setDigestAlgorithm(SHA256); container.setSignatureParameters(signatureParameters); assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", container.getDigestAlgorithm().toString()); } @Test public void testDefaultDigestAlgorithm() throws Exception { BDocContainer container = new BDocContainer(); assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", container.getDigestAlgorithm().toString()); } @Test public void testOpenBDocDocument() throws Exception { BDocContainer container = new BDocContainer("testFiles/one_signature.bdoc"); container.verify(); } @Test public void testOpenBDocDocumentWithTwoSignatures() throws Exception { BDocContainer container = new BDocContainer("testFiles/two_signatures.bdoc"); container.verify(); } @Test(expected = DigiDoc4JException.class) public void testAddDataFileWhenFileDoesNotExist() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("notExisting.txt", "text/plain"); } @Test(expected = DigiDoc4JException.class) public void testAddDataFileFromInputStreamWithByteArrayConversionFailure() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile(new MockInputStream(), "test.txt", "text/plain"); } @Test(expected = DigiDoc4JException.class) public void testAddRawSignature() throws Exception { BDocContainer container = new BDocContainer(); container.addRawSignature(new byte[]{}); } @Test(expected = NotYetImplementedException.class) public void testAddRawSignatureFromInputStream() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.addRawSignature(new ByteArrayInputStream(Signatures.XADES_SIGNATURE.getBytes())); container.save("test_add_raw_signature.bdoc"); Container openedContainer = open("test_add_raw_signature.bdoc"); assertEquals(1, openedContainer.getSignatures().size()); } @Test public void testSaveBDocDocumentWithTwoSignatures() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.sign(PKCS12_SIGNER); container.save("testTwoSignatures.bdoc"); assertEquals(2, container.getSignatures().size()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", container.getSignatures().get(0).getSigningCertificate().getSerial()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", container.getSignatures().get(1).getSigningCertificate().getSerial()); Container openedContainer = open("testTwoSignatures.bdoc"); assertEquals(2, openedContainer.getSignatures().size()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", openedContainer.getSignatures().get(0).getSigningCertificate().getSerial()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", openedContainer.getSignatures().get(1).getSigningCertificate().getSerial()); } @Test public void testGetDefaultSignatureParameters() { Container container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("test.bdoc"); container = open("test.bdoc"); Signature signature = container.getSignature(0); assertNull(signature.getPostalCode()); assertNull(signature.getCity()); assertNull(signature.getStateOrProvince()); assertNull(signature.getCountryName()); assertNull(signature.getSignerRoles()); } @Test public void getSignatureByIndex() { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.sign(PKCS12_SIGNER); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", container.getSignature(1).getSigningCertificate().getSerial()); } @Test public void notThrowingNPEWhenDOCXFileIsAddedToContainer() { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/word_file.docx", "text/xml"); container.sign(PKCS12_SIGNER); assertEquals(1, container.getSignatures().size()); } @Test public void testAddSignaturesToExistingDocument() throws Exception { Container container = open("testFiles/asics_testing_two_signatures.bdoc"); container.sign(PKCS12_SIGNER); container.save("testAddMultipleSignatures.bdoc"); assertEquals(3, container.getSignatures().size()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", container.getSignatures().get(2).getSigningCertificate().getSerial()); Container openedContainer = open("testAddMultipleSignatures.bdoc"); assertEquals(3, openedContainer.getSignatures().size()); assertEquals("497c5a2bfa9361a8534fbed9f48e7a12", openedContainer.getSignatures().get(2).getSigningCertificate().getSerial()); ValidationResult validationResult = openedContainer.validate(); assertEquals(0, validationResult.getErrors().size()); } @Test public void testRemoveSignatureWhenOneSignatureExists() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.removeSignature(0); container.save("testRemoveSignature.bdoc"); assertEquals(0, container.getSignatures().size()); container = new BDocContainer("testRemoveSignature.bdoc"); assertEquals(0, container.getSignatures().size()); } @Test public void testRemoveSignatureWhenTwoSignaturesExist() throws Exception { Container container = open("testFiles/asics_testing_two_signatures.bdoc"); container.removeSignature(0); container.save("testRemoveSignature.bdoc"); container = new BDocContainer("testRemoveSignature.bdoc"); assertEquals(1, container.getSignatures().size()); } @Test public void testRemoveSignatureWhenThreeSignaturesExist() throws Exception { Container container = open("testFiles/asics_testing_two_signatures.bdoc"); container.sign(PKCS12_SIGNER); container.save("testThreeSignatures.bdoc"); container = new BDocContainer("testThreeSignatures.bdoc"); assertEquals(3, container.getSignatures().size()); container.removeSignature(1); container.save("testRemoveSignature.bdoc"); container = new BDocContainer("testRemoveSignature.bdoc"); assertEquals(2, container.getSignatures().size()); } @Test public void testSaveDocumentWithOneSignature() throws Exception { createSignedBDocDocument("testSaveBDocDocumentWithOneSignature.bdoc"); assertTrue(Files.exists(Paths.get("testSaveBDocDocumentWithOneSignature.bdoc"))); } @Test public void testVerifySignedDocument() throws Exception { BDocContainer container = (BDocContainer) createSignedBDocDocument("testSaveBDocDocumentWithOneSignature.bdoc"); ValidationResult result = container.verify(); assertFalse(result.hasErrors()); } @Test public void testTestVerifyOnInvalidDocument() throws Exception { BDocContainer container = new BDocContainer("testFiles/invalid_container.bdoc"); assertTrue(container.verify().hasErrors()); } @Test(expected = DigiDoc4JException.class) public void testRemoveDataFileAfterSigning() throws Exception { createSignedBDocDocument("testRemoveDataFile.bdoc"); Container container = new BDocContainer("testRemoveDataFile.bdoc"); assertEquals("test.txt", container.getDataFiles().get(0).getName()); assertEquals(1, container.getDataFiles().size()); container.removeDataFile("test.txt"); assertEquals(0, container.getDataFiles().size()); } @Test public void testRemoveDataFile() throws Exception { Container container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); assertEquals("test.txt", container.getDataFiles().get(0).getName()); assertEquals(1, container.getDataFiles().size()); container.removeDataFile("testFiles/test.txt"); assertEquals(0, container.getDataFiles().size()); } @Test(expected = DigiDoc4JException.class) public void testAddDataFileAfterSigning() throws Exception { createSignedBDocDocument("testAddDataFile.bdoc"); Container container = new BDocContainer("testAddDataFile.bdoc"); container.addDataFile("testFiles/test.txt", "text/plain"); } @Test(expected = DigiDoc4JException.class) public void testRemovingNonExistingFile() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.removeDataFile("test1.txt"); } @Test(expected = DigiDoc4JException.class) public void testAddingSameFileSeveralTimes() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/test.txt", "text/plain"); } @Test(expected = DigiDoc4JException.class) public void testAddingSameFileInDifferentContainerSeveralTimes() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/sub/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("testAddSameFile.bdoc"); } @Test(expected = DigiDoc4JException.class) public void testAddingNotExistingFile() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("notExistingFile.txt", "text/plain"); } @Test public void testAddFileAsStream() throws Exception { BDocContainer container = new BDocContainer(); ByteArrayInputStream stream = new ByteArrayInputStream("tere, tere".getBytes()); container.addDataFile(stream, "test1.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("testAddFileAsStream.bdoc"); Container containerToTest = new BDocContainer("testAddFileAsStream.bdoc"); assertEquals("test1.txt", containerToTest.getDataFiles().get(0).getName()); } @Test public void setsSignatureId() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setSignatureId("SIGNATURE-1"); container.setSignatureParameters(signatureParameters); container.sign(PKCS12_SIGNER); signatureParameters.setSignatureId("SIGNATURE-2"); container.setSignatureParameters(signatureParameters); container.sign(PKCS12_SIGNER); container.save("setsSignatureId.bdoc"); container = new BDocContainer("setsSignatureId.bdoc"); assertEquals("SIGNATURE-1", container.getSignature(0).getId()); assertEquals("SIGNATURE-2", container.getSignature(1).getId()); ZipFile zip = new ZipFile("setsSignatureId.bdoc"); assertNotNull(zip.getEntry("META-INF/signatures0.xml")); assertNotNull(zip.getEntry("META-INF/signatures1.xml")); } @Test public void setsDefaultSignatureId() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.sign(PKCS12_SIGNER); container.save("testSetsDefaultSignatureId.bdoc"); container = new BDocContainer("testSetsDefaultSignatureId.bdoc"); assertEquals("S0", container.getSignature(0).getId()); assertEquals("S1", container.getSignature(1).getId()); ZipFile zip = new ZipFile("testSetsDefaultSignatureId.bdoc"); assertNotNull(zip.getEntry("META-INF/signatures0.xml")); assertNotNull(zip.getEntry("META-INF/signatures1.xml")); } @Test public void getDataFileByIndex() { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); assertEquals("test.txt", container.getDataFile(0).getName()); } @Test public void rawSignatureDoesNotThrowExceptionInCloseError() throws IOException { BDocContainer container = spy(new BDocContainer()); byte[] signature = {0x41}; MockInputStream value = new MockInputStream(); doNothing().when(container).addRawSignature(value); when(container.getByteArrayInputStream(signature)).thenReturn(value); container.addRawSignature(signature); } @Test(expected = SignatureNotFoundException.class) public void testSignatureNotFoundException() throws Exception { BDocContainer container = new BDocContainer(); BDocContainer spy = spy(container); eu.europa.ec.markt.dss.parameter.SignatureParameters signatureParameters = new eu.europa.ec.markt.dss.parameter.SignatureParameters(); signatureParameters.setDeterministicId("NotPresentSignature"); when(spy.getDssSignatureParameters()).thenReturn(signatureParameters); spy.addDataFile("testFiles/test.txt", "text/plain"); spy.sign(PKCS12_SIGNER); } @Test(expected = DigiDoc4JException.class) public void openNonExistingFileThrowsError() { new BDocContainer("non-existing.bdoc"); } @Test(expected = DigiDoc4JException.class) public void openClosedStreamThrowsException() throws IOException { FileInputStream stream = new FileInputStream(new File("testFiles/test.txt")); stream.close(); new BDocContainer(stream, false); } @Test public void testLargeFileSigning() throws Exception { BDocContainer container = new BDocContainer(); container.configuration.enableBigFilesSupport(10); String path = createLargeFile((container.configuration.getMaxDataFileCachedInBytes()) + 100); container.addDataFile(path, "text/plain"); container.sign(PKCS12_SIGNER); } @Test public void openLargeFileFromStream() throws FileNotFoundException { BDocContainer container = new BDocContainer(); container.configuration.enableBigFilesSupport(0); String path = createLargeFile((container.configuration.getMaxDataFileCachedInBytes()) + 100); container.addDataFile(path, "text/plain"); container.sign(PKCS12_SIGNER); container.save("test-large-file.bdoc"); File file = new File("test-large-file.bdoc"); FileInputStream fileInputStream = new FileInputStream(file); open(fileInputStream, true); IOUtils.closeQuietly(fileInputStream); assertEquals(1, container.getSignatures().size()); } @Test public void openAddFileFromStream() throws IOException { BDocContainer container = new BDocContainer(); container.configuration.enableBigFilesSupport(0); String path = createLargeFile((container.configuration.getMaxDataFileCachedInBytes()) + 100); try (FileInputStream stream = new FileInputStream(new File(path))) { container.addDataFile(stream, "fileName", "text/plain"); container.sign(PKCS12_SIGNER); container.save("test-large-file.bdoc"); File file = new File("test-large-file.bdoc"); FileInputStream fileInputStream = new FileInputStream(file); open(fileInputStream, true); IOUtils.closeQuietly(fileInputStream); } assertEquals(1, container.getSignatures().size()); } private String createLargeFile(long size) { String fileName = "test_large_file.bdoc"; try { RandomAccessFile largeFile = new RandomAccessFile(fileName, "rw"); largeFile.setLength(size);//todo create large file correctly } catch (Exception e) { e.printStackTrace(); } return fileName; } @Test public void testGetDocumentType() throws Exception { createSignedBDocDocument("testGetDocumentType.bdoc"); BDocContainer container = new BDocContainer("testGetDocumentType.bdoc"); assertEquals(DocumentType.BDOC, container.getDocumentType()); } @Test public void testAddTwoFilesAsStream() throws Exception { BDocContainer container = new BDocContainer(); ByteArrayInputStream stream = new ByteArrayInputStream("tere, tere".getBytes()); container.addDataFile(stream, "test1.txt", "text/plain"); container.addDataFile(stream, "test2.txt", "text/plain"); } @Test public void testAddTwoFilesAsFileWithoutOCSP() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(B_BES); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/test.xml", "text/xml"); container.sign(PKCS12_SIGNER); container.save("testTwoFilesSigned.bdoc"); container = new BDocContainer("testTwoFilesSigned.bdoc"); assertEquals(2, container.getDataFiles().size()); } @Test public void testGetFileNameAndID() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/test.xml", "text/xml"); container.sign(PKCS12_SIGNER); container.save("testTwoFilesSigned.bdoc"); container = new BDocContainer("testTwoFilesSigned.bdoc"); assertEquals("test.xml", container.getDataFile(0).getName()); assertEquals("test.txt", container.getDataFile(1).getName()); assertEquals("test.xml", container.getDataFile(0).getId()); assertEquals("test.txt", container.getDataFile(1).getId()); } @Test public void testAddTwoFilesAsFileWithOCSP() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/test.xml", "text/xml"); container.sign(PKCS12_SIGNER); container.save("testTwoFilesSigned.bdoc"); container = new BDocContainer("testTwoFilesSigned.bdoc"); assertEquals(2, container.getDataFiles().size()); } @Test(expected = NotYetImplementedException.class) public void testValidateEmptyDocument() { BDocContainer container = new BDocContainer(); container.validate(); } @Test public void testValidate() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); ValidationResult validationResult = container.validate(); assertEquals(0, validationResult.getErrors().size()); } @Test public void testLoadConfiguration() throws Exception { BDocContainer container = new BDocContainer(); assertFalse(container.configuration.isBigFilesSupportEnabled()); container.loadConfiguration("testFiles/digidoc_test_conf.yaml"); assertTrue(container.configuration.isBigFilesSupportEnabled()); assertEquals(8192, container.configuration.getMaxDataFileCachedInMB()); } @Test public void saveToStream() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile(new ByteArrayInputStream(new byte[]{0x42}), "test_bytes.txt", "text/plain"); container.sign(PKCS12_SIGNER); File expectedContainerAsFile = new File("testSaveToStreamTest.bdoc"); OutputStream out = new FileOutputStream(expectedContainerAsFile); container.save(out); assertTrue(Files.exists(expectedContainerAsFile.toPath())); Container containerToTest = open(expectedContainerAsFile.getName()); assertArrayEquals(new byte[]{0x42}, containerToTest.getDataFiles().get(0).getBytes()); } @Test(expected = DigiDoc4JException.class) public void saveToStreamThrowsException() throws IOException { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); File expectedContainerAsFile = new File("testSaveToStreamTest.bdoc"); OutputStream out = new FileOutputStream(expectedContainerAsFile); out.close(); container.save(out); } @Test public void configurationImmutabilityWhenLoadingFromFile() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("test_immutable.bdoc"); Configuration configuration = new Configuration(Configuration.Mode.TEST); String tspSource = configuration.getTspSource(); container = new BDocContainer("test_immutable.bdoc", configuration); configuration.setTspSource("changed_tsp_source"); assertEquals(tspSource, container.configuration.getTspSource()); } @Test public void TSLIsLoadedAfterSettingNewTSLLocation() { Configuration configuration = new Configuration(); configuration.setTslLocation("file:test-tsl/trusted-test-mp.xml"); BDocContainer container = new BDocContainer(configuration); container.configuration.getTSL(); assertEquals(6, container.configuration.getTSL().getCertificates().size()); configuration.setTslLocation("http://10.0.25.57/tsl/trusted-test-mp.xml"); container = new BDocContainer(configuration); assertNotEquals(6, container.configuration.getTSL().getCertificates().size()); } @Test public void extendToTS() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(B_BES); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("testExtendTo.bdoc"); assertEquals(1, container.getSignatures().size()); assertNull(container.getSignature(0).getOCSPCertificate()); container = new BDocContainer("testExtendTo.bdoc"); container.extendTo(SignatureProfile.LT); container.save("testExtendToContainsIt.bdoc"); assertEquals(1, container.getSignatures().size()); assertNotNull(container.getSignature(0).getOCSPCertificate()); } @Test public void containerIsLT() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(SignatureProfile.LT); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("testLT.bdoc"); container = new BDocContainer("testLT.bdoc"); assertEquals(1, container.getSignatures().size()); assertNotNull(container.getSignature(0).getOCSPCertificate()); } @Test public void verifySignatureProfileIsTS() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(SignatureProfile.LT); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save("testAddConfirmation.bdoc"); assertEquals(1, container.getSignatures().size()); assertNotNull(container.getSignature(0).getOCSPCertificate()); } @Test(expected = NotYetImplementedException.class) public void signatureProfileTMIsNotSupported() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(LT_TM); } @Test(expected = DigiDoc4JException.class) public void extendToWhenConfirmationAlreadyExists() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.setSignatureProfile(B_BES); container.sign(PKCS12_SIGNER); container.save("testExtendTo.bdoc"); assertEquals(1, container.getSignatures().size()); assertNull(container.getSignature(0).getOCSPCertificate()); container = new BDocContainer("testExtendTo.bdoc"); container.extendTo(LT); container.extendTo(LT); } @Test(expected = DigiDoc4JException.class) public void signWithoutDataFile() throws Exception { BDocContainer container = new BDocContainer(); container.sign(PKCS12_SIGNER); } @Test public void extendToWithMultipleSignatures() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.setSignatureProfile(B_BES); container.sign(PKCS12_SIGNER); container.sign(PKCS12_SIGNER); container.save("testExtendTo.bdoc"); assertEquals(2, container.getSignatures().size()); assertNull(container.getSignature(0).getOCSPCertificate()); assertNull(container.getSignature(1).getOCSPCertificate()); container = new BDocContainer("testExtendTo.bdoc"); container.extendTo(LT); container.save("testExtendToContainsIt.bdoc"); container = new BDocContainer("testExtendToContainsIt.bdoc"); assertEquals(2, container.getSignatures().size()); assertNotNull(container.getSignature(0).getOCSPCertificate()); assertNotNull(container.getSignature(1).getOCSPCertificate()); } @Test(expected = NotYetImplementedException.class) public void extendToIsImplementedForTSProfileOtherProfilesThrowException() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.setSignatureProfile(B_BES); container.sign(PKCS12_SIGNER); container.extendTo(LT_TM); } @Test public void extendToWithMultipleSignaturesAndMultipleFiles() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(B_BES); container.addDataFile("testFiles/test.txt", "text/plain"); container.addDataFile("testFiles/test.xml", "text/xml"); container.sign(PKCS12_SIGNER); container.sign(PKCS12_SIGNER); container.save("testAddConfirmation.bdoc"); assertEquals(2, container.getSignatures().size()); assertEquals(2, container.getDataFiles().size()); assertNull(container.getSignature(0).getOCSPCertificate()); assertNull(container.getSignature(1).getOCSPCertificate()); container = new BDocContainer("testAddConfirmation.bdoc"); container.extendTo(LT); container.save("testAddConfirmationContainsIt.bdoc"); assertEquals(2, container.getSignatures().size()); assertEquals(2, container.getDataFiles().size()); assertNotNull(container.getSignature(0).getOCSPCertificate()); assertNotNull(container.getSignature(1).getOCSPCertificate()); } @Test(expected = UnsupportedFormatException.class) public void notBDocThrowsException() { new BDocContainer("testFiles/notABDoc.bdoc"); } @Test(expected = UnsupportedFormatException.class) public void incorrectMimetypeThrowsException() { new BDocContainer("testFiles/incorrectMimetype.bdoc"); } @Test(expected = DigiDoc4JException.class) public void signingThrowsNormalDSSException() { MockBDocContainer container = new MockBDocContainer("Normal DSS Exception"); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); } @Test(expected = OCSPRequestFailedException.class) public void signingThrowsOCSPException() { MockBDocContainer container = new MockBDocContainer("OCSP request failed"); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); } @Test public void getVersion() { BDocContainer container = new BDocContainer(); assertNull(container.getVersion()); } @Test public void testContainerExtensionToTSA() throws Exception { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.extendTo(LTA); assertNotNull(container.getSignature(0).getOCSPCertificate()); } @Test public void twoStepSigning() throws IOException { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); X509Certificate signerCert = getSignerCert(); SignedInfo signedInfo = container.prepareSigning(signerCert); byte[] signature = getExternalSignature(container, signerCert, signedInfo, SHA256); container.signRaw(signature); container.save("test.bdoc"); container = open("test.bdoc"); assertEquals(SHA256, container.getDigestAlgorithm()); ValidationResult validate = container.validate(); assertTrue(validate.isValid()); assertEquals(1, container.getSignatures().size()); Signature resultSignature = container.getSignature(0); assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", resultSignature.getSignatureMethod()); assertNull(resultSignature.getSignerRoles()); assertNull(resultSignature.getCity()); assertEquals("S0", resultSignature.getId()); assertNotNull(resultSignature.getOCSPCertificate()); assertNotNull(resultSignature.getSigningCertificate()); assertNotNull(resultSignature.getRawSignature().length); assertEquals(LT, resultSignature.getProfile()); assertNotNull(resultSignature.getTimeStampTokenCertificate()); List<DataFile> dataFiles = container.getDataFiles(); assertEquals(1, dataFiles.size()); DataFile dataFile = dataFiles.get(0); assertEquals("test.txt", dataFile.getName()); dataFile.calculateDigest(DigestAlgorithm.SHA384); assertEquals("text/plain", dataFile.getMediaType()); assertEquals(new String(Files.readAllBytes(Paths.get("testFiles/test.txt"))), new String(dataFile.getBytes())); assertEquals(15, dataFile.getFileSize()); assertEquals("test.txt", dataFile.getId()); } @Test public void twoStepSigningVerifySignatureParameters() { SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setDigestAlgorithm(DigestAlgorithm.SHA512); signatureParameters.setRoles(asList("manager", "employee")); signatureParameters.setProductionPlace(new SignatureProductionPlace("city", "state", "postalCode", "country")); signatureParameters.setSignatureId("S99"); Container container = create(); container.setSignatureParameters(signatureParameters); container.addDataFile("testFiles/test.txt", "text/plain"); X509Certificate signerCert = getSignerCert(); SignedInfo signedInfo = container.prepareSigning(signerCert); byte[] signature = getExternalSignature(container, signerCert, signedInfo, signatureParameters.getDigestAlgorithm()); container.signRaw(signature); container.save("test.bdoc"); container = open("test.bdoc"); assertEquals(1, container.getSignatures().size()); Signature resultSignature = container.getSignature(0); assertEquals("http://www.w3.org/2001/04/xmlenc#sha512", resultSignature.getSignatureMethod()); assertEquals("employee", resultSignature.getSignerRoles().get(1)); assertEquals("city", resultSignature.getCity()); assertEquals("S99", resultSignature.getId()); } @Test public void twoStepSigningWithSerialization() throws IOException, ClassNotFoundException { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); X509Certificate signerCert = getSignerCert(); SignedInfo signedInfo = container.prepareSigning(signerCert); serialize(container, "container.bin"); byte[] signature = getExternalSignature(container, signerCert, signedInfo, SHA256); container = deserializer("container.bin"); container.signRaw(signature); container.save("test.bdoc"); container = open("test.bdoc"); ValidationResult validate = container.validate(); assertTrue(validate.isValid()); assertEquals(1, container.getSignatures().size()); } @Test public void testContainerCreationAsTSA() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(LTA); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); assertNotNull(container.getSignature(0).getOCSPCertificate()); } @Test(expected = DigiDoc4JException.class) public void extensionNotPossibleWhenSignatureLevelIsSame() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(LTA); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.extendTo(LTA); } private Container createSignedBDocDocument(String fileName) { BDocContainer container = new BDocContainer(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); container.save(fileName); return container; } private class MockInputStream extends InputStream { public MockInputStream() { } @Override public int read() throws IOException { return 0; } @Override public int read(@SuppressWarnings("NullableProblems") byte b[], int off, int len) throws IOException { throw new IOException(); } @Override public void close() throws IOException { throw new IOException(); } } private class MockBDocContainer extends BDocContainer { private String expected; public MockBDocContainer(String expected) { super(); this.expected = expected; } @Override public Signature sign(Signer signer) { super.asicService = spy(new ASiCService(new CommonCertificateVerifier())); doThrow(new DSSException(expected)).when(super.asicService).signDocument(Mockito.any(DSSDocument.class), Mockito.any(eu.europa.ec.markt.dss.parameter.SignatureParameters.class), Mockito.any(byte[].class)); return super.sign(signer); } } static byte[] getExternalSignature(Container container, final X509Certificate signerCert, SignedInfo prepareSigningSignature, final DigestAlgorithm digestAlgorithm) { Signer externalSigner = new ExternalSigner(signerCert) { @Override public byte[] sign(Container container, byte[] dataToSign) { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) { keyStore.load(stream, "test".toCharArray()); } PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray()); final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm(); return DSSUtils.encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign)); } catch (Exception e) { throw new DigiDoc4JException("Loading private key failed"); } } private byte[] addPadding(byte[] digest) { byte[] signatureDigest; switch (digestAlgorithm) { case SHA512: signatureDigest = Constants.SHA512_DIGEST_INFO_PREFIX; break; case SHA256: signatureDigest = Constants.SHA256_DIGEST_INFO_PREFIX; break; default: throw new NotYetImplementedException(); } return ArrayUtils.addAll(signatureDigest, digest); } }; return externalSigner.sign(container, prepareSigningSignature.getDigest()); } static X509Certificate getSignerCert() { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) { keyStore.load(stream, "test".toCharArray()); } return (X509Certificate) keyStore.getCertificate("1"); } catch (Exception e) { throw new DigiDoc4JException("Loading signer cert failed"); } } @Test public void verifySerialization() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); assertTrue(deserializedContainer.validate().isValid()); } @Test public void serializationVerifySpecifiedSignatureParameters() throws Exception { SignatureParameters signatureParameters = new SignatureParameters(); signatureParameters.setDigestAlgorithm(DigestAlgorithm.SHA512); signatureParameters.setRoles(asList("manager", "employee")); signatureParameters.setProductionPlace(new SignatureProductionPlace("city", "state", "postalCode", "country")); signatureParameters.setSignatureId("S99"); Container container = create(); container.setSignatureParameters(signatureParameters); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); Signature signature = deserializedContainer.getSignature(0); assertEquals("postalCode", signature.getPostalCode()); assertEquals("city", signature.getCity()); assertEquals("state", signature.getStateOrProvince()); assertEquals("country", signature.getCountryName()); assertEquals("employee", signature.getSignerRoles().get(1)); assertEquals("S99", signature.getId()); assertEquals("http://www.w3.org/2001/04/xmlenc#sha512", signature.getSignatureMethod()); } @Test public void serializationVerifyDefaultSignatureParameters() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); Signature signature = deserializedContainer.getSignature(0); assertNull(signature.getCity()); assertNull(signature.getSignerRoles()); assertEquals("S0", signature.getId()); assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", signature.getSignatureMethod()); } @Test public void serializationGetDigestAlgorithm() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); assertEquals(SHA256, deserializedContainer.getDigestAlgorithm()); } @Test public void serializationGetDocumentType() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); assertEquals(container.getDocumentType(), deserializedContainer.getDocumentType()); } @Test public void serializationGetOCSPCertificate() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); byte[] ocspCertBeforeSerialization = container.getSignature(0).getOCSPCertificate(). getX509Certificate().getEncoded(); byte[] ocspCertAfterSerialization = deserializedContainer.getSignature(0).getOCSPCertificate(). getX509Certificate().getEncoded(); assertArrayEquals(ocspCertBeforeSerialization, ocspCertAfterSerialization); } @Test public void serializationGetSigningTime() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); Date signingTimeBeforeSerialization = container.getSignature(0).getSigningTime(); Date signingTimeAfterSerialization = deserializedContainer.getSignature(0).getSigningTime(); assertEquals(signingTimeBeforeSerialization, signingTimeAfterSerialization); } @Test(expected = NotYetImplementedException.class) public void serializationGetPolicy() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); String signaturePolicyBeforeSerialization = container.getSignature(0).getPolicy(); String signaturePolicyAfterSerialization = deserializedContainer.getSignature(0).getPolicy(); assertEquals(signaturePolicyBeforeSerialization, signaturePolicyAfterSerialization); } @Test(expected = NotYetImplementedException.class) public void serializationGetSignaturePolicyURI() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); URI signaturePolicyURIBeforeSerialization = container.getSignature(0).getSignaturePolicyURI(); URI signaturePolicyURIAfterSerialization = deserializedContainer.getSignature(0).getSignaturePolicyURI(); assertEquals(signaturePolicyURIBeforeSerialization, signaturePolicyURIAfterSerialization); } @Test public void serializationGetSigningCertificate() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); byte[] signingCertBeforeSerialization = container.getSignature(0).getSigningCertificate(). getX509Certificate().getEncoded(); byte[] singingCertAfterSerialization = deserializedContainer.getSignature(0).getSigningCertificate(). getX509Certificate().getEncoded(); assertArrayEquals(signingCertBeforeSerialization, singingCertAfterSerialization); } @Test public void serializationGetRawSignature() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); byte[] rawSignatureBeforeSerialization = container.getSignature(0).getRawSignature(); byte[] rawSignatureAfterSerialization = deserializedContainer.getSignature(0).getRawSignature(); assertArrayEquals(rawSignatureBeforeSerialization, rawSignatureAfterSerialization); } @Test public void serializationGetTimeStampTokenCertificate() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); byte[] timeStampTokenCertificateBeforeSerialization = container.getSignature(0). getTimeStampTokenCertificate().getX509Certificate().getEncoded(); byte[] timeStampTokenCertificateAfterSerialization = deserializedContainer.getSignature(0). getTimeStampTokenCertificate().getX509Certificate().getEncoded(); assertArrayEquals(timeStampTokenCertificateBeforeSerialization, timeStampTokenCertificateAfterSerialization); } @Test public void serializationGetProfile() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); SignatureProfile signatureProfileBeforeSerialization = container.getSignature(0).getProfile(); SignatureProfile signatureProfileAfterSerialization = deserializedContainer.getSignature(0).getProfile(); assertEquals(signatureProfileBeforeSerialization, signatureProfileAfterSerialization); } @Test public void serializationGetDataFiles() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); int nrOfDataFilesBeforeSerialization = container.getDataFiles().size(); int nrOfDataFilesAfterSerialization = deserializedContainer.getDataFiles().size(); assertEquals(nrOfDataFilesBeforeSerialization, nrOfDataFilesAfterSerialization); } @Test public void serializationDataFileCheck() throws Exception { Container container = create(); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); serialize(container, "container.bin"); Container deserializedContainer = deserializer("container.bin"); DataFile dataFileBeforeSerialization = container.getDataFile(0); DataFile dataFileAfterSerialization = deserializedContainer.getDataFile(0); assertEquals(dataFileBeforeSerialization.getFileSize(), dataFileAfterSerialization.getFileSize()); assertArrayEquals(dataFileBeforeSerialization.getBytes(), dataFileAfterSerialization.getBytes()); assertEquals(dataFileBeforeSerialization.getId(), dataFileAfterSerialization.getId()); assertEquals(dataFileBeforeSerialization.getName(), dataFileAfterSerialization.getName()); assertEquals(dataFileBeforeSerialization.getMediaType(), dataFileAfterSerialization.getMediaType()); byte[] bytesBeforeSerialization = IOUtils.toByteArray(dataFileBeforeSerialization.getStream()); byte[] bytesAfterSerialization = IOUtils.toByteArray(dataFileAfterSerialization.getStream()); assertArrayEquals(bytesBeforeSerialization, bytesAfterSerialization); assertArrayEquals(dataFileAfterSerialization.calculateDigest(), dataFileBeforeSerialization.calculateDigest()); } @Test public void testOCSPRevoked() { Configuration configuration = new Configuration(Configuration.Mode.PROD); configuration.setOCSPAccessCertificateFileName("testFiles/ocsp_juurdepaasutoend.p12d"); configuration.setOCSPAccessCertificatePassword("0vRsI0XQ".toCharArray()); Container container = Container.open("testFiles/EE-TS-BpLT-R-001.asice", configuration); ValidationResult result = container.validate(); assertFalse(result.isValid()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void signatureFileContainsIncorrectFileName() { Container container = Container.open("testFiles/filename_mismatch_signature.asice"); ValidationResult validate = container.validate(); assertEquals(1, validate.getErrors().size()); assertEquals("The reference data object(s) not found!", validate.getErrors().get(0).toString()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void secondSignatureFileContainsIncorrectFileName() { Container container = Container.open("testFiles/filename_mismatch_second_signature.asice"); ValidationResult validate = container.validate(); List<DigiDoc4JException> errors = validate.getErrors(); assertEquals(3, errors.size()); assertEquals("Manifest file has an entry for file test.txt with mimetype text/plain but the signature file" + " for signature S1 does not.", errors.get(0).toString()); assertEquals("Container contains a file named test.txt which is not found in the signature file", errors.get(1).toString()); assertEquals("The reference data object(s) is not intact!", errors.get(2).toString()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void manifestFileContainsIncorrectFileName() { Configuration configuration = new Configuration(Configuration.Mode.PROD); Container container = Container.open("testFiles/filename_mismatch_manifest.asice", configuration); ValidationResult validate = container.validate(); assertEquals(2, validate.getErrors().size()); assertEquals("Manifest file has an entry for file incorrect.txt with mimetype text/plain" + " but the signature file for signature S0 does not.", validate.getErrors().get(0).toString()); assertEquals("The signature file for signature S0 has an entry for file RELEASE-NOTES.txt with mimetype" + " text/plain but the manifest file does not.", validate.getErrors().get(1).toString()); } @Test public void revocationAndTimeStampDifferenceTooLarge() { Configuration configuration = new Configuration(Configuration.Mode.PROD); Container container = Container.open("testFiles/revocation_timestamp_delta_26h.asice", configuration); ValidationResult validate = container.validate(); assertEquals(1, validate.getErrors().size()); assertEquals("The difference between the revocation time and the signature time stamp is too large", validate.getErrors().get(0).toString()); } @Test public void revocationAndTimeStampDifferenceNotTooLarge() { Configuration configuration = new Configuration(Configuration.Mode.PROD); configuration.setValidationPolicy("conf/test_constraint_SigningTimeCreationTimeDeltaIs27H.xml"); Container container = Container.open("testFiles/revocation_timestamp_delta_26h.asice", configuration); ValidationResult validate = container.validate(); assertEquals(0, validate.getErrors().size()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void signatureFileAndManifestFileContainDifferentMimeTypeForFile() { Configuration configuration = new Configuration(Configuration.Mode.PROD); Container container = Container.open("testFiles/mimetype_mismatch.asice", configuration); ValidationResult validate = container.validate(); assertEquals(2, validate.getErrors().size()); assertEquals("Manifest file has an entry for file RELEASE-NOTES.txt with mimetype application/pdf" + " but the signature file for signature S0 does not.", validate.getErrors().get(0).toString()); assertEquals("The signature file for signature S0 has an entry for file RELEASE-NOTES.txt with mimetype" + " text/plain but the manifest file does not.", validate.getErrors().get(1).toString()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void dssReturnsEmptySignatureList() { Container container = Container.open("testFiles/filename_mismatch_signature.asice"); ValidationResult validate = container.validate(); assertEquals(1, validate.getErrors().size()); assertEquals("The reference data object(s) not found!", validate.getErrors().get(0).toString()); } @Test(expected = DigiDoc4JException.class) public void duplicateFileThrowsException() { Container container = Container.open("testFiles/22902_data_files_with_same_names.bdoc"); container.validate(); } @Test(expected = DigiDoc4JException.class) public void duplicateSignatureFileThrowsException() { Container container = Container.open("testFiles/22913_signatures_xml_double.bdoc"); container.validate(); } @Test(expected = DigiDoc4JException.class) public void missingManifestFile() { Container container = Container.open("testFiles/missing_manifest.asice"); container.validate(); } @Test(expected = DigiDoc4JException.class) public void missingMimeTypeFile() { Container.open("testFiles/missing_mimetype_file.asice"); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void containerHasFileWhichIsNotInManifestAndNotInSignatureFile() { Configuration configuration = new Configuration(Configuration.Mode.PROD); Container container = Container.open("testFiles/extra_file_in_container.asice", configuration); ValidationResult result = container.validate(); List<DigiDoc4JException> errors = result.getErrors(); assertEquals(1, errors.size()); assertEquals("Container contains a file named AdditionalFile.txt which is not found in the signature file", errors.get(0).getMessage()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void containerMissesFileWhichIsInManifestAndSignatureFile() { Container container = Container.open("testFiles/zip_misses_file_which_is_in_manifest.asice"); ValidationResult result = container.validate(); List<DigiDoc4JException> errors = result.getErrors(); assertEquals(1, errors.size()); assertEquals("The reference data object(s) not found!", errors.get(0).toString()); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test public void containerMissingOCSPData() { Container container = Container.open("testFiles/TS-06_23634_TS_missing_OCSP_adjusted.asice"); List<DigiDoc4JException> errors = container.validate().getErrors(); assertEquals("ASiC_E_BASELINE_LT", container.getSignatureProfile()); assertEquals(1, errors.size()); assertTrue(errors.get(0).toString().contains("No revocation data for the certificate")); } @Test(expected = DigiDoc4JException.class) public void corruptedOCSPDataThrowsException() { Container.open("testFiles/corrupted_ocsp_data.asice"); } @Test @Ignore //TODO Currently BES container validates with an error: revocation data not found public void containerWithBESProfileHasNoValidationErrors() throws Exception { BDocContainer container = new BDocContainer(); container.setSignatureProfile(B_BES); container.addDataFile("testFiles/test.txt", "text/plain"); container.sign(PKCS12_SIGNER); assertEquals("ASiC_E_BASELINE_B", container.getSignatureProfile()); assertNull(container.getSignature(0).getOCSPCertificate()); ValidationResult result = container.validate(); assertEquals(0, result.getErrors().size()); } }
package com.badlogic.gdx.utils; import com.badlogic.gdx.utils.JsonWriter.OutputType; /** Container for a JSON object, array, string, double, long, boolean, or null. * <p> * Iteration of arrays or objects is easily done using a for loop:<br> * * <pre> * JsonValue map = ...; * for (JsonValue entry = map.child(); entry != null; entry = entry.next()) * System.out.println(entry.name() + " = " + entry.asString()); * </pre> * @author Nathan Sweet */ public class JsonValue { private String name; private ValueType type; private String stringValue; private Boolean booleanValue; private Double doubleValue; private long longValue; private JsonValue child, next, prev; public JsonValue (ValueType type) { this.type = type; } /** @param value May be null. */ public JsonValue (String value) { set(value); } public JsonValue (double value) { set(value); } public JsonValue (long value) { set(value); } public JsonValue (boolean value) { set(value); } /** Returns the child at the specified index. * @return May be null. */ public JsonValue get (int index) { JsonValue current = child; while (current != null && index > 0) { index current = current.next; } return current; } /** Returns the child with the specified name. * @return May be null. */ public JsonValue get (String name) { JsonValue current = child; while (current != null && !current.name.equalsIgnoreCase(name)) current = current.next; return current; } public JsonValue require (int index) { JsonValue current = child; while (current != null && index > 0) { index current = current.next; } if (current == null) throw new IllegalArgumentException("Child not found with index: " + index); return current; } public JsonValue require (String name) { JsonValue current = child; while (current != null && !current.name.equalsIgnoreCase(name)) current = current.next; if (current == null) throw new IllegalArgumentException("Child not found with name: " + name); return current; } /** Removes the child with the specified name. * @return May be null. */ public JsonValue remove (int index) { JsonValue child = get(index); if (child == null) return null; if (child.prev == null) { this.child = child.next; if (this.child != null) this.child.prev = null; } else { child.prev.next = child.next; if (child.next != null) child.next.prev = child.prev; } return child; } /** Removes the child with the specified name. * @return May be null. */ public JsonValue remove (String name) { JsonValue child = get(name); if (child == null) return null; if (child.prev == null) { this.child = child.next; if (this.child != null) this.child.prev = null; } else { child.prev.next = child.next; if (child.next != null) child.next.prev = child.prev; } return child; } /** Returns this number of children in the array or object. */ public int size () { JsonValue current = child; int size = 0; while (current != null) { size++; current = current.next; } return size; } public String asString () { if (stringValue != null) return stringValue; if (doubleValue != null) { if (doubleValue % 1 == 0) return Long.toString(longValue); return Double.toString(doubleValue); } if (booleanValue != null) return Boolean.toString(booleanValue); if (type == ValueType.nullValue) return null; throw new IllegalStateException("Value cannot be converted to string: " + type); } public float asFloat () { if (doubleValue != null) return doubleValue.floatValue(); if (stringValue != null) { try { return Float.parseFloat(stringValue); } catch (NumberFormatException ignored) { } } if (booleanValue != null) return booleanValue ? 1 : 0; throw new IllegalStateException("Value cannot be converted to float: " + type); } public double asDouble () { if (doubleValue != null) return doubleValue; if (stringValue != null) { try { return Double.parseDouble(stringValue); } catch (NumberFormatException ignored) { } } if (booleanValue != null) return booleanValue ? 1 : 0; throw new IllegalStateException("Value cannot be converted to double: " + type); } public long asLong () { if (doubleValue != null) return longValue; if (stringValue != null) { try { return Long.parseLong(stringValue); } catch (NumberFormatException ignored) { } } if (booleanValue != null) return booleanValue ? 1 : 0; throw new IllegalStateException("Value cannot be converted to long: " + type); } public int asInt () { if (doubleValue != null) return (int)longValue; if (stringValue != null) { try { return Integer.parseInt(stringValue); } catch (NumberFormatException ignored) { } } if (booleanValue != null) return booleanValue ? 1 : 0; throw new IllegalStateException("Value cannot be converted to int: " + type); } public boolean asBoolean () { if (booleanValue != null) return booleanValue; if (doubleValue != null) return longValue == 0; if (stringValue != null) return stringValue.equalsIgnoreCase("true"); throw new IllegalStateException("Value cannot be converted to boolean: " + type); } /** Finds the child with the specified name and returns its first child. * @return May be null. */ public JsonValue getChild (String name) { JsonValue child = get(name); return child == null ? null : child.child; } /** Finds the child with the specified name and returns it as a string. Returns defaultValue if not found. * @param defaultValue May be null. */ public String getString (String name, String defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue() || child.isNull()) ? defaultValue : child.asString(); } /** Finds the child with the specified name and returns it as a float. Returns defaultValue if not found. */ public float getFloat (String name, float defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue()) ? defaultValue : child.asFloat(); } /** Finds the child with the specified name and returns it as a double. Returns defaultValue if not found. */ public double getDouble (String name, double defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue()) ? defaultValue : child.asDouble(); } /** Finds the child with the specified name and returns it as a long. Returns defaultValue if not found. */ public long getLong (String name, long defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue()) ? defaultValue : child.asLong(); } /** Finds the child with the specified name and returns it as an int. Returns defaultValue if not found. */ public int getInt (String name, int defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue()) ? defaultValue : child.asInt(); } /** Finds the child with the specified name and returns it as a boolean. Returns defaultValue if not found. */ public boolean getBoolean (String name, boolean defaultValue) { JsonValue child = get(name); return (child == null || !child.isValue()) ? defaultValue : child.asBoolean(); } public String getString (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asString(); } public float getFloat (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asFloat(); } public double getDouble (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asDouble(); } public long getLong (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asLong(); } public int getInt (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asInt(); } public boolean getBoolean (String name) { JsonValue child = get(name); if (child == null) throw new IllegalArgumentException("Named value not found: " + name); return child.asBoolean(); } public String getString (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asString(); } public float getFloat (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asFloat(); } public double getDouble (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asDouble(); } public long getLong (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asLong(); } public int getInt (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asInt(); } public boolean getBoolean (int index) { JsonValue child = get(index); if (child == null) throw new IllegalArgumentException("Indexed value not found: " + name); return child.asBoolean(); } public ValueType type () { return type; } public void setType (ValueType type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); this.type = type; } public boolean isArray () { return type == ValueType.array; } public boolean isObject () { return type == ValueType.object; } public boolean isString () { return type == ValueType.stringValue; } /** Returns true if this is a double or long value. */ public boolean isNumber () { return type == ValueType.doubleValue || type == ValueType.longValue; } public boolean isDouble () { return type == ValueType.doubleValue; } public boolean isLong () { return type == ValueType.longValue; } public boolean isBoolean () { return type == ValueType.booleanValue; } public boolean isNull () { return type == ValueType.nullValue; } /** Returns true if this is not an array or object. */ public boolean isValue () { switch (type) { case stringValue: case doubleValue: case longValue: case booleanValue: case nullValue: return true; } return false; } /** Returns the name for this object value. * @return May be null. */ public String name () { return name; } public void setName (String name) { this.name = name; } /** Returns the first child for this object or array. * @return May be null. */ public JsonValue child () { return child; } public void addChild (JsonValue newChild) { JsonValue current = child; if (current == null) { child = newChild; return; } while (true) { if (current.next == null) { current.next = newChild; newChild.prev = current; return; } current = current.next; } } /** Returns the next sibling of this value. * @return May be null. */ public JsonValue next () { return next; } public void setNext (JsonValue next) { this.next = next; } /** Returns the previous sibling of this value. * @return May be null. */ public JsonValue prev () { return prev; } public void setPrev (JsonValue prev) { this.prev = prev; } /** @param value May be null. */ public void set (String value) { stringValue = value; type = value == null ? ValueType.nullValue : ValueType.stringValue; } public void set (double value) { doubleValue = value; longValue = (long)value; type = ValueType.doubleValue; } public void set (long value) { longValue = value; doubleValue = (double)value; type = ValueType.longValue; } public void set (boolean value) { booleanValue = value; type = ValueType.booleanValue; } public String toString () { return prettyPrint(OutputType.minimal, 0); } public String prettyPrint (OutputType outputType, int singleLineColumns) { StringBuilder buffer = new StringBuilder(512); prettyPrint(this, buffer, outputType, 0, singleLineColumns); return buffer.toString(); } private void prettyPrint (JsonValue object, StringBuilder buffer, OutputType outputType, int indent, int singleLineColumns) { if (object.isObject()) { if (object.child() == null) { buffer.append("{}"); } else { boolean newLines = !isFlat(object); int start = buffer.length(); outer: while (true) { buffer.append(newLines ? "{\n" : "{ "); int i = 0; for (JsonValue child = object.child(); child != null; child = child.next()) { if (newLines) indent(indent, buffer); buffer.append(outputType.quoteName(child.name())); buffer.append(": "); prettyPrint(child, buffer, outputType, indent + 1, singleLineColumns); if (child.next() != null) buffer.append(","); buffer.append(newLines ? '\n' : ' '); if (!newLines && buffer.length() - start > singleLineColumns) { buffer.setLength(start); newLines = true; continue outer; } } break; } if (newLines) indent(indent - 1, buffer); buffer.append('}'); } } else if (object.isArray()) { if (object.child() == null) { buffer.append("[]"); } else { boolean newLines = !isFlat(object); int start = buffer.length(); outer: while (true) { buffer.append(newLines ? "[\n" : "[ "); for (JsonValue child = object.child(); child != null; child = child.next()) { if (newLines) indent(indent, buffer); prettyPrint(child, buffer, outputType, indent + 1, singleLineColumns); if (child.next() != null) buffer.append(","); buffer.append(newLines ? '\n' : ' '); if (!newLines && buffer.length() - start > singleLineColumns) { buffer.setLength(start); newLines = true; continue outer; } } break; } if (newLines) indent(indent - 1, buffer); buffer.append(']'); } } else if (object.isString()) { buffer.append(outputType.quoteValue(object.asString())); } else if (object.isDouble()) { double doubleValue = object.asDouble(); long longValue = (int)doubleValue; buffer.append(doubleValue - longValue == 0 ? longValue : object); } else if (object.isLong()) { buffer.append(object.asLong()); } else if (object.isBoolean()) { buffer.append(object.asBoolean()); } else if (object.isNull()) { buffer.append("null"); } else throw new SerializationException("Unknown object type: " + object); } static private boolean isFlat (JsonValue object) { for (JsonValue child = object.child(); child != null; child = child.next()) if (child.isObject() || child.isArray()) return false; return true; } static private void indent (int count, StringBuilder buffer) { for (int i = 0; i < count; i++) buffer.append('\t'); } public enum ValueType { object, array, stringValue, doubleValue, longValue, booleanValue, nullValue } }
package jordan.bettercraft.init; import jordan.bettercraft.init.blocks.CustomBlock; import jordan.bettercraft.init.blocks.crops.LettucePlant; import jordan.bettercraft.init.blocks.crops.StrawberryPlant; import jordan.bettercraft.init.blocks.crops.SweetcornPlant; import jordan.bettercraft.init.blocks.crops.TomatoPlant; import jordan.bettercraft.init.blocks.ores.CopperOre; import jordan.bettercraft.init.blocks.ores.RubyOre; import jordan.bettercraft.init.blocks.ores.SapphireOre; import jordan.bettercraft.main.Reference; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; public class BetterCrops { public static Block STRAWBERRY_PLANT; public static Block SWEET_CORN_PLANT; public static Block LETTUCE_PLANT; public static Block TOMATO_PLANT; public static void init() { STRAWBERRY_PLANT = new StrawberryPlant(); STRAWBERRY_PLANT.setUnlocalizedName("strawberry_plant"); SWEET_CORN_PLANT = new SweetcornPlant(); SWEET_CORN_PLANT.setUnlocalizedName("sweet_corn_plant"); LETTUCE_PLANT = new LettucePlant(); LETTUCE_PLANT.setUnlocalizedName("lettuce_plant"); TOMATO_PLANT = new TomatoPlant(); TOMATO_PLANT.setUnlocalizedName("strawberry_plant"); } public static void registerRenders() { registerRender(STRAWBERRY_PLANT); registerRender(SWEET_CORN_PLANT); registerRender(LETTUCE_PLANT); registerRender(TOMATO_PLANT); } public static void registerRender(Block block) { Item item = Item.getItemFromBlock(block); Minecraft.getMinecraft().getRenderItem().getItemModelMesher() .register(item, 0, new ModelResourceLocation(Reference.MODID + ":" + item.getUnlocalizedName().substring(5), "inventory")); } }
package com.joelapenna.foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import android.net.Uri; import android.text.TextUtils; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Foursquare { private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare"); public static final boolean DEBUG = true; public static final boolean PARSER_DEBUG = false; public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com"; public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends"; public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends"; public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup"; public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings"; public static final String MALE = "male"; public static final String FEMALE = "female"; private String mPhone; private String mPassword; private FoursquareHttpApiV1 mFoursquareV1; @V1 public Foursquare(FoursquareHttpApiV1 httpApi) { mFoursquareV1 = httpApi; } public void setCredentials(String phone, String password) { mPhone = phone; mPassword = password; mFoursquareV1.setCredentials(phone, password); } @V1 public void setOAuthToken(String token, String secret) { mFoursquareV1.setOAuthTokenWithSecret(token, secret); } @V1 public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void clearAllCredentials() { setCredentials(null, null); setOAuthToken(null, null); } @V1 public boolean hasCredentials() { return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret(); } @V1 public boolean hasLoginAndPassword() { return mFoursquareV1.hasCredentials(); } @V1 public Credentials authExchange() throws FoursquareException, FoursquareError, FoursquareCredentialsException, IOException { if (mFoursquareV1 == null) { throw new NoSuchMethodError( "authExchange is unavailable without a consumer key/secret."); } return mFoursquareV1.authExchange(mPhone, mPassword); } @V1 public Tip addTip(String vid, String text, String type, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 @LocationRequired public Venue addVenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public CheckinResult checkin(String venueId, String venueName, Location location, String shout, boolean isPrivate, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, shout, isPrivate, twitter, facebook); } @V1 public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friends(String userId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friends(userId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friendRequests(); } @V1 public User friendApprove(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendApprove(userId); } @V1 public User friendDeny(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendDeny(userId); } @V1 public User friendSendrequest(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendSendrequest(userId); } @V1 public Group<Group<Tip>> tips(Location location, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, limit); } @V1 public User user(String user, boolean mayor, boolean badges, Location location) throws FoursquareException, FoursquareError, IOException { if (location != null) { return mFoursquareV1.user(user, mayor, badges, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } else { return mFoursquareV1.user(user, mayor, badges, null, null, null, null, null); } } @V1 public Venue venue(String id, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 @LocationRequired public Group<Group<Venue>> venues(Location location, String query, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, query, limit); } public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion, boolean useOAuth) { LOG.log(Level.INFO, "Using foursquare.com for requests."); return new FoursquareHttpApiV1(domain, clientVersion, useOAuth); } public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) { return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth); } public static final String createLeaderboardUrl(String userId, Location location) { Uri.Builder builder = new Uri.Builder() .scheme("http") .authority("foursquare.com") .appendEncodedPath("/iphone/me") .appendQueryParameter("view", "all") .appendQueryParameter("scope", "friends") .appendQueryParameter("uid", userId); if (!TextUtils.isEmpty(location.geolat)) { builder.appendQueryParameter("geolat", location.geolat); } if (!TextUtils.isEmpty(location.geolong)) { builder.appendQueryParameter("geolong", location.geolong); } if (!TextUtils.isEmpty(location.geohacc)) { builder.appendQueryParameter("geohacc", location.geohacc); } if (!TextUtils.isEmpty(location.geovacc)) { builder.appendQueryParameter("geovacc", location.geovacc); } return builder.build().toString(); } @interface V1 { } /** * This api call requires a location. */ @interface LocationRequired { } public static class Location { String geolat = null; String geolong = null; String geohacc = null; String geovacc = null; String geoalt = null; public Location() { } public Location(final String geolat, final String geolong, final String geohacc, final String geovacc, final String geoalt) { this.geolat = geolat; this.geolong = geolong; this.geohacc = geohacc; this.geovacc = geovacc; this.geoalt = geovacc; } public Location(final String geolat, final String geolong) { this(geolat, geolong, null, null, null); } } }
package com.takwolf.digest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class Digest { public static final Digest MD2 = new Digest(Algorithm.MD2); public static final Digest MD5 = new Digest(Algorithm.MD5); public static final Digest SHA1 = new Digest(Algorithm.SHA1); public static final Digest SHA256 = new Digest(Algorithm.SHA256); public static final Digest SHA384 = new Digest(Algorithm.SHA384); public static final Digest SHA512 = new Digest(Algorithm.SHA512); public enum Algorithm { MD2("MD2"), MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), SHA384("SHA-384"), SHA512("SHA-512"); private final String value; Algorithm(String value) { this.value = value; } public String getValue() { return value; } } private final Algorithm algorithm; private Digest(Algorithm algorithm) { this.algorithm = algorithm; } public byte[] getRaw(byte[] data) { try { return MessageDigest.getInstance(algorithm.getValue()).digest(data); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } public byte[] getRaw(String data) { return getRaw(data.getBytes()); } public String getHex(byte[] data) { StringBuilder sb = new StringBuilder(); for (byte b : getRaw(data)) { sb.append(String.format("%02x", 0xFF & b)); } return sb.toString(); } public String getHex(String data) { return getHex(data.getBytes()); } }
package com.intellij.codeInsight.actions; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.lang.LanguageFormatting; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class AbstractLayoutCodeProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor"); protected final Project myProject; private final Module myModule; private PsiDirectory myDirectory; private PsiFile myFile; private PsiFile[] myFiles; private boolean myIncludeSubdirs; private final String myProgressText; private final String myCommandName; private final Runnable myPostRunnable; protected AbstractLayoutCodeProcessor(Project project, String commandName, String progressText) { myProject = project; myModule = null; myDirectory = null; myIncludeSubdirs = true; myCommandName = commandName; myProgressText = progressText; myPostRunnable = null; } protected AbstractLayoutCodeProcessor(Project project, Module module, String commandName, String progressText) { myProject = project; myModule = module; myDirectory = null; myIncludeSubdirs = true; myCommandName = commandName; myProgressText = progressText; myPostRunnable = null; } protected AbstractLayoutCodeProcessor(Project project, PsiDirectory directory, boolean includeSubdirs, String progressText, String commandName) { myProject = project; myModule = null; myDirectory = directory; myIncludeSubdirs = includeSubdirs; myProgressText = progressText; myCommandName = commandName; myPostRunnable = null; } protected AbstractLayoutCodeProcessor(Project project, PsiFile file, String progressText, String commandName) { myProject = project; myModule = null; myFile = file; myProgressText = progressText; myCommandName = commandName; myPostRunnable = null; } protected AbstractLayoutCodeProcessor(Project project, PsiFile[] files, String progressText, String commandName, Runnable postRunnable) { myProject = project; myModule = null; myFiles = filterFiles(files); myProgressText = progressText; myCommandName = commandName; myPostRunnable = postRunnable; } private static PsiFile[] filterFiles(PsiFile[] files){ ArrayList<PsiFile> list = new ArrayList<PsiFile>(); for (PsiFile file : files) { if (isFormatable(file)) { list.add(file); } } return list.toArray(new PsiFile[list.size()]); } @NotNull protected abstract Runnable preprocessFile(PsiFile file) throws IncorrectOperationException; public void run() { if (myDirectory != null){ runProcessDirectory(myDirectory, myIncludeSubdirs); } else if (myFiles != null){ runProcessFiles(myFiles); } else if (myFile != null) { runProcessFile(myFile); } else if (myModule != null) { runProcessOnModule(myModule); } else if (myProject != null) { runProcessOnProject(myProject); } } private void runProcessFile(final PsiFile file) { Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); if (document == null) { return; } if (!file.isWritable()){ if (!FileDocumentManager.fileForDocumentCheckedOutSuccessfully(document, myProject)) { Messages.showMessageDialog(myProject, PsiBundle.message("cannot.modify.a.read.only.file", file.getName()), CodeInsightBundle.message("error.dialog.readonly.file.title"), Messages.getErrorIcon() ); return; } } final Runnable[] resultRunnable = new Runnable[1]; Runnable readAction = new Runnable() { public void run() { if (!checkFileWritable(file)) return; try{ resultRunnable[0] = preprocessFile(file); } catch(IncorrectOperationException e){ LOG.error(e); } } }; Runnable writeAction = new Runnable() { public void run() { if (resultRunnable[0] != null){ resultRunnable[0].run(); } } }; runLayoutCodeProcess(readAction, writeAction); } private boolean checkFileWritable(final PsiFile file){ if (!file.isWritable()){ MessagesEx.fileIsReadOnly(myProject, file.getVirtualFile()) .setTitle(CodeInsightBundle.message("error.dialog.readonly.file.title")) .showLater(); return false; } else{ return true; } } @Nullable private Runnable preprocessFiles(List<PsiFile> files) { ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); String oldText = null; double oldFraction = 0; if (progress != null){ oldText = progress.getText(); oldFraction = progress.getFraction(); progress.setText(myProgressText); } final Runnable[] runnables = new Runnable[files.size()]; for(int i = 0; i < files.size(); i++) { PsiFile file = files.get(i); if (progress != null){ if (progress.isCanceled()) return null; progress.setFraction((double)i / files.size()); } if (file.isWritable()){ try{ runnables[i] = preprocessFile(file); } catch(IncorrectOperationException e){ LOG.error(e); } } files.set(i, null); } if (progress != null){ progress.setText(oldText); progress.setFraction(oldFraction); } return new Runnable() { public void run() { for (Runnable runnable : runnables) { if (runnable != null) { runnable.run(); } } } }; } private void runProcessFiles(final PsiFile[] files) { // let's just ignore read-only files here final Runnable[] resultRunnable = new Runnable[1]; runLayoutCodeProcess( new Runnable() { public void run() { resultRunnable[0] = preprocessFiles(new ArrayList<PsiFile>(Arrays.asList(files))); } }, new Runnable() { public void run() { if (resultRunnable[0] != null){ resultRunnable[0].run(); } } } ); } private void runProcessDirectory(final PsiDirectory directory, final boolean recursive) { final ArrayList<PsiFile> array = new ArrayList<PsiFile>(); collectFilesToProcess(array, directory, recursive); final String where = CodeInsightBundle.message("process.scope.directory", directory.getVirtualFile().getPresentableUrl()); runProcessOnFiles(where, array); } private void runProcessOnProject(final Project project) { final ArrayList<PsiFile> array = new ArrayList<PsiFile>(); collectFilesInProject(project, array); String where = CodeInsightBundle.message("process.scope.project", project.getPresentableUrl()); runProcessOnFiles(where, array); } private void runProcessOnModule(final Module module) { final ArrayList<PsiFile> array = new ArrayList<PsiFile>(); collectFilesInModule(module, array); String where = CodeInsightBundle.message("process.scope.module", module.getModuleFilePath()); runProcessOnFiles(where, array); } private void collectFilesInProject(Project project, ArrayList<PsiFile> array) { final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { collectFilesInModule(module, array); } } private void collectFilesInModule(Module module, ArrayList<PsiFile> array) { final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots(); for (VirtualFile root : contentRoots) { PsiDirectory dir = PsiManager.getInstance(myProject).findDirectory(root); if (dir != null) { collectFilesToProcess(array, dir, true); } } } private void runProcessOnFiles(final String where, final List<PsiFile> array) { boolean success = CodeInsightUtilBase.preparePsiElementsForWrite(array); if (!success) { List<PsiFile> writeables = new ArrayList<PsiFile>(); for (PsiFile file : array) { if (file.isWritable()) { writeables.add(file); } } if (writeables.isEmpty()) return; int res = Messages.showOkCancelDialog(myProject, CodeInsightBundle.message("error.dialog.readonly.files.message", where), CodeInsightBundle.message("error.dialog.readonly.files.title"), Messages.getQuestionIcon()); if (res != 0) { return; } array.clear(); array.addAll(writeables); } final Runnable[] resultRunnable = new Runnable[1]; runLayoutCodeProcess(new Runnable() { public void run() { resultRunnable[0] = preprocessFiles(array); } }, new Runnable() { public void run() { if (resultRunnable[0] != null) { resultRunnable[0].run(); } } }); } private static boolean isFormatable(PsiFile file) { return LanguageFormatting.INSTANCE.forContext(file) != null; } private static void collectFilesToProcess(ArrayList<PsiFile> array, PsiDirectory dir, boolean recursive) { PsiFile[] files = dir.getFiles(); for (PsiFile file : files) { if (isFormatable(file)) { array.add(file); } } if (recursive){ PsiDirectory[] subdirs = dir.getSubdirectories(); for (PsiDirectory subdir : subdirs) { collectFilesToProcess(array, subdir, recursive); } } } private void runLayoutCodeProcess(final Runnable readAction, final Runnable writeAction) { final ProgressWindow progressWindow = new ProgressWindow(true, myProject); progressWindow.setTitle(myCommandName); progressWindow.setText(myProgressText); final ModalityState modalityState = ModalityState.current(); final Runnable process = new Runnable() { public void run() { ApplicationManager.getApplication().runReadAction(readAction); } }; Runnable runnable = new Runnable() { public void run() { try { //DaemonCodeAnalyzer.getInstance(myProject).setUpdateByTimerEnabled(false); ProgressManager.getInstance().runProcess(process, progressWindow); } catch(ProcessCanceledException e) { return; } /* finally { DaemonCodeAnalyzer.getInstance(myProject).setUpdateByTimerEnabled(true); } */ final Runnable writeRunnable = new Runnable() { public void run() { CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { CommandProcessor.getInstance().markCurrentCommandAsComplex(myProject); ApplicationManager.getApplication().runWriteAction(writeAction); if (myPostRunnable != null) { ApplicationManager.getApplication().invokeLater(myPostRunnable); } } }, myCommandName, null); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { writeRunnable.run(); } else { ApplicationManager.getApplication().invokeLater(writeRunnable, modalityState, myProject.getDisposed()); } } }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().executeOnPooledThread(runnable); } } public void runWithoutProgress() throws IncorrectOperationException { final Runnable runnable = preprocessFile(myFile); runnable.run(); } }
package org.infinispan.demo; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; public class CacheListener { public static void main(String[] args) { Configuration conf = new ConfigurationBuilder().build(); EmbeddedCacheManager cm = new DefaultCacheManager(conf); Cache<String, String> cache = cm.getCache(); cache.addListener(new EntryListener()); for (int i = 0; i < 100; i++) { cache.put("key" + i, "value" + i); } cm.stop(); } }
package liquibase.integration.ant; import liquibase.resource.FileSystemResourceAccessor; import liquibase.util.StringUtil; import org.apache.tools.ant.AntClassLoader; import java.io.File; public class AntResourceAccessor extends FileSystemResourceAccessor { public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) { if (changeLogDirectory != null) { changeLogDirectory = changeLogDirectory.replace("\\", "/"); } if (changeLogDirectory == null) { this.addRootPath(new File("").getAbsoluteFile().toPath()); this.addRootPath(new File("/").getAbsoluteFile().toPath()); } else { this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath()); } final String classpath = StringUtil.trimToNull(classLoader.getClasspath()); if (classpath != null) { for (String path : classpath.split(System.getProperty("path.separator"))) { this.addRootPath(new File(path).toPath()); } } } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import java.lang.annotation.Annotation; import java.util.Arrays; import com.facebook.litho.annotations.FromBind; import com.facebook.litho.annotations.FromBoundsDefined; import com.facebook.litho.annotations.FromMeasure; import com.facebook.litho.annotations.FromPrepare; import com.facebook.litho.annotations.GetExtraAccessibilityNodeAt; import com.facebook.litho.annotations.GetExtraAccessibilityNodesCount; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBind; import com.facebook.litho.annotations.OnBoundsDefined; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMeasureBaseline; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnPopulateAccessibilityNode; import com.facebook.litho.annotations.OnPopulateExtraAccessibilityNode; import com.facebook.litho.annotations.OnPrepare; import com.facebook.litho.annotations.OnUnbind; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.ShouldUpdate; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.SpecModel; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public class MountSpecHelper extends ComponentSpecHelper { private enum MountType { NONE, DRAWABLE, VIEW, } private static final Class<Annotation>[] STAGE_ANNOTATIONS = new Class[] { /* Methods that can have inter-stage props - these MUST come first in this list */ OnPrepare.class, OnMeasure.class, OnBoundsDefined.class, OnBind.class, /* Methods that do not support inter-stage props */ OnMount.class, OnPopulateAccessibilityNode.class, GetExtraAccessibilityNodesCount.class, OnPopulateExtraAccessibilityNode.class, GetExtraAccessibilityNodeAt.class, OnUnbind.class, OnUnmount.class, }; private static final Class<Annotation>[] INTER_STAGE_INPUT_ANNOTATIONS = new Class[] { FromPrepare.class, FromMeasure.class, FromBoundsDefined.class, FromBind.class, }; public MountSpecHelper( ProcessingEnvironment processingEnv, TypeElement specElement, SpecModel specModel) { super( processingEnv, specElement, specElement.getAnnotation(MountSpec.class).value(), specElement.getAnnotation(MountSpec.class).isPublic(), STAGE_ANNOTATIONS, INTER_STAGE_INPUT_ANNOTATIONS, specModel); } @Override protected void validate() { if (mQualifiedClassName == null) { throw new ComponentsProcessingException( mSpecElement, "You should either provide an explicit component name " + "e.g. @MountSpec(\"MyComponent\"); or suffix your class name with " + "\"Spec\" e.g. a \"MyComponentSpec\" class name generates a component named " + "\"MyComponent\"."); } if (Utils.getAnnotatedMethod(mStages.getSourceElement(), OnCreateMountContent.class) == null) { throw new ComponentsProcessingException( mSpecElement, "You need to have a method annotated with @OnCreateMountContent in your spec"); } } /** * Generate an onPrepare implementation that delegates to the @OnPrepare-annotated method. */ public void generateOnPrepare() { final ExecutableElement onPrepare = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPrepare.class); if (onPrepare == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = null; methodDescription.name = "onPrepare"; methodDescription.parameterTypes = new TypeName[] {ClassNames.COMPONENT_CONTEXT}; mStages.generateDelegate( methodDescription, onPrepare, ClassNames.COMPONENT); } /** * Generate an onMeasure implementation that delegates to the @OnCreateLayout-annotated method. */ public void generateOnMeasure() { final ExecutableElement onMeasure = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMeasure.class); if (onMeasure == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMeasure"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassNames.COMPONENT_LAYOUT, ClassName.INT, ClassName.INT, ClassNames.SIZE, }; mTypeSpec.addMethod( MethodSpec.methodBuilder("canMeasure") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.BOOLEAN) .addStatement("return true") .build()); mStages.generateDelegate( methodDescription, onMeasure, ClassNames.COMPONENT); } /** * Generate an onBoundsDefined implementation that delegates to the * @OnBoundsDefined-annotated method. */ public void generateOnBoundsDefined() { final ExecutableElement onBoundsDefined = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnBoundsDefined.class); if (onBoundsDefined == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onBoundsDefined"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassNames.COMPONENT_LAYOUT, }; mStages.generateDelegate( methodDescription, onBoundsDefined, ClassNames.COMPONENT); } /** * Generate an onMeasureBaseline implementation that delegates to the * @OnMeasureBaseline-annotated method. */ public void generateOnMeasureBaseline() { final ExecutableElement onMeasureBaseline = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMeasureBaseline.class); if (onMeasureBaseline == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMeasureBaseline"; methodDescription.returnType = TypeName.INT; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, TypeName.INT, TypeName.INT, }; mStages.generateDelegate( methodDescription, onMeasureBaseline, ClassNames.COMPONENT); } /** * Generate an onCreateMountContent implementation that delegates to the * @OnCreateMountContent-annotated method. */ public void generateOnCreateMountContentAndGetMountType() { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); final MountType componentMountType = getMountType(onCreateMountContent.getReturnType()); if (componentMountType != MountType.VIEW && componentMountType != MountType.DRAWABLE) { throw new ComponentsProcessingException( onCreateMountContent, "onCreateMountContent's return type should be either a View or a Drawable subclass"); } mTypeSpec.addMethod( MethodSpec.methodBuilder("getMountType") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE) .addStatement( "return $T.$L", ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE, componentMountType) .build()); mTypeSpec.addMethod( MethodSpec.methodBuilder("poolSize") .addAnnotation(Override.class) .addModifiers(javax.lang.model.element.Modifier.PROTECTED) .returns(TypeName.INT) .addStatement("return "+mSpecElement.getAnnotation(MountSpec.class).poolSize()) .build()); mTypeSpec.addMethod( new OnCreateMountContentMethodBuilder() .target(mStages.getSourceDelegateAccessorName()) .delegateName(onCreateMountContent.getSimpleName().toString()) .build()); } /** * Generate an onMount implementation that delegates to the @OnMount-annotated method. */ public void generateOnMount() { final ExecutableElement onMount = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnMount.class); if (onMount == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.name = "onMount"; methodDescription.returnType = ClassName.VOID; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; if (!Utils.getParametersWithAnnotation(onMount, FromMeasure.class).isEmpty() || !Utils.getParametersWithAnnotation(onMount, FromBoundsDefined.class).isEmpty()) { mTypeSpec.addMethod(new IsMountSizeDependentMethodSpecBuilder().build()); } mStages.generateDelegate( methodDescription, onMount, Arrays.asList(ClassNames.COMPONENT_CONTEXT, getMountType()), ClassNames.COMPONENT); } private TypeName getMountType() { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); return ClassName.get(onCreateMountContent.getReturnType()); } /** * Generate an onBind implementation that delegates to the @OnBind-annotated method. */ public void generateOnBind() { final ExecutableElement onBind = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnBind.class); if (onBind == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onBind"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onBind, methodDescription); } /** * Generate an onUnbind implementation that delegates to the @OnUnbind-annotated method. */ public void generateOnUnbind() { final ExecutableElement onIdle = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnUnbind.class); if (onIdle == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onUnbind"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onIdle, methodDescription); } /** * Generate an onUnmount implementation that delegates to the @OnUnmount-annotated method. */ public void generateOnUnmount() { final ExecutableElement onUnmount = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnUnmount.class); if (onUnmount == null) { return; } final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = ClassName.VOID; methodDescription.name = "onUnmount"; methodDescription.parameterTypes = new TypeName[] { ClassNames.COMPONENT_CONTEXT, ClassName.OBJECT, }; generateMountCompliantMethod(onUnmount, methodDescription); } private void generateMountCompliantMethod( ExecutableElement method, MethodDescription methodDescription) { final ExecutableElement onCreateMountContent = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnCreateMountContent.class); final TypeMirror mountReturnType = onCreateMountContent.getReturnType(); final VariableElement mountParameter = method.getParameters().get(1); final TypeMirror mountParameterType = mountParameter.asType(); // The return type of onMount() and the second parameter on onUnmount() // should have the same type. if (!mStages.isSameType(mountParameterType, mountReturnType)) { throw new ComponentsProcessingException( mountParameter, "Second parameter of " + methodDescription.name + " should be of same type " + "of onCreateMountContent()'s return"); } mStages.generateDelegate( methodDescription, method, Arrays.asList(ClassNames.COMPONENT_CONTEXT, ClassName.get(mountParameterType)), ClassNames.COMPONENT); } private static MountType getMountType(TypeMirror returnTypeParam) { TypeMirror returnType = returnTypeParam; while (returnType.getKind() != TypeKind.NONE && returnType.getKind() != TypeKind.VOID) { final TypeElement returnElement = (TypeElement) ((DeclaredType) returnType).asElement(); final TypeName type = ClassName.get(returnElement); if (type.equals(ClassNames.VIEW)) { return MountType.VIEW; } else if (type.equals(ClassNames.DRAWABLE)) { return MountType.DRAWABLE; } returnType = returnElement.getSuperclass(); } return MountType.NONE; } /** * Generate an onPopulateAccessibilityNode implementation that delegates to the * {@link com.facebook.litho.annotations.OnPopulateAccessibilityNode}-annotated method. */ public void generateAccessibilityMethods() { final ExecutableElement onPopulateAccessibilityNode = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPopulateAccessibilityNode.class); final ExecutableElement onPopulateExtraAccessibilityNode = Utils.getAnnotatedMethod( mStages.getSourceElement(), OnPopulateExtraAccessibilityNode.class); final ExecutableElement getExtraAccessibilityNodeAt = Utils.getAnnotatedMethod( mStages.getSourceElement(), GetExtraAccessibilityNodeAt.class); final ExecutableElement getNumExtraAccessibilityNodes = Utils.getAnnotatedMethod( mStages.getSourceElement(), GetExtraAccessibilityNodesCount.class); if (onPopulateAccessibilityNode == null && onPopulateExtraAccessibilityNode == null && getExtraAccessibilityNodeAt == null && getNumExtraAccessibilityNodes == null) { return; } if ((onPopulateExtraAccessibilityNode != null || getExtraAccessibilityNodeAt != null || getNumExtraAccessibilityNodes != null) && (onPopulateExtraAccessibilityNode == null || getExtraAccessibilityNodeAt == null || getNumExtraAccessibilityNodes == null)) { throw new ComponentsProcessingException( mSpecElement,
// Scope.java package ed.js.engine; import java.lang.reflect.*; import java.util.*; import ed.js.*; import ed.js.func.*; public class Scope { public static Scope GLOBAL = new Scope( "GLOBAL" , JSBuiltInFunctions._myScope ); static { GLOBAL._locked = true; GLOBAL._global = true; } static class _NULL { } static _NULL NULL = new _NULL(); public Scope( String name , Scope parent ){ _name = name; _parent = parent; } public Scope child(){ return new Scope( _name + ".child" , this ); } public Object put( String name , Object o , boolean local ){ if ( _locked ) throw new RuntimeException( "locked" ); if ( local || _parent == null || _parent._locked || ( _objects != null && _objects.containsKey( name ) ) || _global ){ if ( o == null ) o = NULL; if ( o instanceof String) o = new JSString( (String)o ); if ( _objects == null ) _objects = new TreeMap<String,Object>(); _objects.put( name , o ); return o; } _parent.put( name , o , false ); return o; } public Object get( String name ){ final Object r = _get( name ); return r; } Object _get( String name ){ Object foo = _objects == null ? null : _objects.get( name ); if ( foo != null ){ if ( foo == NULL ) return null; return foo; } if ( _parent == null ) return null; return _parent._get( name ); } public JSFunction getFunction( String name ){ Object o = get( name ); if ( o == null ) return null; if ( ! ( o instanceof JSFunction ) ) throw new RuntimeException( "not a function : " + name ); return (JSFunction)o; } public Scope newThis( JSFunction f ){ _this = new JSClass( f ); return this; } public Scope setThis( JSObject o ){ _this = o; return this; } public JSFunction getFunctionAndSetThis( final Object obj , final String name ){ if ( obj instanceof JSObject ){ JSObject jsobj = (JSObject)obj; _this = jsobj; return (JSFunction)(jsobj.get( name )); } _nThis = obj; _nThisFunc = name; return _nativeFuncCall; } public JSObject getThis(){ return _this; } public JSObject clearThisNew( Object whoCares ){ JSObject foo = _this; _this = null; return foo; } public Object clearThisNormal( Object o ){ _this = null; _nThis = null; _nThisFunc = null; return o; } final String _name; final Scope _parent; boolean _locked = false; boolean _global = false; Map<String,Object> _objects; // js this JSObject _this; // native this Object _nThis; String _nThisFunc; private static final Object[] EMPTY_OBJET_ARRAY = new Object[0]; private static final JSFunctionCalls0 _nativeFuncCall = new JSFunctionCalls0(){ Map< Class , Map< String , List<Method> > > _classToMethods = new HashMap< Class , Map< String , List<Method> > >(); List<Method> getMethods( Class c , String n ){ Map<String,List<Method>> m = _classToMethods.get( c ); if ( m == null ){ m = new HashMap<String,List<Method>>(); _classToMethods.put( c , m ); } List<Method> l = m.get( n ); if ( l != null ) return l; l = new ArrayList<Method>(); for ( Method method : c.getMethods() ) if ( method.getName().equals( n ) ) l.add( method ); m.put( n , l ); return l; } public Object call( Scope s , Object params[] ){ final Object obj = s._nThis; final String name = s._nThisFunc; methods: for ( Method m : getMethods( obj.getClass() , name ) ){ Class myClasses[] = m.getParameterTypes(); if ( myClasses != null ){ if ( params == null ) params = EMPTY_OBJET_ARRAY; if ( myClasses.length != params.length ) continue; for ( int i=0; i<myClasses.length; i++ ){ // null is fine with me if ( params[i] == null ) continue; if ( myClasses[i] == String.class ) params[i] = params[i].toString(); if ( ! myClasses[i].isAssignableFrom( params[i].getClass() ) ) continue methods; } } m.setAccessible( true ); try { return m.invoke( obj , params ); } catch ( Exception e ){ throw new RuntimeException( e ); } } throw new RuntimeException( "can't find a valid native method for : " + name ); } }; }
import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.wikidata.wdtk.datamodel.interfaces.EntityDocumentProcessor; import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue; import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument; import org.wikidata.wdtk.datamodel.interfaces.Statement; import org.wikidata.wdtk.datamodel.interfaces.StatementGroup; import org.wikidata.wdtk.datamodel.interfaces.TimeValue; import org.wikidata.wdtk.datamodel.interfaces.Value; import org.wikidata.wdtk.datamodel.interfaces.ValueSnak; import org.wikidata.wdtk.dumpfiles.DumpProcessingController; import org.wikidata.wdtk.dumpfiles.MwRevision; import org.wikidata.wdtk.dumpfiles.MwRevisionProcessor; import org.wikidata.wdtk.dumpfiles.StatisticsMwRevisionProcessor; /** * This program creates the JSON files for the ViziData Web Application * * based on DumpProcessingExample by Markus Kroetzsch * * @version 0.1 * @author Georg Wild * */ public class DataProcessor { public static void main(String[] args) throws IOException { // Define where log messages go Helper.configureLogging(); // Print information about this program printDocumentation(); // Controller object for processing dumps: DumpProcessingController dumpProcessingController = new DumpProcessingController( "wikidatawiki"); // // Use any download directory: // dumpProcessingController.setDownloadDirectory(System.getProperty("user.dir")); // Our local data processor class ItemDataProcessor edpItemStats = new ItemDataProcessor(); // Subscribe to the most recent entity documents of type wikibase item: dumpProcessingController.registerEntityDocumentProcessor(edpItemStats, MwRevision.MODEL_WIKIBASE_ITEM, true); // General statistics and time keeping: MwRevisionProcessor rpRevisionStats = new StatisticsMwRevisionProcessor( "revision processing statistics", 10000); // Subscribe to all current revisions (null = no filter): dumpProcessingController.registerMwRevisionProcessor(rpRevisionStats, null, true); // Start processing (may trigger downloads where needed): // Process all recent dumps (including daily dumps as far as avaiable) dumpProcessingController.processMostRecentJsonDump(); edpItemStats.finishProcessingEntityDocuments(); } /** * Print some basic documentation about this program. */ private static void printDocumentation() { System.out.println("********************************************************************"); System.out.println("*** ViziData Dump Data Extractor V0.1"); System.out.println("***"); System.out.println("*** This program will chew on Wikidatas data and create"); System.out.println("*** the JSON files that can be feed to the ViziData web application."); System.out.println("***"); System.out.println("*** It's currently very basic and poorly written (much hardcode)"); System.out.println("*** and gets the birth and death data of all humans."); System.out.println("*** Just be patient."); System.out.println("********************************************************************"); } /** * This class handles the actual processing of EntityDocuments and * collects the information which at the end is used to build the * output files * * @author Georg Wild * */ static class ItemDataProcessor implements EntityDocumentProcessor { private static final int GEO_TILE_COUNT = 36, // number of slices for geodata grouping GEO_WMIN = -180, GEO_WMAX = 180; private static final JSONObject DEFAULT_COLOR_SCALE = new JSONObject() .put("min", new JSONArray() .put(134).put(205).put(215)) .put("max", new JSONArray() .put(0).put(0).put(0)); private int itemCount = 0; // all coordinate values HashMap<String,GlobeCoordinatesValue> coords = new HashMap<String,GlobeCoordinatesValue>(); // coordinates of items // for data gathering, should be made more dynamic at some point Set<String> humans = new HashSet<String>(); HashMap<String,String> h_placeOfBirth = new HashMap<String, String>(); HashMap<String,String> h_placeOfDeath = new HashMap<String, String>(); HashMap<String,Long> h_dateOfBirth = new HashMap<String, Long>(); HashMap<String,Long> h_dateOfDeath = new HashMap<String, Long>(); /** * TODO this function is almost completely hard coded * better approach would be to define a static configuration object * about which datagroups and datasets to build and work it all from there */ @Override public void processItemDocument(ItemDocument itemDocument) { ItemIdValue subj = itemDocument.getItemId(); // this item Value value = null; // all purpose value obj boolean is_human = false; // flag ItemIdValue birthplace = null, // place of birth deathplace = null; // place of death TimeValue birthdate = null, // date of birth deathdate = null; // date of death for (StatementGroup sg : itemDocument.getStatementGroups()) { // TARGET = humans if(sg.getProperty().getId().equals("P31")) { // instance of for(Statement s : sg.getStatements()) { if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof ItemIdValue) { if("Q5".equals(((ItemIdValue) value).getId())) { // human is_human = true; } } } } } ///// GATHER INTEL // place of birth if(sg.getProperty().getId().equals("P19")) { // place of birth for(Statement s : sg.getStatements()){ if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof ItemIdValue) { birthplace = (ItemIdValue) value; } } } } // place of death if(sg.getProperty().getId().equals("P20")) { // place of death for(Statement s : sg.getStatements()){ if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof ItemIdValue) { deathplace = (ItemIdValue) value; } } } } // date of birth if(sg.getProperty().getId().equals("P569")) { // date of birth for(Statement s : sg.getStatements()){ if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof TimeValue) { birthdate = (TimeValue) value; } } } } // date of death if(sg.getProperty().getId().equals("P570")) { // date of death for(Statement s : sg.getStatements()){ if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof TimeValue) { deathdate = (TimeValue) value; } } } } ///// general information // save coordinates if we find any if(sg.getProperty().getId().equals("P625")) { // coordinate location for(Statement s : sg.getStatements()){ if(s.getClaim().getMainSnak() instanceof ValueSnak) { value = ((ValueSnak) s.getClaim().getMainSnak()).getValue(); if(value instanceof GlobeCoordinatesValue) { coords.put(subj.getId(), (GlobeCoordinatesValue) value); /*/ GlobeCoordinatesValue v = (GlobeCoordinatesValue) value; System.out.println(v.getLatitude()); System.out.println((double)v.getLatitude());//*/ } } } } } // EXTERMINA...erm..SAVE! if(is_human) { humans.add(subj.getId()); if(birthplace != null) h_placeOfBirth.put(subj.getId(), birthplace.getId()); if(deathplace != null) h_placeOfDeath.put(subj.getId(), deathplace.getId()); if(birthdate != null) h_dateOfBirth.put(subj.getId(), birthdate.getYear()); if(deathdate != null) h_dateOfDeath.put(subj.getId(), deathdate.getYear()); } itemCount++; if(itemCount%100000 == 0) { printStatus(); } } @Override public void processPropertyDocument(PropertyDocument propertyDocument) { // ignore properties // (in fact, the above code does not even register the processor for // receiving properties) } private void printStatus() { System.out.println("processed "+itemCount+" items so far..."); System.out.println("...got "+humans.size()+" humans"); System.out.println("...got "+(h_dateOfBirth.size()+h_dateOfDeath.size())+" time values"); System.out.println("...got "+(h_placeOfBirth.size()+h_placeOfDeath.size())+" locations"); System.out.println("...(also got "+coords.size()+" location-coordinate mappings)"); System.out.println(""); } //@Override public void finishProcessingEntityDocuments() { System.out.println("*** Finished the dump!"); System.out.println("*** Let me build the files for you real quick..."); buildData(); System.out.println("*** There you go!"); } /** * TODO this should be made much more dynamic * to automate generation of various datasets * as much as possible * (still much hard code) */ private void buildData() { GlobeCoordinatesValue cv; Long tv; int geo_tile_width = (GEO_WMAX - GEO_WMIN)/GEO_TILE_COUNT; HashMap<String,Integer> propMap = new HashMap<String,Integer>(); JSONArray jp_members = new JSONArray(); HashMap<String, JSONArray> datasetdata = new HashMap<String, JSONArray>(); JSONArray jd_datasets = new JSONArray(); /// dataset config /// (note: should be moved at the top of class at some point) Integer filecount = 0; DataSet d; Collection<DataSet> sm = new ArrayList<DataSet>(); // births d = new DataSet(); d.id = "birth"; d.file = "humans_d"+String.format("%02d", filecount++)+".json"; d.geo = h_placeOfBirth; d.time = h_dateOfBirth; d.strings = new JSONObject() .put("label", "births") .put("desc", "Place and time of birth") .put("term", "were born"); d.colorScale = DEFAULT_COLOR_SCALE; sm.add(d); // deaths d = new DataSet(); d.id = "death"; d.file = "humans_d"+String.format("%02d", filecount++)+".json"; d.geo = h_placeOfDeath; d.time = h_dateOfDeath; d.strings = new JSONObject() .put("label", "deaths") .put("desc", "Place and time of death") .put("term", "have died"); d.colorScale = new JSONObject() .put("min", new JSONArray() .put(255).put(201).put(201)) .put("max", new JSONArray() .put(10).put(0).put(0)); sm.add(d); /// dataset config for(DataSet ds : sm) { double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; // create and initialize dataset array JSONArray jd = new JSONArray(); for(int i = 0; i < GEO_TILE_COUNT; i++) { jd.put(i, new JSONObject()); } for(String s : humans) { cv = coords.get(ds.geo.get(s)); tv = ds.time.get(s); if((cv != null && tv != null )// is usable for viz && (tv <=2015)) { //exclude the future for now (TODO move into dataset config) long y = tv; if(min>y) { min = y; } if(max<y) { max = y; } int tile = 0; int propI; double lon = cv.getLongitude()/(double)GlobeCoordinatesValue.PREC_DEGREE;///1000000000D; double lat = cv.getLatitude()/(double)GlobeCoordinatesValue.PREC_DEGREE;///1000000000D; while(lon > (GEO_WMIN+(tile+1)*geo_tile_width)) { tile++; } // Insert in props, if no exists if(propMap.containsKey(s)) { propI = propMap.get(s); } else { jp_members.put(new JSONArray() .put(s) // TODO put all the properties we have (currently none) ); propI = jp_members.length(); propMap.put(s, propI); } // Insert in data, check for already existing objects String key = Long.toString((y)); JSONArray geodata = new JSONArray() .put(lon).put(lat).put(propI); if(!jd.getJSONObject(tile).has(key)) { // !key exists jd.getJSONObject(tile).put(key, new JSONArray() .put(geodata) ); } else { ((JSONArray)jd.getJSONObject(tile).get(key)) .put(geodata); } /* if(!jd.has(key)) { // key no exists, create new jd.put(key, new JSONArray() .put(tile,new JSONArray() .put(new JSONArray() .put(lon).put(lat).put(propI) ) ) ); } else { // key exists JSONArray a = (JSONArray)jd.get(key); if(a.isNull(tile)) { // tile is empty a.put(tile,new JSONArray().put(new JSONArray() .put(lon).put(lat).put(propI) ) ); } else { // tile haz points ((JSONArray)a.get(tile)).put(new JSONArray() .put(lon).put(lat).put(propI)); } }*/ } } jd_datasets.put(new JSONObject() .put("id", ds.id) .put("file", ds.file) .put("min", min) .put("max", max) .put("strings", ds.strings) .put("colorScale", ds.colorScale)); datasetdata.put(ds.file, jd); } JSONObject jp = new JSONObject() // the properties file .put("properties", new JSONArray() .put("id")) .put("members", jp_members); JSONObject jm = new JSONObject() // the meta file .put("id", "humans") .put("title", "Humans") .put("label", "humans") .put("properties", "humans_p.json") .put("tile_width", geo_tile_width) //.put("tile_count", GEO_TILE_COUNT) .put("datasets", jd_datasets); writeJsonToFile("humans.json", jm); writeJsonToFile("humans_p.json", jp); for(String k : datasetdata.keySet()) { writeJsonToFile(k, datasetdata.get(k)); } return; } /** * writes given json object to file * @param filename * @param j * @return !always true */ private boolean writeJsonToFile(String filename, JSONObject j) { System.out.print("*** writing file "+filename+" to disk..."); Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8")); j.write(writer); } catch (IOException ex) { ex.printStackTrace(); } finally { try { writer.close(); System.out.println("done."); } catch (Exception ex) { ex.printStackTrace(); } } return true; } private boolean writeJsonToFile(String filename, JSONArray j) { System.out.print("*** writing file "+filename+" to disk..."); Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8")); j.write(writer); } catch (IOException ex) { ex.printStackTrace(); } finally { try { writer.close(); System.out.println("done."); } catch (Exception ex) { ex.printStackTrace(); } } return true; } } }
package data; import java.io.Serializable; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.Default; import javax.inject.Named; import org.apache.deltaspike.data.api.EntityRepository; import org.apache.deltaspike.data.api.Query; import org.apache.deltaspike.data.api.Repository; import com.darwinsys.todo.model.Task; /** * This is a basic DAO-like interface for use by JSF or EJB. * Methods are implemented for us by Apache DeltaSpike Data. * The methods in the inherited interface suffice for many apps! * @author Ian Darwin */ @Named("todoList") @Default @SessionScoped @Repository public interface TodoList extends Serializable, EntityRepository<Task, Long> { // The ordering of Priority is 0=Top..3=Lowest, so sort by prio asc is correct here @Query(value="select t from Task t where t.status < 3 order by t.priority asc, lower(t.name) asc") List<Task> findAll(); }
package mirror; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.jar.Manifest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.rvesse.airline.annotations.Cli; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.github.rvesse.airline.help.Help; import io.grpc.Channel; import io.grpc.internal.ServerImpl; import io.grpc.netty.NegotiationType; import io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.NettyServerBuilder; import mirror.Mirror.MirrorClientCommand; import mirror.Mirror.MirrorServerCommand; import mirror.MirrorGrpc.MirrorStub; import mirror.tasks.TaskFactory; import mirror.tasks.ThreadBasedTaskFactory; @Cli( name = "mirror", description = "two-way, real-time sync of files across machines", commands = { MirrorClientCommand.class, MirrorServerCommand.class }, defaultCommand = Help.class) // @Version(sources = { "/META-INF/MANIFEST.MF" }, suppressOnError = false) public class Mirror { private static final Logger log = LoggerFactory.getLogger(Mirror.class); private static final int maxMessageSize = 1073741824; // 1gb private static final int defaultPort = 49172; static { LoggingConfig.init(); } public static void main(String[] args) throws Exception { com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(Mirror.class); cli.parse(args).run(); } public static abstract class BaseArgs implements Runnable { @Option(name = "--skip-limit-checks", description = "skip system file descriptor/watches checks") public boolean skipLimitChecks; @Option(name = "--enable-log-file", description = "enables logging debug statements to mirror.log") public boolean enableLogFile; @Override public final void run() { if (enableLogFile) { LoggingConfig.enableLogFile(); } if (!skipLimitChecks && !SystemChecks.checkLimits()) { // SystemChecks will have log.error'd some output System.exit(-1); } runIfChecksOkay(); } protected abstract void runIfChecksOkay(); } @Command(name = "server", description = "starts a server for the remote client to connect to") public static class MirrorServerCommand extends BaseArgs { @Option(name = { "-p", "--post" }, description = "port to listen on, default: " + defaultPort) public int port = defaultPort; @Override protected void runIfChecksOkay() { TaskFactory taskFactory = new ThreadBasedTaskFactory(); FileWatcherFactory watcherFactory = FileWatcherFactory.newFactory(taskFactory); MirrorServer server = new MirrorServer(watcherFactory); ServerImpl rpc = NettyServerBuilder .forPort(port) .maxMessageSize(maxMessageSize) .addService(MirrorServer.withCompressionEnabled(server)) .build(); try { rpc.start(); log.info("Listening on " + port); rpc.awaitTermination(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Command(name = "client", description = "two-way real-time sync") public static class MirrorClientCommand extends BaseArgs { @Option(name = { "-h", "--host" }, description = "host name of remote server to connect to") public String host; @Option(name = { "-p", "--post" }, description = "port remote server to connect to, default: " + defaultPort) public int port = defaultPort; @Option(name = { "-l", "--local-root" }, description = "path on the local side to sync, e.g. ~/code") public String localRoot; @Option(name = { "-r", "--remote-root" }, description = "path on the remote side to sync, e.g. ~/code") public String remoteRoot; @Option(name = { "-i", "--include" }, description = "pattern of files to sync, even if they are git ignored") public List<String> extraIncludes = new ArrayList<>(); @Option(name = { "-e", "--exclude" }, description = "pattern of files to skip, in addition to what is git ignored") public List<String> extraExcludes = new ArrayList<>(); @Option(name = { "-li", "--use-internal-patterns" }, description = "use hardcoded include/excludes that generally work well for internal repos") public boolean useInternalPatterns; @Override protected void runIfChecksOkay() { try { Channel c = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.PLAINTEXT).maxMessageSize(maxMessageSize).build(); MirrorStub stub = MirrorGrpc.newStub(c).withCompression("gzip"); PathRules includes = new PathRules(); PathRules excludes = new PathRules(); setupIncludesAndExcludes(includes, excludes, extraIncludes, extraExcludes, useInternalPatterns); TaskFactory taskFactory = new ThreadBasedTaskFactory(); FileWatcherFactory watcherFactory = FileWatcherFactory.newFactory(taskFactory); MirrorClient client = new MirrorClient( Paths.get(localRoot), Paths.get(remoteRoot), includes, excludes, taskFactory, new ConnectionDetector.Impl(), watcherFactory); client.startSession(stub); // dumb way of waiting until they hit control-c CountDownLatch cl = new CountDownLatch(1); cl.await(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } public static void setupIncludesAndExcludes( PathRules includes, PathRules excludes, List<String> extraIncludes, List<String> extraExcludes, boolean useInternalPatterns) { addDefaultIncludeExcludeRules(includes, excludes); if (useInternalPatterns) { addInternalDefaults(includes, excludes); } extraIncludes.forEach(line -> includes.addRule(line)); extraExcludes.forEach(line -> excludes.addRule(line)); } private static void addDefaultIncludeExcludeRules(PathRules includes, PathRules excludes) { // IntelliJ safe write files excludes.addRule("*___jb_bak___"); excludes.addRule("*___jb_old___"); // Ignore all hidden files, e.g. especially .git/.svn directories excludes.addRule(".*"); // Since we exclude hidden files, re-include .gitignore so the remote-side knows what to ignore includes.addRule(".gitignore"); } private static void addInternalDefaults(PathRules includes, PathRules excludes) { // Maybe most of these could be dropped if svn:ignore was supported? excludes.addRules("tmp", "temp", "target", "build", "bin"); // these are resources in the build/ directory that are still useful to have // on the laptop, e.g. for the IDE includes.setRules( // include generated source code "src_managed", "**/src/mainGeneratedRest", "**/src/mainGeneratedDataTemplate", "testGeneratedRest", "testGeneratedDataTemplate", "**/build/*/classes/mainGeneratedInternalUrns/", "**/build/*/resources/mainGeneratedInternalUrns/", // sync the MP-level config directory "*/config", // but not svn directories within it "!*/config.svn", // include the binaries the laptop-side IDE will want "*-SNAPSHOT.jar", // include project files for the laptop-side IDE "*.iml", "*.ipr", "*.iws", ".classpath", ".project"); } }
package org.jdbdt; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.sql.Timestamp; import java.util.Arrays; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.function.Function; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.jdbdt.CallInfo.MethodInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * JDBDT log. * * @since 0.1 * */ final class Log implements AutoCloseable { /** * Creator method (stream variant). * @param out Output stream. * @return A new log instance. */ static Log create(PrintStream out) { return new Log(out, true); } /** * Creator method (file variant). * @param outputFile Output file. * @return A new log instance. */ static Log create(File outputFile) { try { return new Log(new PrintStream(outputFile), false); } catch (FileNotFoundException e) { throw new InvalidOperationException("File does not exist.", e); } } /** * Output stream. */ private final PrintStream out; /** * Closing behavior flag. */ private final boolean ignoreClose; /** * XML document instance. */ private final Document xmlDoc; /** * Constructor. * @param out Output stream. * @param ignoreClose If true, calls to {@link #close()} on the * created log will not close the output stream. */ private Log(PrintStream out, boolean ignoreClose) { this.out = out; this.ignoreClose = ignoreClose; this.xmlDoc = XML_DOC_FACTORY.newDocument(); } @SuppressWarnings({ "javadoc" }) private Element root(CallInfo callInfo) { Element e = createNode(null, ROOT_TAG); e.setAttribute(VERSION_TAG, JDBDT.version()); e.setAttribute(TIME_TAG, new Timestamp(System.currentTimeMillis()).toString()); write(e, callInfo); return e; } @SuppressWarnings("javadoc") private void flush(Element rootNode) { DOMSource ds = new DOMSource(rootNode); try { StreamResult sr = new StreamResult(out); XML_TRANSFORMER.transform(ds, sr); out.flush(); } catch (Exception e) { throw new InternalAPIError(e); } } /** * Close the log. * * <p> * The log should not be used after this method is called. * </p> * */ @Override public void close() { if (!ignoreClose) { out.close(); } } /** * Write a data set to the log. * @param callInfo Call info. * @param data Data set. */ void write(CallInfo callInfo, DataSet data) { Element rootNode = root(callInfo); write(rootNode, data.getSource()); Element dsNode = createNode(rootNode, DATA_SET_TAG); write(dsNode, ROWS_TAG, data.getSource().getMetaData().columns(), data.getRows().iterator()); flush(rootNode); } @SuppressWarnings("javadoc") private void write(Element parent, DataSource source) { Element node = createNode(parent, DATA_SOURCE_TAG); node.setAttribute(JAVA_TYPE_TAG, source.getClass().getName()); write(node, source.getMetaData()); writeSQL(node, source.getSQLForQuery()); } @SuppressWarnings("javadoc") private void write(Element root, CallInfo info) { Element ctxNode = createNode(root, CONTEXT_TAG); if (info.getMessage().length() > 0) { simpleNode(ctxNode, CTX_MESSAGE_TAG, info.getMessage()); } write(ctxNode, CTX_CALLER_TAG, info.getCallerMethodInfo()); write(ctxNode, CTX_API_METHOD_TAG, info.getAPIMethodInfo()); } @SuppressWarnings("javadoc") private void write (Element ctxNode, String tag, MethodInfo mi) { Element miNode = createNode(ctxNode, tag); simpleNode(miNode, CTX_CLASS_TAG, mi.getClassName()); simpleNode(miNode, CTX_METHOD_TAG, mi.getMethodName()); simpleNode(miNode, CTX_FILE_TAG, mi.getFileName()); simpleNode(miNode, CTX_LINE_TAG, String.valueOf(mi.getLineNumber())); } @SuppressWarnings("javadoc") private void write(Element parent, MetaData md) { int index = 1; Element node = createNode(parent, COLUMNS_TAG); node.setAttribute(COUNT_TAG, String.valueOf(md.getColumnCount())); for (MetaData.ColumnInfo col : md.columns()) { Element colNode = createNode(node, COLUMN_TAG); colNode.setAttribute(INDEX_TAG, String.valueOf(index++)); colNode.setAttribute(LABEL_TAG, col.label()); colNode.setAttribute(SQL_TYPE_TAG, col.type().toString()); } } /** * Log SQL code. * @param callInfo Call info. * @param sql SQL code. */ void writeSQL(CallInfo callInfo, String sql) { Element rootNode = root(callInfo); writeSQL(rootNode, sql); flush(rootNode); } @SuppressWarnings("javadoc") private void writeSQL(Element parent, String sql) { Element sqlNode = createNode(parent, SQL_TAG); sqlNode.appendChild(xmlDoc.createCDATASection(sql)); } /** * Log delta assertion. * @param callInfo Call info. * @param assertion Delta assertion. */ void write(CallInfo callInfo, DeltaAssertion assertion) { final Element rootNode = root(callInfo); final DataSource ds = assertion.getSource(); write(rootNode, ds); final Element daNode = createNode(rootNode, DELTA_ASSERTION_TAG); final List<MetaData.ColumnInfo> mdCols = ds.getMetaData().columns(); final Element expectedNode = createNode(daNode, EXPECTED_TAG); write(expectedNode, OLD_DATA_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.OLD_DATA_EXPECTED)); write(expectedNode, NEW_DATA_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.NEW_DATA_EXPECTED)); if (! assertion.passed()) { Element errorsNode = createNode(daNode, ERRORS_TAG), oldDataErrors = createNode(errorsNode, OLD_DATA_TAG), newDataErrors = createNode(errorsNode, NEW_DATA_TAG); write(oldDataErrors, EXPECTED_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_EXPECTED)); write(oldDataErrors, ACTUAL_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_ACTUAL)); write(newDataErrors, EXPECTED_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_EXPECTED)); write(newDataErrors, ACTUAL_TAG, mdCols, assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_ACTUAL)); } flush(rootNode); } /** * Log plain call information. * @param callInfo Call information. */ void writeCallInfo(CallInfo callInfo) { final Element rootNode = root(callInfo); createNode(rootNode, callInfo.getAPIMethodInfo().getMethodName()); flush(rootNode); } /** * Log state assertion. * @param callInfo Call info. * @param assertion State assertion. */ void write(CallInfo callInfo, DataSetAssertion assertion) { final Element rootNode = root(callInfo); final DataSource ds = assertion.getSource(); write(rootNode, ds); final Element saNode = createNode(rootNode, ASSERTION_TAG); final List<MetaData.ColumnInfo> mdCols = ds.getMetaData().columns(); write(saNode, EXPECTED_TAG, mdCols, assertion.data(DataSetAssertion.IteratorType.EXPECTED_DATA)); if (! assertion.passed()) { Element errorsNode = createNode(saNode, ERRORS_TAG); write(errorsNode, EXPECTED_TAG, mdCols, assertion.data(DataSetAssertion.IteratorType.ERRORS_EXPECTED)); write(errorsNode, ACTUAL_TAG, mdCols, assertion.data(DataSetAssertion.IteratorType.ERRORS_ACTUAL)); } flush(rootNode); } @SuppressWarnings("javadoc") private void write(Element parent, String tag, List<MetaData.ColumnInfo> columns, Iterator<Row> itr) { int size = 0; Element topNode = createNode(parent, tag); while (itr.hasNext()) { Row r = itr.next(); Object[] data = r.data(); Element rowElem = createNode(topNode, ROW_TAG); for (int i=0; i < data.length; i++) { Element colNode = createNode(rowElem, COLUMN_TAG); colNode.setAttribute(LABEL_TAG, columns.get(i).label()); Object cValue = data[i]; if (cValue != null) { String typeAttr, valueContent; Class<?> cClass = cValue.getClass(); if (cClass.isArray()) { typeAttr = cValue.getClass().getTypeName(); valueContent = arrayAsString(cValue, cClass.getComponentType()); } else { typeAttr = cValue.getClass().getName(); valueContent = cValue.toString(); } colNode.setAttribute(JAVA_TYPE_TAG, typeAttr); colNode.setTextContent(valueContent); } else { colNode.setTextContent(NULL_VALUE); } } size++; } topNode.setAttribute(COUNT_TAG, String.valueOf(size)); } @SuppressWarnings("javadoc") private Element createNode(Element parent, String tag) { Element node = xmlDoc.createElement(tag); if (parent != null) { parent.appendChild(node); } return node; } @SuppressWarnings("javadoc") private void simpleNode(Element parent, String tag, String value) { Element child = createNode(parent, tag); child.setTextContent(value); } @SuppressWarnings("javadoc") private String arrayAsString(Object array, Class<?> elemClass) { return elemClass.isPrimitive() ? ARRAY_STRING_FORMATTERS.get(elemClass).apply(array) : Arrays.deepToString((Object[]) array); } /** * Document builder factory handle. */ private static final DocumentBuilder XML_DOC_FACTORY; /** * Transformer handle. */ private static final Transformer XML_TRANSFORMER; @SuppressWarnings("javadoc") private static final String ROOT_TAG = "jdbdt-log-message"; @SuppressWarnings("javadoc") private static final String VERSION_TAG = "version"; @SuppressWarnings("javadoc") private static final String TIME_TAG = "time"; @SuppressWarnings("javadoc") private static final String DELTA_ASSERTION_TAG = "delta-assertion"; @SuppressWarnings("javadoc") private static final String ASSERTION_TAG = "assertion"; @SuppressWarnings("javadoc") private static final String ERRORS_TAG = "errors"; @SuppressWarnings("javadoc") private static final String EXPECTED_TAG = "expected"; @SuppressWarnings("javadoc") private static final String ACTUAL_TAG = "actual"; @SuppressWarnings("javadoc") private static final String DATA_SET_TAG = "data-set"; @SuppressWarnings("javadoc") private static final String DATA_SOURCE_TAG = "data-source"; @SuppressWarnings("javadoc") private static final String COLUMNS_TAG = "columns"; @SuppressWarnings("javadoc") private static final String OLD_DATA_TAG = "old-data"; @SuppressWarnings("javadoc") private static final String NEW_DATA_TAG = "new-data"; @SuppressWarnings("javadoc") private static final String ROWS_TAG = "rows"; @SuppressWarnings("javadoc") private static final String ROW_TAG = "row"; @SuppressWarnings("javadoc") private static final String SQL_TAG = "sql"; @SuppressWarnings("javadoc") private static final String COLUMN_TAG = "column"; @SuppressWarnings("javadoc") private static final String LABEL_TAG = "label"; @SuppressWarnings("javadoc") private static final String SQL_TYPE_TAG = "sql-type"; @SuppressWarnings("javadoc") private static final String JAVA_TYPE_TAG = "java-type"; @SuppressWarnings("javadoc") private static final String INDEX_TAG = "index"; @SuppressWarnings("javadoc") private static final String COUNT_TAG = "count"; @SuppressWarnings("javadoc") private static final String NULL_VALUE = "NULL"; @SuppressWarnings("javadoc") private static final String CONTEXT_TAG = "context"; @SuppressWarnings("javadoc") private static final String CTX_CALLER_TAG = "caller"; @SuppressWarnings("javadoc") private static final String CTX_API_METHOD_TAG = "api-method"; @SuppressWarnings("javadoc") private static final String CTX_LINE_TAG = "line"; @SuppressWarnings("javadoc") private static final String CTX_FILE_TAG = "file"; @SuppressWarnings("javadoc") private static final String CTX_CLASS_TAG = "class"; @SuppressWarnings("javadoc") private static final String CTX_MESSAGE_TAG = "message"; @SuppressWarnings("javadoc") private static final String CTX_METHOD_TAG = "method"; @SuppressWarnings("javadoc") private static final IdentityHashMap<Class<?>, Function<Object, String> > ARRAY_STRING_FORMATTERS; static { try { // XML handles XML_DOC_FACTORY = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XML_TRANSFORMER = TransformerFactory.newInstance().newTransformer(); XML_TRANSFORMER.setOutputProperty(OutputKeys.INDENT, "yes"); XML_TRANSFORMER.setOutputProperty(OutputKeys.METHOD, "xml"); XML_TRANSFORMER.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); XML_TRANSFORMER.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); XML_TRANSFORMER.setOutputProperty(OutputKeys.STANDALONE, "no"); XML_TRANSFORMER.setOutputProperty(OutputKeys.VERSION, "1.0"); XML_TRANSFORMER.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // "Array string formatters" ARRAY_STRING_FORMATTERS = new IdentityHashMap<>(); ARRAY_STRING_FORMATTERS.put(Boolean.TYPE, o -> Arrays.toString((boolean[]) o)); ARRAY_STRING_FORMATTERS.put(Byte.TYPE, o -> Misc.toHexString((byte[]) o)); ARRAY_STRING_FORMATTERS.put(Character.TYPE, o -> Arrays.toString((char[]) o)); ARRAY_STRING_FORMATTERS.put(Double.TYPE, o -> Arrays.toString((double[]) o)); ARRAY_STRING_FORMATTERS.put(Float.TYPE, o -> Arrays.toString((float[]) o)); ARRAY_STRING_FORMATTERS.put(Integer.TYPE, o -> Arrays.toString((int[]) o)); ARRAY_STRING_FORMATTERS.put(Long.TYPE, o -> Arrays.toString((long[]) o)); ARRAY_STRING_FORMATTERS.put(Short.TYPE, o -> Arrays.toString((short[]) o)); } catch (ParserConfigurationException | TransformerConfigurationException | TransformerFactoryConfigurationError e) { throw new InternalAPIError(e); } } }
package jade.core; import jade.util.leap.Serializable; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import jade.util.leap.Iterator; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; import jade.util.leap.ArrayList; import java.util.Vector; import jade.core.behaviours.Behaviour; import jade.lang.Codec; import jade.lang.acl.*; import jade.onto.Frame; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.domain.AMSService; // Concepts from fipa-agent-management ontology import jade.domain.FIPAAgentManagement.AMSAgentDescription; import jade.domain.FIPAException; import jade.content.ContentManager; /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable { private final static short UNPROTECTMYPOINTER = 0; /** @serial */ // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } private static class AgentInMotionError extends Error { AgentInMotionError() { super("Agent " + Thread.currentThread().getName() + " is about to move or be cloned."); } } // This class manages bidirectional associations between Timer and // Behaviour objects, using hash tables. This class is fully // synchronized because is accessed both by agent internal thread // and high priority Timer Dispatcher thread. private static class AssociationTB { private Map BtoT = new HashMap(); private Map TtoB = new HashMap(); public synchronized void addPair(Behaviour b, Timer t) { BtoT.put(b, t); TtoB.put(t, b); } public synchronized void removeMapping(Behaviour b) { Timer t = (Timer)BtoT.remove(b); if(t != null) { TtoB.remove(t); } } public synchronized void removeMapping(Timer t) { Behaviour b = (Behaviour)TtoB.remove(t); if(b != null) { BtoT.remove(b); } } public synchronized Timer getPeer(Behaviour b) { return (Timer)BtoT.get(b); } public synchronized Behaviour getPeer(Timer t) { return (Behaviour)TtoB.get(t); } public synchronized Iterator timers() { return TtoB.keySet().iterator(); } } /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if(millis == 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); pendingTimers.addPair(b, t); theDispatcher.add(t); } // Restarts the behaviour associated with t. This method runs within // the time-critical Timer Dispatcher thread. void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { b.restart(); } } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); theDispatcher.remove(t); } // Did this restart() cause the root behaviour to become runnable ? // If so, put the root behaviour back into the ready queue. Behaviour root = b.root(); if(root.isRunnable()) myScheduler.restart(root); } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>idle</em> agent state. */ public static final int AP_IDLE = 3; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 4; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 5; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 6; /** Represents the <code>transit</code> agent state. */ public static final int AP_TRANSIT = 7; // Non compliant states, used internally. Maybe report to FIPA... /** Represents the <code>copy</code> agent state. */ static final int AP_COPY = 8; /** Represents the <code>gone</code> agent state. This is the state the original instance of an agent goes into when a migration transaction successfully commits. */ static final int AP_GONE = 9; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 10; // Hand-made type checking private static final AgentState[] STATES = new AgentState[] { new AgentState("Illegal MIN state"), new AgentState("Initiated"), new AgentState("Active"), new AgentState("Idle"), new AgentState("Suspended"), new AgentState("Waiting"), new AgentState("Deleted"), new AgentState("Transit"), new AgentState("Copy"), new AgentState("Gone"), new AgentState("Illegal MAX state") }; /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking /** Default value for message queue size. When the number of buffered messages exceeds this value, older messages are discarded according to a <b><em>FIFO</em></b> replacement policy. @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getQueueSize() */ public static final int MSG_QUEUE_SIZE = 100; /** The Agent ID for the AMS of this platform. */ static AID AMS; /** The Agent ID for the Default DF of this platform. */ static AID DEFAULT_DF; /** Get the Agent ID for the platform AMS. @return An <code>AID</code> object, that can be used to contact the AMS of this platform. */ public static final AID getAMS() { return AMS; } /** Get the Agent ID for the platform default DF. @return An <code>AID</code> object, that can be used to contact the default DF of this platform. */ public static final AID getDefaultDF() { return DEFAULT_DF; } private int msgQueueMaxSize = MSG_QUEUE_SIZE; private transient MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE); private transient AgentToolkit myToolkit; /** @serial */ private String myName = null; /** @serial */ private AID myAID = null; /** @serial */ private String myHap = null; private transient Object stateLock = new Object(); // Used to make state transitions atomic private transient Object waitLock = new Object(); // Used for agent waiting private transient Object suspendLock = new Object(); // Used for agent suspension private transient Thread myThread; private transient TimerDispatcher theDispatcher; /** @serial */ private Scheduler myScheduler; private transient AssociationTB pendingTimers = new AssociationTB(); // Free running counter that increments by one for each message // received. /** @serial */ private int messageCounter = 0 ; // Individual agent capabilities private transient Map languages = new HashMap(); private transient Map ontologies = new HashMap(); /** The <code>Behaviour</code> that is currently executing. @see jade.core.behaviours.Behaviour @serial */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage @serial */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. /** @serial */ private volatile int myAPState; /** This flag is used to distinguish the normal AP_ACTIVE state from the particular case in which the agent state is set to AP_ACTIVE during agent termination to allow it to deregister with the AMS. In this case in fact a call to <code>doDelete()</code>, <code>doMove()</code>, <code>doClone()</code> and <code>doSuspend()</code> should have no effect. */ private boolean terminating = false; // These two variables are used as temporary buffers for // mobility-related parameters private transient Location myDestination; private transient String myNewName; // Temporary buffer for agent suspension /** @serial */ private int myBufferedState = AP_MIN; /** Default constructor. */ public Agent() { setState(AP_INITIATED); myScheduler = new Scheduler(this); Runtime rt = Runtime.instance(); theDispatcher = rt.getTimerDispatcher(); } /** * This method must be overridden by programmers in order to pass * arguments to the agent. * Otherwise, to pass argument to the agent by command line or using the RMA GUI * see the programmer's guide for a better documentation. * * @param args an array of string (as passed on the command line - Unix-like syntax). * @deprecated use the method <code>getArguments</code> instead */ public void setArguments(String args[]) {} private transient Object[] arguments = null; // array of arguments /** * Called by AgentContainerImpl in order to pass arguments to a * just created Agent. **/ public final void setArguments(Object args[]) { // I have declared the method final otherwise getArguments would not work! arguments=args; if (arguments != null) { //FIXME. This code goes away with the depcreated setArguments(String[]) method String sargs[] = new String[args.length]; for (int i=0; i<args.length; i++) sargs[i]=args[i].toString(); setArguments(sargs); } } /** * Return the array of arguments as they were set by the previous * call of the method <code>setArguments</code>. * <p> Take care that the arguments are transient and they do not * migrate with the agent neither are cloned with the agent! **/ protected Object[] getArguments() { return arguments; } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public final String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@fipa.org:50</em>). */ public final String getName() { return myName + '@' + myHap; } /** Method to query the private Agent ID. Note that this Agent ID is <b>different</b> from the one that is registered with the platform AMS. @return An <code>Agent ID</code> object, containing the complete agent GUID, addresses and resolvers. */ public final AID getAID() { return myAID; } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public final String getHap() { return myHap; } /** Method to retrieve the location this agent is currently at. @return A <code>Location</code> object, describing the location where this agent is currently running. */ public Location here() { return myToolkit.here(); } static void initReservedAIDs(AID amsID, AID defaultDfID) { AMS = amsID; DEFAULT_DF = defaultDfID; } /** Adds a Content Language codec to the agent capabilities. When an agent wants to provide automatic support for a specific content language, it must use an implementation of the <code>Codec</code> interface for the specific content language, and add it to its languages table with this method. @param languageName The symbolic name to use for the language. @param translator A translator for the specific content language, able to translate back and forth between text strings and Frame objects. @see jade.core.Agent#deregisterLanguage(String languageName) @see jade.lang.Codec */ public void registerLanguage(String languageName, Codec translator) { languages.put(new CaseInsensitiveString(languageName), translator); } /** Looks a content language up into the supported languages table. @param languageName The name of the desired content language. @return The translator for the given language, or <code>null</code> if no translator was found. */ public Codec lookupLanguage(String languageName) { Codec result = (Codec)languages.get(new CaseInsensitiveString(languageName)); return result; } /** Removes a Content Language from the agent capabilities. @param languageName The name of the language to remove. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) */ public void deregisterLanguage(String languageName) { languages.remove(new CaseInsensitiveString(languageName)); } /** Adds an Ontology to the agent capabilities. When an agent wants to provide automatic support for a specific ontology, it must use an implementation of the <code>Ontology</code> interface for the specific ontology and add it to its ontologies table with this method. @param ontologyName The symbolic name to use for the ontology @param o An ontology object, that is able to convert back and forth between Frame objects and application specific Java objects representing concepts. @see jade.core.Agent#deregisterOntology(String ontologyName) @see jade.onto.Ontology */ public void registerOntology(String ontologyName, Ontology o) { ontologies.put(new CaseInsensitiveString(ontologyName), o); } /** Looks an ontology up into the supported ontologies table. @param ontologyName The name of the desired ontology. @return The given ontology, or <code>null</code> if no such named ontology was found. */ public Ontology lookupOntology(String ontologyName) { Ontology result = (Ontology)ontologies.get(new CaseInsensitiveString(ontologyName)); return result; } /** Removes an Ontology from the agent capabilities. @param ontologyName The name of the ontology to remove. @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) */ public void deregisterOntology(String ontologyName) { ontologies.remove(new CaseInsensitiveString(ontologyName)); } //__BACKWARD_COMPATIBILITY__BEGIN /** Builds a Java object out of an ACL message. This method uses the <code>:language</code> slot to select a content language and the <code>:ontology</code> slot to select an ontology. Then the <code>:content</code> slot is interpreted according to the chosen language and ontology, to build an object of a user defined class. @param msg The ACL message from which a suitable Java object will be built. @return A new list of Java objects, each object representing an element of the t-uple of the the message content in the given content language and ontology. @exception jade.domain.FIPAException If some problem related to the content language or to the ontology is detected. @see jade.core.Agent#registerLanguage(String languageName, Codec translator) @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) @see jade.core.Agent#fillContent(ACLMessage msg, List content) @deprecated Use the new support for content Language and ontologies instead */ public java.util.List extractContent(ACLMessage msg) throws FIPAException { ArrayList l = (ArrayList) extractContent2(msg); return l.toList(); } /** Fills the <code>:content</code> slot of an ACL message with the string representation of a t-uple of user defined ontological objects. Each Java object in the given list is first converted into a <code>Frame</code> object according to the ontology present in the <code>:ontology</code> message slot, then the <code>Frame</code> is translated into a <code>String</code> using the codec for the content language indicated by the <code>:language</code> message slot. <p> Notice that this method works properly only if in the Ontology each Java class has been registered to play just one role, otherwise ambiguity of role playing cannot be solved automatically. @param msg The ACL message whose content will be filled. @param content A list of Java objects that will be converted into a string and written inti the <code>:content</code> slot. This object must be an instance of a class registered into the ontology named in the <code>:ontology</code> message slot. @exception jade.domain.FIPAException This exception is thrown if the <code>:language</code> or <code>:ontology</code> message slots contain an unknown name, or if some problem occurs during the various translation steps. @see jade.core.Agent#extractContent(ACLMessage msg) @see jade.core.Agent#registerLanguage(String languageName, Codec translator) @see jade.core.Agent#registerOntology(String ontologyName, Ontology o) @deprecated Use the new support for content Language and ontologies instead */ public void fillContent(ACLMessage msg, java.util.List content) throws FIPAException { ArrayList l = new ArrayList(); l.fromList(content); fillContent2(msg, l); } //__BACKWARD_COMPATIBILITY__END /** This is a temporary hack that is used internally by the framework until the new content language and ontology support will be fully integrated. Do not use this method. Use the new support for content Language and ontologies instead */ public List extractContent2(ACLMessage msg) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { List tuple = c.decode(msg.getContent(), o); return o.createObject(tuple); } catch(Codec.CodecException cce) { cce.getNested().printStackTrace(); throw new FIPAException("Codec error: " + cce.getMessage()); } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } /** This is a temporary hack that is used internally by the framework until the new content language and ontology support will be fully integrated. Do not use this method. Use the new support for content Language and ontologies instead */ public void fillContent2(ACLMessage msg, List content) throws FIPAException { Codec c = lookupLanguage(msg.getLanguage()); if(c == null) throw new FIPAException("Unknown Content Language"); Ontology o = lookupOntology(msg.getOntology()); if(o == null) throw new FIPAException("Unknown Ontology"); try { List l = new ArrayList(); Frame f; for (int i=0; i<content.size(); i++) { f = o.createFrame(content.get(i), o.getRoleName(content.get(i).getClass())); l.add(f); } String s = c.encode(l, o); msg.setContent(s); } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } } // This is used by the agent container to wait for agent termination void join() { try { myThread.join(); } catch(InterruptedException ie) { ie.printStackTrace(); } } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue. @see jade.core.Agent#setQueueSize(int newSize) */ public int getQueueSize() { return msgQueue.getMaxSize(); } private void setState(int state) { synchronized(stateLock) { int oldState = myAPState; myAPState = state; notifyChangedAgentState(oldState, myAPState); } } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { int state; synchronized(stateLock) { state = myAPState; } return state; } AgentState getAgentState() { return STATES[getState()]; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and this method should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. <b> It is highly descouraged the usage of this method </b> because it does not guarantee agent autonomy; soon this policy will be enfored by removing or restricting the scope of the method @param name The local name of the agent. */ public void doStart(String name) { // FIXME: Temporary hack for JSP example if(myToolkit == null) { Runtime rt = Runtime.instance(); setToolkit(rt.getDefaultToolkit()); theDispatcher = rt.getTimerDispatcher(); } if(myToolkit == null) throw new InternalError("Trying to start an agent without proper runtime support."); myToolkit.handleStart(name, this); } /** Make a state transition from <em>active</em> to <em>transit</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a migration process. @param destination The <code>Location</code> to migrate to. */ public void doMove(Location destination) { synchronized(stateLock) { if(((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE)) && !terminating) { myBufferedState = myAPState; setState(AP_TRANSIT); myDestination = destination; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>active</em> to <em>copy</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a clonation process. @param destination The <code>Location</code> where the copy agent will start. @param newName The name that will be given to the copy agent. */ public void doClone(Location destination, String newName) { synchronized(stateLock) { if(((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE)) && !terminating) { myBufferedState = myAPState; setState(AP_COPY); myDestination = destination; myNewName = newName; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>transit</em> or <code>copy</code> to <em>active</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called by the destination Agent Platform when a migration process completes and the mobile agent is about to be restarted on its new location. */ void doExecute() { synchronized(stateLock) { // FIXME: Hack to manage agents moving while in AP_IDLE state, // but with pending timers. The correct solution would be to // restore all pending timers. if(myBufferedState == AP_IDLE) myBufferedState = AP_ACTIVE; setState(myBufferedState); myBufferedState = AP_MIN; activateAllBehaviours(); } } /** Make a state transition from <em>transit</em> to <em>gone</em> state. This state is only used to label the original copy of a mobile agent which migrated somewhere. */ void doGone() { synchronized(stateLock) { setState(AP_GONE); } } /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE) && !terminating) { myBufferedState = myAPState; setState(AP_SUSPENDED); } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { setState(myBufferedState); } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notifyAll(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) setState(AP_WAITING); } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if((myAPState == AP_WAITING) || (myAPState == AP_IDLE)) { setState(AP_ACTIVE); } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(waitLock) { waitLock.notifyAll(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { synchronized(stateLock) { if(myAPState != AP_DELETED && !terminating) { setState(AP_DELETED); if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } // This is to be called only by the scheduler void doIdle() { synchronized(stateLock) { if(myAPState != AP_IDLE) setState(AP_IDLE); } } /** Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection. Of course, the whole agent must be serializable in order to be written successfully. @param s The stream this agent will be sent to. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during writing. @see jade.core.Agent#read(InputStream s) */ public void write(OutputStream s) throws IOException { ObjectOutput out = new ObjectOutputStream(s); out.writeUTF(myName); out.writeObject(this); } /** Read a previously saved agent from an input stream and restarts it under its former name. This method can realize some sort of mobility through time, where an agent is saved, then destroyed and then restarted from the saved copy. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(name); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** Read a previously saved agent from an input stream and restarts it under a different name. This method can realize agent cloning through streams, where an agent is saved, then an exact copy of it is restarted as a completely separated agent, with the same state but with different identity and address. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @param agentName The name of the new agent, copy of the saved original one. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s, String agentName) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(agentName); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. The stream must contain the saved state of <b>the same agent</b> that it is trying to restore itself; that is, <em>both</em> the Java object <em>and</em> the agent name must be the same. @param s The input stream the agent state will be read from. @exception IOException Thrown if some I/O error occurs during stream reading. <em>Note: This method is currently not implemented</em> */ public void restore(InputStream s) throws IOException { // FIXME: Not implemented } /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try { AMSAgentDescription amsd = new AMSAgentDescription(); amsd.setName(myAID); amsd.setOwnership("JADE"); amsd.setState(AMSAgentDescription.ACTIVE); switch(myAPState) { case AP_INITIATED: setState(AP_ACTIVE); // No 'break' statement - fall through case AP_ACTIVE: if (myAID.equals(getAMS())) //special version for the AMS to avoid deadlock ((jade.domain.ams)this).AMSRegister(amsd); else AMSService.register(this,amsd); notifyStarted(); setup(); break; case AP_TRANSIT: doExecute(); afterMove(); break; case AP_COPY: doExecute(); if (myAID.equals(getAMS())) //special version for the AMS to avoid deadlock ((jade.domain.ams)this).AMSRegister(amsd); else AMSService.register(this,amsd); afterClone(); break; } mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { switch(myAPState) { case AP_DELETED: terminating = true; int savedState = getState(); setState(AP_ACTIVE); takeDown(); destroy(); setState(savedState); break; case AP_GONE: break; default: terminating = true; System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!"); System.out.println("State was " + myAPState); savedState = getState(); setState(AP_ACTIVE); takeDown(); destroy(); setState(savedState); } } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.behaviours.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} /** Actions to perform before moving. This empty placeholder method can be overridden by user defined agents to execute some actions just before leaving an agent container for a migration. */ protected void beforeMove() {} /** Actions to perform after moving. This empty placeholder method can be overridden by user defined agents to execute some actions just after arriving to the destination agent container for a migration. */ protected void afterMove() {} /** Actions to perform before cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just before copying an agent to another agent container. */ protected void beforeClone() {} /** Actions to perform after cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just after creating an agent copy to the destination agent container. */ protected void afterClone() {} // This method is used by the Agent Container to fire up a new agent for the first time void powerUp(AID id, ResourceManager rm) { // Set this agent's name and address and start its embedded thread if((myAPState == AP_INITIATED)||(myAPState == AP_TRANSIT)||(myAPState == AP_COPY)) { myName = id.getLocalName(); myHap = id.getHap(); myAID = id; //myThread = new Thread(myGroup, this); myThread = rm.getThread(ResourceManager.USER_AGENTS, getLocalName(), this); //myThread.setName(getLocalName()); //myThread.setPriority(myGroup.getMaxPriority()); myThread.start(); } } private void writeObject(ObjectOutputStream out) throws IOException { // Updates the queue maximum size field, before serialising msgQueueMaxSize = msgQueue.getMaxSize(); out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Restore transient fields (apart from myThread, which will be set by doStart()) msgQueue = new MessageQueue(msgQueueMaxSize); stateLock = new Object(); suspendLock = new Object(); waitLock = new Object(); pendingTimers = new AssociationTB(); languages = new HashMap(); ontologies = new HashMap(); theDispatcher = Runtime.instance().getTimerDispatcher(); } private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { try { // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; case AP_TRANSIT: notifyMove(); if(myAPState == AP_GONE) { beforeMove(); return; } break; case AP_COPY: beforeClone(); notifyCopy(); doExecute(); break; case AP_ACTIVE: try { // Select the next behaviour to execute int oldState = myAPState; currentBehaviour = myScheduler.schedule(); if(myAPState != oldState) setState(oldState); } // Someone interrupted the agent. It could be a kill or a // move/clone request... catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); case AP_ACTIVE: System.out.println("WARNING: Spurious wakeup for agent " + getLocalName()); } } // Remember how many messages arrived int oldMsgCounter = messageCounter; // Just do it! currentBehaviour.actionWrapper(); // If the current Behaviour is blocked and more messages // arrived, restart the behaviour to give it another chance if((oldMsgCounter != messageCounter) && (!currentBehaviour.isRunnable())) currentBehaviour.restart(); // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { currentBehaviour.onEnd(); myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviour from ready behaviours queue // and put it in blocked behaviours queue myScheduler.block(currentBehaviour); currentBehaviour = null; } break; } // Now give CPU control to other agents Thread.yield(); } catch(AgentInMotionError aime) { // Do nothing, since this is a doMove() or doClone() from the outside. } } } private void waitUntilWake(long millis) { synchronized(waitLock) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while long elapsedTime = System.currentTimeMillis() - startTime; // If this was a timed wait, update time to wait; if the // total time has passed, wake up. if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) setState(AP_ACTIVE); } } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); } } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { suspendLock.wait(); // Blocks on suspended state monitor } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); case AP_TRANSIT: case AP_COPY: // Undo the previous clone or move request setState(AP_SUSPENDED); } } } } } private void destroy() { try { if (myAID.equals(getAMS())) { //special version for the AMS to avoid deadlock AMSAgentDescription amsd = new AMSAgentDescription(); amsd.setName(getAID()); ((jade.domain.ams)this).AMSDeregister(amsd); } else AMSService.deregister(this); } catch(FIPAException fe) { fe.printStackTrace(); } // Remove all pending timers Iterator it = pendingTimers.timers(); while(it.hasNext()) { Timer t = (Timer)it.next(); theDispatcher.remove(t); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.behaviours.Behaviour */ public void addBehaviour(Behaviour b) { b.setAgent(this); myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.behaviours.Behaviour */ public void removeBehaviour(Behaviour b) { b.setAgent(null); myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { try { if(msg.getSender().getName().length() < 1) msg.setSender(myAID); } catch (NullPointerException e) { msg.setSender(myAID); } notifySend(msg); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { synchronized(waitLock) { if(msgQueue.isEmpty()) { return null; } else { currentMessage = msgQueue.removeFirst(); notifyReceived(currentMessage); return currentMessage; } } } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized(waitLock) { Iterator messages = msgQueue.iterator(); while(messages.hasNext()) { ACLMessage cursor = (ACLMessage)messages.next(); if(pattern.match(cursor)) { msg = cursor; msgQueue.remove(cursor); currentMessage = cursor; notifyReceived(msg); break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { synchronized(waitLock) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = null; synchronized(waitLock) { msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); doWait(timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; msg = receive(pattern); if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) break; } } } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(waitLock) { msgQueue.addFirst(msg); } } final void setToolkit(AgentToolkit at) { myToolkit = at; } final void resetToolkit() { myToolkit = null; } /** This method blocks until the agent has finished its start-up phase (i.e. until just before its setup() method is called. When this method returns, the target agent is registered with the AMS and the JADE platform is aware of it. */ public synchronized void waitUntilStarted() { while(getState() == AP_INITIATED) { try { wait(); } catch(InterruptedException ie) { // Do nothing... } } } // Event firing methods // Notify creator that the start-up phase has completed private synchronized void notifyStarted() { notifyAll(); } // Notify toolkit that a message was posted in the message queue private void notifyPosted(ACLMessage msg) { myToolkit.handlePosted(myAID, msg); } // Notify toolkit that a message was extracted from the message // queue private void notifyReceived(ACLMessage msg) { myToolkit.handleReceived(myAID, msg); } // Notify toolkit of the need to send a message private void notifySend(ACLMessage msg) { myToolkit.handleSend(msg); } // Notify toolkit of the destruction of the current agent private void notifyDestruction() { myToolkit.handleEnd(myAID); } // Notify toolkit of the need to move the current agent private void notifyMove() { myToolkit.handleMove(myAID, myDestination); } // Notify toolkit of the need to copy the current agent private void notifyCopy() { myToolkit.handleClone(myAID, myDestination, myNewName); } // Notify toolkit that the current agent has changed its state private void notifyChangedAgentState(int oldState, int newState) { AgentState from = STATES[oldState]; AgentState to = STATES[newState]; if(myToolkit != null) myToolkit.handleChangedAgentState(myAID, from, to); } private void activateAllBehaviours() { myScheduler.restartAll(); } /** Put a received message into the agent message queue. The message is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage (ACLMessage msg) { synchronized(waitLock) { /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock taken in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); f.write(msg.toString()); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ if(msg != null) { msgQueue.addLast(msg); notifyPosted(msg); } doWake(); messageCounter++; } /* try { java.io.FileWriter f = new java.io.FileWriter("logs/" + getLocalName(), true); f.write("waitLock dropped in postMessage() [thread " + Thread.currentThread().getName() + "]\n"); f.close(); } catch(java.io.IOException ioe) { System.out.println(ioe.getMessage()); } */ } Iterator messages() { return msgQueue.iterator(); } private ContentManager theContentManager = new ContentManager(); /** * Retrieves the content manager * * @return The content manager. */ public ContentManager getContentManager() { return theContentManager; } }
package jade.core; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Serializable; import java.util.Date; import java.util.Enumeration; import java.util.Vector; import jade.lang.acl.*; import jade.domain.AgentManagementOntology; import jade.domain.FipaRequestClientBehaviour; import jade.domain.FIPAException; public class Agent implements Runnable, Serializable, CommBroadcaster { // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } // Agent Platform Life-Cycle states public static final int AP_MIN = -1; // Hand-made type checking public static final int AP_INITIATED = 1; public static final int AP_ACTIVE = 2; public static final int AP_SUSPENDED = 3; public static final int AP_WAITING = 4; public static final int AP_DELETED = 5; public static final int AP_MAX = 6; // Hand-made type checking // Domain Life-Cycle states public static final int D_MIN = 9; // Hand-made type checking public static final int D_ACTIVE = 10; public static final int D_SUSPENDED = 20; public static final int D_RETIRED = 30; public static final int D_UNKNOWN = 40; public static final int D_MAX = 41; // Hand-made type checking protected Vector msgQueue = new Vector(); protected Vector listeners = new Vector(); protected String myName = null; protected String myAddress = null; protected Thread myThread; protected Scheduler myScheduler; protected Behaviour currentBehaviour; protected ACLMessage currentMessage; private int myAPState; private int myDomainState; private Vector blockedBehaviours = new Vector(); protected ACLParser myParser = ACLParser.create(); public Agent() { myAPState = AP_INITIATED; myDomainState = D_UNKNOWN; myThread = new Thread(this); myScheduler = new Scheduler(this); } public String getName() { return myName; } public String getAddress() { return myAddress; } // This is used by the agent container to wait for agent termination void join() { try { // FIXME: Some deadlock problems, since thread.interrupt() does not seem to work doWake(); myThread.join(500); // Wait at most 500 milliseconds } catch(InterruptedException ie) { ie.printStackTrace(); } } // State transition methods for Agent Platform Life-Cycle public void doStart(String name, String platformAddress) { // Transition from Initiated to Active // Set this agent's name and address and start its embedded thread myName = new String(name); myAddress = new String(platformAddress); myThread.setName(myName); myThread.start(); } public void doMove() { // Transition from Active to Initiated myAPState = AP_INITIATED; // FIXME: Should do something more } public void doSuspend() { // Transition from Active to Suspended myAPState = AP_SUSPENDED; // FIXME: Should do something more } public void doActivate() { // Transition from Suspended to Active myAPState = AP_ACTIVE; // FIXME: Should do something more } public synchronized void doWait() { // Transition from Active to Waiting myAPState = AP_WAITING; while(myAPState == AP_WAITING) { try { wait(); // Blocks on its monitor } catch(InterruptedException ie) { myAPState = AP_DELETED; throw new AgentDeathError(); } } } public synchronized void doWake() { // Transition from Waiting to Active myAPState = AP_ACTIVE; activateAllBehaviours(); notify(); // Wakes up the embedded thread } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. public void doDelete() { // Transition to destroy the agent myAPState = AP_DELETED; if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } public final void run() { try{ registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); setup(); mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { takeDown(); destroy(); } } protected void setup() {} protected void takeDown() {} private void mainLoop() throws InterruptedException { while(myAPState != AP_DELETED) { // Select the next behaviour to execute currentBehaviour = myScheduler.schedule(); // Just do it! currentBehaviour.action(); if(myAPState == AP_DELETED) return; // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviours from scheduling queue and put it // in blocked behaviours queue myScheduler.remove(currentBehaviour); blockedBehaviours.addElement(currentBehaviour); currentBehaviour = null; } // Now give CPU control to other agents Thread.yield(); } } private void destroy() { try { deregisterWithAMS(); } catch(FIPAException fe) { fe.printStackTrace(); } notifyDestruction(); } public void addBehaviour(Behaviour b) { myScheduler.add(b); } public void removeBehaviour(Behaviour b) { myScheduler.remove(b); } // Event based message sending -- unicast public final void send(ACLMessage msg) { CommEvent event = new CommEvent(this, msg); broadcastEvent(event); } // Event based message sending -- multicast public final void send(ACLMessage msg, AgentGroup g) { CommEvent event = new CommEvent(this, msg, g); broadcastEvent(event); } // Non-blocking receive public final synchronized ACLMessage receive() { if(msgQueue.isEmpty()) { return null; } else { ACLMessage msg = (ACLMessage)msgQueue.firstElement(); currentMessage = msg; msgQueue.removeElementAt(0); return msg; } } // Non-blocking receive with pattern matching on messages public final synchronized ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; Enumeration messages = msgQueue.elements(); while(messages.hasMoreElements()) { ACLMessage cursor = (ACLMessage)messages.nextElement(); if(pattern.match(cursor)) { msg = cursor; currentMessage = cursor; msgQueue.removeElement(cursor); break; // Exit while loop } } return msg; } // Blocking receive public final synchronized ACLMessage blockingReceive() { ACLMessage msg = receive(); while(msg == null) { doWait(); msg = receive(); } return msg; } // Blocking receive with pattern matching on messages public final synchronized ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = receive(pattern); while(msg == null) { doWait(); msg = receive(pattern); } return msg; } // Put a received message back in message queue public final synchronized void putBack(ACLMessage msg) { msgQueue.insertElementAt(msg,0); } /** @deprecated Builds an ACL message from a character stream. Now ACLMessage class has this capabilities itself, through fromText() method. @see ACLMessage */ public ACLMessage parse(Reader text) { ACLMessage msg = null; try { msg = myParser.parse(text); } catch(ParseException pe) { pe.printStackTrace(); } catch(TokenMgrError tme) { tme.printStackTrace(); } return msg; } private ACLMessage FipaRequestMessage(String dest, String replyString) { ACLMessage request = new ACLMessage("request"); request.setSource(myName); request.setDest(dest); request.setLanguage("SL0"); request.setOntology("fipa-agent-management"); request.setProtocol("fipa-request"); request.setReplyWith(replyString); return request; } private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException { send(request); ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getType().equalsIgnoreCase("agree")) { reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(!reply.getType().equalsIgnoreCase("inform")) { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } else { String content = reply.getContent(); return content; } } else { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } } // FIXME: Temporary hack; should find a better solution... private void doFipaRequestClientNB(ACLMessage request, String replyString) throws FIPAException { MessageTemplate template = MessageTemplate.MatchReplyTo(replyString); addBehaviour(new FipaRequestClientBehaviour(this, request, template) { protected void handleNotUnderstood(ACLMessage reply) { // Do nothing } protected void handleRefuse(ACLMessage reply) { // Do nothing } protected void handleAgree(ACLMessage reply) { // Do nothing } protected void handleFailure(ACLMessage reply) { // Do Nothing } protected void handleInform(ACLMessage reply) { // Do nothing } }); } // Register yourself with platform AMS public void registerWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-registration-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(myName + "@" + myAddress); amsd.setAddress(myAddress); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } // Authenticate yourself with platform AMS public void authenticateWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { // FIXME: Not implemented } // Deregister yourself with platform AMS public void deregisterWithAMS() throws FIPAException { String replyString = myName + "-ams-deregistration-" + (new Date()).getTime(); // Get a semi-complete request message ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(myName + "@" + myAddress); a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } // Modify your registration with platform AMS public void modifyAMSRegistration(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(myName + "@" + myAddress); amsd.setAddress(myAddress); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } public void forwardWithACC(ACLMessage msg) throws FIPAException { String replyString = myName + "-acc-forward-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("acc", replyString); // Build an ACC action object for the request AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction(); a.setName(AgentManagementOntology.ACCAction.FORWARD); a.setArg(msg); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } // Register yourself with a DF public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-register-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.REGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply, in a separate Behaviour doFipaRequestClientNB(request, replyString); } // Deregister yourself with a DF public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-deregister-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.DEREGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClientNB(request, replyString); } // Modify registration data with a DF public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.MODIFY); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClientNB(request, replyString); } // Search a DF for information public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException { String replyString = myName + "-df-search-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction(); a.setName(AgentManagementOntology.DFAction.SEARCH); a.setActor(dfName); a.setArg(dfd); if(constraints == null) { AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint(); c.setName(AgentManagementOntology.Constraint.DFDEPTH); c.setFn(AgentManagementOntology.Constraint.EXACTLY); c.setArg(1); a.addConstraint(c); } else { // Put constraints into action Enumeration e = constraints.elements(); while(e.hasMoreElements()) { AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)e.nextElement(); a.addConstraint(c); } } // Convert it to a String and write it in content field of the request StringWriter textOut = new StringWriter(); a.toText(textOut); request.setContent(textOut.toString()); // Send message and collect reply String content = doFipaRequestClient(request, replyString); // Extract agent descriptors from reply message AgentManagementOntology.DFSearchResult found = null; StringReader textIn = new StringReader(content); try { found = AgentManagementOntology.DFSearchResult.fromText(textIn); } catch(jade.domain.ParseException jdpe) { jdpe.printStackTrace(); } catch(jade.domain.TokenMgrError jdtme) { jdtme.printStackTrace(); } return found; } // Event handling methods // Broadcast communication event to registered listeners private void broadcastEvent(CommEvent event) { Enumeration e = listeners.elements(); while(e.hasMoreElements()) { CommListener l = (CommListener)e.nextElement(); l.CommHandle(event); } } // Register a new listener public final void addCommListener(CommListener l) { listeners.addElement(l); } // Remove a registered listener public final void removeCommListener(CommListener l) { listeners.removeElement(l); } // Notify listeners of the destruction of the current agent private void notifyDestruction() { Enumeration e = listeners.elements(); while(e.hasMoreElements()) { CommListener l = (CommListener)e.nextElement(); l.endSource(myName); } } private void activateAllBehaviours() { // Put all blocked behaviours back in ready queue while(!blockedBehaviours.isEmpty()) { Behaviour b = (Behaviour)blockedBehaviours.lastElement(); blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1); b.restart(); myScheduler.add(b); } } // Put an incoming message in agent's message queue and activate all // blocking behaviours waiting for a message public final synchronized void postMessage (ACLMessage msg) { if(msg != null) msgQueue.addElement(msg); doWake(); } }
package xal.app.bpmviewer; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.net.*; import xal.extension.application.*; import xal.extension.smf.application.AcceleratorApplication; /** * BpmViewerMain is a concrete subclass of ApplicationAdaptor for the bpmViewer * application. * *@author shishlo *@version July 12, 2004 */ public class BpmViewerMain extends ApplicationAdaptor { /** * Constructor */ public BpmViewerMain() { } /** * Returns the text file suffixes of files this application can open. * *@return Suffixes of readable files */ public String[] readableDocumentTypes() { return new String[]{"bpm"}; } /** * Returns the text file suffixes of files this application can write. * *@return Suffixes of writable files */ public String[] writableDocumentTypes() { return new String[]{"bpm"}; } /** * Returns an instance of the bpmViewer application document. * *@return An instance of bpmViewer application document. */ public XalDocument newEmptyDocument() { return new BpmViewerDocument(); } /** * Returns an instance of the bpmViewer application document corresponding * to the specified URL. * *@param url The URL of the file to open. *@return An instance of an bpmViewer application document. */ public XalDocument newDocument(java.net.URL url) { return new BpmViewerDocument(url); } /** * Specifies the name of the bpmViewer application. * *@return Name of the application. */ public String applicationName() { return "BPM_Viewer"; } /** * Activates the preference panel for the bpmViewer application. * *@param document The document whose preferences are being changed. */ public void editPreferences(XalDocument document) { ((BpmViewerDocument) document).editPreferences(); } /** * Specifies whether the bpmViewer application will send standard output * and error to the console. * *@return true or false. */ public boolean usesConsole() { String usesConsoleProperty = System.getProperty("usesConsole"); if (usesConsoleProperty != null) { return Boolean.valueOf(usesConsoleProperty).booleanValue(); } else { return true; } } /** * The main method of the application. * *@param args The command line arguments */ public static void main(String[] args) { final BpmViewerMain appAdaptor = new BpmViewerMain(); URL[] predefConfURLArr = null; if ( args.length == 0 ) { predefConfURLArr = new URL[0]; } else { predefConfURLArr = new URL[args.length]; for ( int index = 0; index < args.length; index++ ) { predefConfURLArr[index] = appAdaptor.getResourceURL( "config/" + args[index] ); } } try { Application.launch( appAdaptor, predefConfURLArr ); } catch (Exception exception) { System.err.println(exception.getMessage()); exception.printStackTrace(); JOptionPane.showMessageDialog( null, exception.getMessage(), exception.getClass().getName(), JOptionPane.WARNING_MESSAGE ); } } }
package org.commcare.dalvik.dialogs; /** * @author amstone326 */ public interface DialogController { /** Should call generateProgressDialog to obtain an instance of a dialog * for the given taskId, and then call show on that dialog fragment */ void showProgressDialog(int taskId); /** Should dismiss the current dialog fragment */ void dismissProgressDialog(); /** Return the dialog that is currently showing, or null * if none exists */ CustomProgressDialog getCurrentDialog(); /** Update the current dialog's message to the new text */ void updateProgress(String updateText, int taskId); /** Update the current dialog's progress bar */ void updateProgressBar(int progress, int max, int taskId); /** Create an instance of CustomProgressDialog specific to the activity * implementing this method -- this method should be implemented lower down * in the activity hierarchy, in one of CommCareActivity's subclasses, * while the other 3 methods can be handled entirely by CommCareActivity */ CustomProgressDialog generateProgressDialog(int taskId); }
package jodd.joy.core; import jodd.db.DbDefault; import jodd.db.DbSessionProvider; import jodd.db.connection.ConnectionProvider; import jodd.db.oom.DbOomManager; import jodd.db.oom.config.AutomagicDbOomConfigurator; import jodd.db.pool.CoreConnectionPool; import jodd.joy.exception.AppException; import jodd.joy.jtx.meta.ReadWriteTransaction; import jodd.jtx.JtxTransactionManager; import jodd.jtx.db.DbJtxSessionProvider; import jodd.jtx.db.DbJtxTransactionManager; import jodd.jtx.meta.Transaction; import jodd.jtx.proxy.AnnotationTxAdvice; import jodd.jtx.proxy.AnnotationTxAdviceManager; import jodd.jtx.proxy.AnnotationTxAdviceSupport; import jodd.log.Log; import jodd.petite.PetiteContainer; import jodd.petite.config.AutomagicPetiteConfigurator; import jodd.petite.proxetta.ProxettaAwarePetiteContainer; import jodd.petite.scope.SessionScope; import jodd.petite.scope.SingletonScope; import jodd.props.Props; import jodd.props.PropsUtil; import jodd.proxetta.MethodInfo; import jodd.proxetta.Proxetta; import jodd.proxetta.ProxyAspect; import jodd.proxetta.pointcuts.MethodAnnotationPointcut; import jodd.util.ClassLoaderUtil; import jodd.util.SystemUtil; import java.lang.annotation.Annotation; import java.net.MalformedURLException; import java.net.URL; /** * Default application core frame. Contains init point to * all application frameworks and layers. */ public abstract class DefaultAppCore { /** * Application properties (from props config file). */ public static final String APP_DIR = "app.dir"; public static final String APP_WEB = "app.web"; /** * Petite bean names. */ public static final String PETITE_APPCORE = "app"; // AppCore public static final String PETITE_DBPOOL = "dbpool"; // database pool public static final String PETITE_DBOOM = "dboom"; // DbOom instance public static final String PETITE_APPINIT = "appInit"; // init bean /** * Logger. Resolved during initialization. */ protected static Log log; /** * App dir. Resolved during initialization. */ protected String appDir; /** * Is web application. Resolved during initialization. */ protected boolean isWebApplication; /** * Scanning entries that will be examined by various * Jodd auto-magic tools. */ protected String[] scanIncludedEntries; /** * Default constructor. */ protected DefaultAppCore() { } protected boolean initialized; /** * Returns <code>true</code> if application is started as a part of web application. */ public boolean isWebApplication() { return isWebApplication; } /** * Returns application directory. */ public String getAppDir() { return appDir; } /** * Initializes system. Invoked *before* anything else! * Override to register types for TypeManager, DbOom conversions, JTX annotations etc. * <p> * May also set the value of <code>appDir</code>. */ @SuppressWarnings("unchecked") public void init() { if (initialized == true) { return; } initialized = true; if (appPropsName == null) { appPropsName = "app.props"; } if (appPropsNamePattern == null) { appPropsNamePattern = "/app*.prop*"; } if (jtxAnnotations == null) { jtxAnnotations = new Class[] {Transaction.class, ReadWriteTransaction.class}; } if (jtxScopePattern == null) { jtxScopePattern = "$class"; } if (appDir == null) { resolveAppDir(appPropsName); // app directory is resolved from location of 'app.props'. } System.setProperty(APP_DIR, appDir); System.setProperty(APP_WEB, Boolean.toString(isWebApplication)); initLogger(); // logger becomes available after this point } /** * Initializes the logger. It must be initialized after the * log path is defined. */ protected void initLogger() { log = Log.getLogger(DefaultAppCore.class); } /** * Resolves application root folders. * Usually invoked on the very beginning, <b>before</b> application initialization. * <p> * If application is started as web application, app folder is one below the WEB-INF folder. * Otherwise, the root folder is equal to the working folder. */ protected void resolveAppDir(String classPathFileName) { URL url = ClassLoaderUtil.getResourceUrl(classPathFileName); if (url == null) { throw new AppException("Unable to resolve app dirs, missing: " + classPathFileName); } String protocol = url.getProtocol(); if (protocol.equals("file") == false) { try { url = new URL(url.getFile()); } catch (MalformedURLException ignore) { } } appDir = url.getFile(); int ndx = appDir.indexOf("WEB-INF"); isWebApplication = (ndx != -1); appDir = isWebApplication ? appDir.substring(0, ndx) : SystemUtil.getWorkingFolder(); } /** * Starts the application and performs all initialization. */ public void start() { init(); initLogger(); initProps(); initScanning(); log.info("app dir: " + appDir); try { startProxetta(); startPetite(); startDb(); startApp(); log.info("app started"); } catch (RuntimeException rex) { if (log != null) { log.error(rex.toString(), rex); } else { System.out.println(rex.toString()); rex.printStackTrace(); } try { stop(); } catch (Exception ignore) { } throw rex; } } /** * Stops the application. */ public void stop() { log.info("shutting down..."); stopApp(); stopDb(); log.info("app stopped"); } /** * Main application props file name, must exist in class path. */ protected String appPropsName; /** * Application props file name pattern. */ protected String appPropsNamePattern; /** * Application props. */ protected Props appProps; /** * Returns applications properties loaded from props files. */ public Props getAppProps() { return appProps; } /** * Creates and loads application props. * It first load system properties (registered as <code>sys.*</code>) * and then environment properties (registered as <code>env.*</code>). * Finally, props files are read from the classpath. */ protected void initProps() { appProps = new Props(); appProps.loadSystemProperties("sys"); appProps.loadEnvironment("env"); PropsUtil.loadFromClasspath(appProps, appPropsNamePattern); } /** * Defines the entries that will be included in the scanning process, * when configuring Jodd frameworks. By default, scanning entries includes * all classes that belongs to the project and to the jodd. */ protected String[] initScanning() { scanIncludedEntries = new String[] { this.getClass().getPackage().getName() + ".*", "jodd.*" }; } protected Proxetta proxetta; /** * Returns proxetta. */ public Proxetta getProxetta() { return proxetta; } /** * Creates Proxetta with all aspects. The following aspects are created: * * <li>Transaction proxy - applied on all classes that contains public top-level methods * annotated with <code>@Transaction</code> annotation. This is just one way how proxies * can be applied - since base configuration is in Java, everything is possible. */ protected void startProxetta() { log.info("proxetta initialization"); proxetta = Proxetta.withAspects(createAppAspects()).loadsWith(this.getClass().getClassLoader()); } /** * Creates all application aspects. By default it creates just * {@link #createTxProxyAspects() transactional aspect}. */ protected ProxyAspect[] createAppAspects() { return new ProxyAspect[] {createTxProxyAspects()}; } /** * Creates TX aspect that will be applied on all classes * having at least one public top-level method annotated * with {@link #jtxAnnotations registered JTX annotations}. */ protected ProxyAspect createTxProxyAspects() { return new ProxyAspect( AnnotationTxAdvice.class, new MethodAnnotationPointcut(jtxAnnotations) { @Override public boolean apply(MethodInfo methodInfo) { return isPublic(methodInfo) && isTopLevelMethod(methodInfo) && super.apply(methodInfo); } }); } protected PetiteContainer petite; /** * Returns application container (Petite). */ public PetiteContainer getPetite() { return petite; } /** * Creates and initializes Petite container. * It will be auto-magically configured by scanning the classpath. * Also, all 'app*.prop*' will be loaded and values will * be injected in the matched beans. At the end it registers * this instance of core into the container. */ protected void startPetite() { log.info("petite initialization"); petite = createPetiteContainer(); log.info("app in web: " + Boolean.valueOf(isWebApplication)); if (isWebApplication == false) { // make session scope to act as singleton scope // if this is not a web application (and http session is not available). petite.registerScope(SessionScope.class, new SingletonScope()); } // automagic configuration AutomagicPetiteConfigurator pcfg = new AutomagicPetiteConfigurator(); pcfg.setIncludedEntries(scanIncludedEntries); pcfg.configure(petite); // load parameters from properties files petite.defineParameters(appProps); // add AppCore instance to Petite petite.addBean(PETITE_APPCORE, this); } /** * Creates Petite container. By default, it creates * {@link jodd.petite.proxetta.ProxettaAwarePetiteContainer proxetta aware petite container}. */ protected PetiteContainer createPetiteContainer() { return new ProxettaAwarePetiteContainer(proxetta); } /** * Database debug mode will print out SQL statements. */ protected boolean dbDebug; /** * Returns <code>true</code> if database debug mode is on. */ public boolean isDbDebug() { return dbDebug; } /** * JTX manager. */ protected JtxTransactionManager jtxManager; /** * Returns JTX transaction manager. */ public JtxTransactionManager getJtxManager() { return jtxManager; } /** * Database connection provider. */ protected ConnectionProvider connectionProvider; /** * Returns connection provider. */ public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * JTX annotations. */ protected Class<? extends Annotation>[] jtxAnnotations; /** * JTX scope pattern. * @see {@link AnnotationTxAdviceManager} */ protected String jtxScopePattern; /** * Initializes database. First, creates connection pool. * and transaction manager. Then, Jodds DbOomManager is * configured. It is also configured automagically, by scanning * the class path for entities. */ @SuppressWarnings("unchecked") protected void startDb() { log.info("database initialization"); // connection pool petite.registerBean(PETITE_DBPOOL, CoreConnectionPool.class); connectionProvider = (ConnectionProvider) petite.getBean(PETITE_DBPOOL); connectionProvider.init(); // transactions manager jtxManager = createJtxTransactionManager(connectionProvider); jtxManager.setValidateExistingTransaction(true); AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager(jtxManager, jtxScopePattern); annTxAdviceManager.registerAnnotations(jtxAnnotations); AnnotationTxAdviceSupport.manager = annTxAdviceManager; DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager); // global settings DbDefault.debug = dbDebug; DbDefault.connectionProvider = connectionProvider; DbDefault.sessionProvider = sessionProvider; DbOomManager dbOomManager = createDbOomManager(); DbOomManager.setInstance(dbOomManager); petite.addBean(PETITE_DBOOM, dbOomManager); // automatic configuration AutomagicDbOomConfigurator dbcfg = new AutomagicDbOomConfigurator(); dbcfg.setIncludedEntries(scanIncludedEntries); dbcfg.configure(dbOomManager); } /** * Creates JTX transaction manager. */ protected JtxTransactionManager createJtxTransactionManager(ConnectionProvider connectionProvider) { return new DbJtxTransactionManager(connectionProvider); } /** * Creates DbOomManager. */ protected DbOomManager createDbOomManager() { return DbOomManager.getInstance(); } /** * Closes database resources at the end. */ protected void stopDb() { log.info("database shutdown"); jtxManager.close(); connectionProvider.close(); } protected AppInit appInit; /** * Initializes business part of the application. * Simply delegates to {@link AppInit#init()}. */ protected void startApp() { appInit = (AppInit) petite.getBean(PETITE_APPINIT); if (appInit != null) { appInit.init(); } } /** * Stops business part of the application. * Simply delegates to {@link AppInit#stop()}. */ protected void stopApp() { if (appInit != null) { appInit.stop(); } } }
package com.wavefront.agent; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.io.Files; import com.google.gson.Gson; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.fasterxml.jackson.databind.JsonNode; import com.wavefront.api.AgentAPI; import com.wavefront.api.agent.AgentConfiguration; import com.wavefront.common.Clock; import com.wavefront.metrics.ExpectedAgentMetric; import com.wavefront.metrics.JsonMetricsGenerator; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Gauge; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.jboss.resteasy.plugins.providers.jackson.ResteasyJacksonProvider; import org.jboss.resteasy.spi.ResteasyProviderFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.ResourceBundle; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; /** * Agent that runs remotely on a server collecting metrics. * * @author Clement Pang (clement@wavefront.com) */ public abstract class AbstractAgent { protected static final Logger logger = Logger.getLogger("agent"); private static final Gson GSON = new Gson(); private static final int GRAPHITE_LISTENING_PORT = 2878; private static final int OPENTSDB_LISTENING_PORT = 4242; @Parameter(names = {"-f", "--file"}, description = "Proxy configuration file") private String pushConfigFile = null; @Parameter(names = {"-c", "--config"}, description = "Local configuration file to use (overrides using the server to obtain a config file)") private String configFile = null; @Parameter(names = {"-p", "--prefix"}, description = "Prefix to prepend to all push metrics before reporting.") protected String prefix = null; @Parameter(names = {"-t", "--token"}, description = "Token to auto-register agent with an account") private String token = null; @Parameter(names = {"-l", "--loglevel"}, description = "Log level for push data (NONE/SUMMARY/DETAILED); NONE is default") protected String pushLogLevel = "NONE"; @Parameter(names = {"-v", "--validationlevel"}, description = "Validation level for push data (NO_VALIDATION/NUMERIC_ONLY/TEXT_ONLY/ALL); NO_VALIDATION is default") protected String pushValidationLevel = "NUMERIC_ONLY"; @Parameter(names = {"-h", "--host"}, description = "Server URL") protected String server = "http://localhost:8082/api/"; @Parameter(names = {"--buffer"}, description = "File to use for buffering failed transmissions to Wavefront servers" + ". Defaults to buffer.") private String bufferFile = "buffer"; @Parameter(names = {"--retryThreads"}, description = "Number of threads retrying failed transmissions. Defaults to " + "the number of processors (min. 4). Buffer files are maxed out at 2G each so increasing the number of retry " + "threads effectively governs the maximum amount of space the agent will use to buffer points locally") protected int retryThreads = Math.max(4, Runtime.getRuntime().availableProcessors()); @Parameter(names = {"--flushThreads"}, description = "Number of threads that flush data to the server. Defaults to" + "the number of processors (min. 4). Setting this value too large will result in sending batches that are too " + "small to the server and wasting connections. This setting is per listening port.") protected int flushThreads = Math.max(4, Runtime.getRuntime().availableProcessors()); @Parameter(names = {"--purgeBuffer"}, description = "Whether to purge the retry buffer on start-up. Defaults to " + "false.") private boolean purgeBuffer = false; @Parameter(names = {"--pushFlushInterval"}, description = "Milliseconds between flushes to . Defaults to 1000 ms") protected long pushFlushInterval = 1000; @Parameter(names = {"--pushFlushMaxPoints"}, description = "Maximum allowed points in a single push flush. Defaults" + " to 50,000") protected int pushFlushMaxPoints = 50000; @Parameter(names = {"--pushBlockedSamples"}, description = "Max number of blocked samples to print to log. Defaults" + " to 0.") protected int pushBlockedSamples = 0; @Parameter(names = {"--pushListenerPorts"}, description = "Comma-separated list of ports to listen on. Defaults to " + "2878.") protected String pushListenerPorts = "" + GRAPHITE_LISTENING_PORT; @Parameter(names = {"--graphitePorts"}, description = "Comma-separated list of ports to listen on for graphite " + "data. Defaults to empty list.") protected String graphitePorts = ""; @Parameter(names = {"--graphiteFormat"}, description = "Comma-separated list of metric segments to extract and " + "reassemble as the hostname (1-based).") protected String graphiteFormat = ""; @Parameter(names = {"--graphiteDelimiters"}, description = "Concatenated delimiters that should be replaced in the " + "extracted hostname with dots. Defaults to underscores (_).") protected String graphiteDelimiters = "_"; @Parameter(names = {"--httpJsonPorts"}, description = "Comma-separated list of ports to listen on for json metrics " + "data. Binds, by default, to none.") protected String httpJsonPorts = ""; @Parameter(names = {"--writeHttpJsonPorts"}, description = "Comma-separated list of ports to listen on for json metrics from collectd write_http json format " + "data. Binds, by default, to none.") protected String writeHttpJsonPorts = ""; @Parameter(names = {"--hostname"}, description = "Hostname for the agent. Defaults to FQDN of machine.") protected String hostname; @Parameter(names = {"--idFile"}, description = "File to read agent id from. Defaults to ~/.dshell/id") protected String idFile = null; @Parameter(names = {"--graphiteWhitelistRegex"}, description = "(DEPRECATED for whitelistRegex)", hidden = true) protected String graphiteWhitelistRegex; @Parameter(names = {"--graphiteBlacklistRegex"}, description = "(DEPRECATED for blacklistRegex)", hidden = true) protected String graphiteBlacklistRegex; @Parameter(names = {"--whitelistRegex"}, description = "Regex pattern (java.util.regex) that graphite input lines must match to be accepted") protected String whitelistRegex; @Parameter(names = {"--blacklistRegex"}, description = "Regex pattern (java.util.regex) that graphite input lines must NOT match to be accepted") protected String blacklistRegex; @Parameter(names = {"--opentsdbPorts"}, description = "Comma-separated list of ports to listen on for opentsdb " + "data. Defaults to: " + OPENTSDB_LISTENING_PORT) protected String opentsdbPorts = "" + OPENTSDB_LISTENING_PORT; @Parameter(names = {"--opentsdbWhitelistRegex"}, description = "Regex pattern (java.util.regex) that opentsdb input lines must match to be accepted") protected String opentsdbWhitelistRegex; @Parameter(names = {"--opentsdbBlacklistRegex"}, description = "Regex pattern (java.util.regex) that opentsdb input lines must NOT match to be accepted") protected String opentsdbBlacklistRegex; @Parameter(names = {"--splitPushWhenRateLimited"}, description = "Whether to split the push batch size when the push is rejected by Wavefront due to rate limit. Default false.") protected boolean splitPushWhenRateLimited = false; @Parameter(names = {"--retryBackoffBaseSeconds"}, description = "For exponential backoff when retry threads are throttled, the base (a in a^b) in seconds. Default 2.0") protected double retryBackoffBaseSeconds = 2.0; @Parameter(names = {"--customSourceTags"}, description = "Comma separated list of point tag keys that should be treated as the source in Wavefront in the absence of a tag named source or host") protected String customSourceTagsProperty = "fqdn"; @Parameter(names = {"--ephemeral"}, description = "If true, this agent is removed from Wavefront after 24 hours of inactivity.") protected boolean ephemeral = false; @Parameter(description = "Unparsed parameters") protected List<String> unparsed_params; protected QueuedAgentService agentAPI; protected ResourceBundle props; protected final AtomicLong bufferSpaceLeft = new AtomicLong(); protected List<String> customSourceTags = new ArrayList<String>(); protected final boolean localAgent; protected final boolean pushAgent; /** * Executors for support tasks. */ private final ScheduledExecutorService auxiliaryExecutor = Executors.newScheduledThreadPool(1); protected UUID agentId; private final Runnable updateConfiguration = new Runnable() { @Override public void run() { try { AgentConfiguration config = fetchConfig(); if (config != null) { processConfiguration(config); } } finally { auxiliaryExecutor.schedule(this, 60, TimeUnit.SECONDS); } } }; public AbstractAgent() { this(false, false); } public AbstractAgent(boolean localAgent, boolean pushAgent) { this.pushAgent = pushAgent; this.localAgent = localAgent; try { this.hostname = InetAddress.getLocalHost().getCanonicalHostName(); Metrics.newGauge(ExpectedAgentMetric.BUFFER_BYTES_LEFT.metricName, new Gauge<Long>() { @Override public Long value() { return bufferSpaceLeft.get(); } } ); } catch (UnknownHostException e) { throw Throwables.propagate(e); } } protected abstract void startListeners(); private void loadListenerConfigurationFile() throws IOException { // If they've specified a push configuration file, override the command line values if (pushConfigFile != null) { Properties prop = new Properties(); try { prop.load(new FileInputStream(pushConfigFile)); prefix = Strings.emptyToNull(prop.getProperty("prefix", prefix)); pushLogLevel = prop.getProperty("pushLogLevel", pushLogLevel); pushValidationLevel = prop.getProperty("pushValidationLevel", pushValidationLevel); token = prop.getProperty("token", token); server = prop.getProperty("server", server); hostname = prop.getProperty("hostname", hostname); idFile = prop.getProperty("idFile", idFile); pushFlushInterval = Integer.parseInt(prop.getProperty("pushFlushInterval", String.valueOf(pushFlushInterval))); pushFlushMaxPoints = Integer.parseInt(prop.getProperty("pushFlushMaxPoints", String.valueOf(pushFlushMaxPoints))); pushBlockedSamples = Integer.parseInt(prop.getProperty("pushBlockedSamples", String.valueOf(pushBlockedSamples))); pushListenerPorts = prop.getProperty("pushListenerPorts", pushListenerPorts); retryThreads = Integer.parseInt(prop.getProperty("retryThreads", String.valueOf(retryThreads))); flushThreads = Integer.parseInt(prop.getProperty("flushThreads", String.valueOf(flushThreads))); httpJsonPorts = prop.getProperty("jsonListenerPorts", httpJsonPorts); writeHttpJsonPorts = prop.getProperty("writeHttpJsonListenerPorts", writeHttpJsonPorts); graphitePorts = prop.getProperty("graphitePorts", graphitePorts); graphiteFormat = prop.getProperty("graphiteFormat", graphiteFormat); graphiteDelimiters = prop.getProperty("graphiteDelimiters", graphiteDelimiters); graphiteWhitelistRegex = prop.getProperty("graphiteWhitelistRegex", graphiteWhitelistRegex); graphiteBlacklistRegex = prop.getProperty("graphiteBlacklistRegex", graphiteBlacklistRegex); whitelistRegex = prop.getProperty("whitelistRegex", whitelistRegex); blacklistRegex = prop.getProperty("blacklistRegex", blacklistRegex); opentsdbPorts = prop.getProperty("opentsdbPorts", opentsdbPorts); opentsdbWhitelistRegex = prop.getProperty("opentsdbWhitelistRegex", opentsdbWhitelistRegex); opentsdbBlacklistRegex = prop.getProperty("opentsdbBlacklistRegex", opentsdbBlacklistRegex); splitPushWhenRateLimited = Boolean.parseBoolean(prop.getProperty("splitPushWhenRateLimited", String.valueOf(splitPushWhenRateLimited))); retryBackoffBaseSeconds = Double.parseDouble(prop.getProperty("retryBackoffBaseSeconds", String.valueOf(retryBackoffBaseSeconds))); customSourceTagsProperty = prop.getProperty("customSourceTags", customSourceTagsProperty); ephemeral = Boolean.parseBoolean(prop.getProperty("ephemeral", String.valueOf(ephemeral))); logger.warning("Loaded configuration file " + pushConfigFile); } catch (Throwable exception) { logger.severe("Could not load configuration file " + pushConfigFile); throw exception; } // Compatibility with deprecated fields if (whitelistRegex == null && graphiteWhitelistRegex != null) { whitelistRegex = graphiteWhitelistRegex; } if (blacklistRegex == null && graphiteBlacklistRegex != null) { blacklistRegex = graphiteBlacklistRegex; } PostPushDataTimedTask.setPointsPerBatch(pushFlushMaxPoints); QueuedAgentService.setSplitBatchSize(pushFlushMaxPoints); QueuedAgentService.setRetryBackoffBaseSeconds(retryBackoffBaseSeconds); } } /** * Entry-point for the application. * * @param args Command-line parameters passed on to JCommander to configure the daemon. */ public void start(String[] args) throws IOException { try { logger.info("Arguments: " + Joiner.on(", ").join(args)); new JCommander(this, args); if (unparsed_params != null) { logger.info("Unparsed arguments: " + Joiner.on(", ").join(unparsed_params)); } // 1. Load the listener configuration, if it exists loadListenerConfigurationFile(); // 2. Read or create the unique Id for the daemon running on this machine. readOrCreateDaemonId(); // read build information. props = ResourceBundle.getBundle("build"); // create List of custom tags from the configuration string String[] tags = customSourceTagsProperty.split(","); for (String tag : tags) { tag = tag.trim(); if (!customSourceTags.contains(tag)) { customSourceTags.add(tag); } else { logger.warning("Custom source tag: " + tag + " was repeated. Check the customSourceTags property in wavefront.conf"); } } // 3. Setup proxies. AgentAPI service = createAgentService(); try { setupQueueing(service); } catch (IOException e) { logger.log(Level.SEVERE, "Cannot setup local file for queueing due to IO error", e); throw e; } // 4. Start the (push) listening endpoints startListeners(); // 5. Poll or read the configuration file to use. AgentConfiguration config; if (configFile != null) { logger.info("Loading configuration file from: " + configFile); try { config = GSON.fromJson(new FileReader(configFile), AgentConfiguration.class); } catch (FileNotFoundException e) { throw new RuntimeException("Cannot read config file: " + configFile); } try { config.validate(localAgent); } catch (RuntimeException ex) { logger.log(Level.SEVERE, "cannot parse config file", ex); throw new RuntimeException("cannot parse config file", ex); } agentId = null; } else { config = fetchConfig(); logger.info("scheduling regular configuration polls"); auxiliaryExecutor.schedule(updateConfiguration, 10, TimeUnit.SECONDS); URI url = URI.create(server); if (url.getPath().endsWith("/api/")) { String configurationLogMessage = "TO CONFIGURE THIS PROXY AGENT, USE THIS KEY: " + agentId; logger.warning(Strings.repeat("*", configurationLogMessage.length())); logger.warning(configurationLogMessage); logger.warning(Strings.repeat("*", configurationLogMessage.length())); } } // 6. Setup work units and targets based on the configuration. if (config != null) { logger.info("initial configuration is available, setting up proxy agent"); processConfiguration(config); } logger.info("setup complete"); } catch (Throwable t) { logger.log(Level.SEVERE, "Aborting start-up", t); System.exit(1); } } /** * Create RESTeasy proxies for remote calls via HTTP. */ protected AgentAPI createAgentService() { ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); factory.registerProvider(JsonNodeWriter.class); factory.registerProvider(ResteasyJacksonProvider.class); HttpClient httpClient = HttpClientBuilder.create(). useSystemProperties(). setMaxConnTotal(200). setMaxConnPerRoute(100). setDefaultRequestConfig( RequestConfig.custom(). setContentCompressionEnabled(true). setRedirectsEnabled(true). setConnectTimeout(5000). setConnectionRequestTimeout(5000). setSocketTimeout(60000).build()). build(); ResteasyClient client = new ResteasyClientBuilder(). httpEngine(new ApacheHttpClient4Engine(httpClient, true)). providerFactory(factory). build(); ResteasyWebTarget target = client.target(server); return target.proxy(AgentAPI.class); } private void setupQueueing(AgentAPI service) throws IOException { agentAPI = new QueuedAgentService(service, bufferFile, retryThreads, Executors.newScheduledThreadPool(retryThreads + 1, new ThreadFactory() { private AtomicLong counter = new AtomicLong(); @Override public Thread newThread(Runnable r) { Thread toReturn = new Thread(r); toReturn.setName("submission worker: " + counter.getAndIncrement()); return toReturn; } }), purgeBuffer, agentId, splitPushWhenRateLimited, pushLogLevel); } /** * Read or create the Daemon id for this machine. Reads from ~/.dshell/id. */ private void readOrCreateDaemonId() { File agentIdFile; if (idFile != null) { agentIdFile = new File(idFile); } else { File userHome = new File(System.getProperty("user.home")); if (!userHome.exists() || !userHome.isDirectory()) { logger.severe("Cannot read from user.home, quitting"); System.exit(1); } File configDirectory = new File(userHome, ".dshell"); if (configDirectory.exists()) { if (!configDirectory.isDirectory()) { logger.severe(configDirectory + " must be a directory!"); System.exit(1); } } else { if (!configDirectory.mkdir()) { logger.severe("Cannot create .dshell directory under " + userHome); System.exit(1); } } agentIdFile = new File(configDirectory, "id"); } if (agentIdFile.exists()) { if (agentIdFile.isFile()) { try { agentId = UUID.fromString(Files.readFirstLine(agentIdFile, Charsets.UTF_8)); logger.info("Proxy Agent Id read from file: " + agentId); } catch (IllegalArgumentException ex) { logger.severe("Cannot read proxy agent id from " + agentIdFile + ", content is malformed"); System.exit(1); } catch (IOException e) { logger.log(Level.SEVERE, "Cannot read from " + agentIdFile, e); System.exit(1); } } else { logger.severe(agentIdFile + " is not a file!"); System.exit(1); } } else { agentId = UUID.randomUUID(); logger.info("Proxy Agent Id created: " + agentId); try { Files.write(agentId.toString(), agentIdFile, Charsets.UTF_8); } catch (IOException e) { logger.severe("Cannot write to " + agentIdFile); System.exit(1); } } } /** * Fetch configuration of the daemon from remote server. * * @return Fetched configuration. {@code null} if the configuration is invalid. */ private AgentConfiguration fetchConfig() { AgentConfiguration newConfig; try { logger.info("fetching configuration from server at: " + server); File buffer = new File(bufferFile).getAbsoluteFile(); try { while (buffer != null && buffer.getUsableSpace() == 0) { buffer = buffer.getParentFile(); } if (buffer != null) { // the amount of space is limited by the number of retryThreads. bufferSpaceLeft.set(Math.min((long) Integer.MAX_VALUE * retryThreads, buffer.getUsableSpace())); } } catch (Throwable t) { logger.warning("cannot compute remaining space in buffer file partition: " + t); } JsonNode agentMetrics = JsonMetricsGenerator.generateJsonMetrics(Metrics.defaultRegistry(), true, true, true); newConfig = agentAPI.checkin(agentId, hostname, token, props.getString("build.version"), System.currentTimeMillis(), localAgent, agentMetrics, pushAgent, ephemeral); } catch (Exception ex) { logger.warning("cannot fetch proxy agent configuration from remote server: " + Throwables.getRootCause(ex)); return null; } if (newConfig.currentTime != null) { Clock.set(newConfig.currentTime); } try { newConfig.validate(localAgent); } catch (Exception ex) { logger.log(Level.WARNING, "configuration file read from server is invalid", ex); try { agentAPI.agentError(agentId, "Configuration file is invalid: " + ex.toString()); } catch (Exception e) { logger.log(Level.WARNING, "cannot report error to collector", e); } return null; } return newConfig; } /** * Actual agents can do additional configuration. * * @param config The configuration to process. */ protected void processConfiguration(AgentConfiguration config) { try { agentAPI.agentConfigProcessed(agentId); } catch (RuntimeException e) { // cannot throw or else configuration update thread would die. } } }
package configgen; import configgen.data.Datas; import configgen.define.ConfigCollection; import configgen.gen.CachedFileOutputStream; import configgen.gen.Generator; import configgen.type.Cfgs; import configgen.value.CfgVs; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public final class Main { private static void usage(String reason) { System.err.println(reason); System.out.println("Usage: java -jar configgen.jar [options]"); System.out.println(" -configdir config data directory."); System.out.println(" -xml default config.xml in datadir."); System.out.println(" -encoding csv and xml encoding. default GBK"); System.out.println(" -v verbose, default no"); Generator.providers.forEach((k, v) -> System.out.println(" -gen " + k + "," + v.usage())); System.out.println(" -packtext for i18n, pack text.csv to text.zip"); Runtime.getRuntime().exit(1); } public static void main(String[] args) throws Exception { String configdir = null; String xml = null; String encoding = "GBK"; List<Generator> generators = new ArrayList<>(); for (int i = 0; i < args.length; ++i) { switch (args[i]) { case "-configdir": configdir = args[++i]; break; case "-xml": xml = args[++i]; break; case "-encoding": encoding = args[++i]; break; case "-gen": Generator generator = Generator.create(args[++i]); if (generator == null) usage(""); generators.add(generator); break; case "-v": Logger.enableVerbose(); break; case "-packtext": File file = new File(args[++i]); try (ZipOutputStream zos = new ZipOutputStream(new CheckedOutputStream(new CachedFileOutputStream(new File("text.zip")), new CRC32()))) { ZipEntry ze = new ZipEntry("text.csv"); ze.setTime(0); zos.putNextEntry(ze); Files.copy(file.toPath(), zos); } return; default: usage("unknown args " + args[i]); break; } } if (configdir == null) { usage("-configdir miss"); return; } Path dir = Paths.get(configdir); File xmlFile = xml != null ? new File(xml) : dir.resolve("config.xml").toFile(); Logger.verbose("parse xml " + xmlFile); ConfigCollection define = new ConfigCollection(xmlFile); Cfgs type = new Cfgs(define); type.resolve(); Logger.verbose("read data " + dir + " then auto complete xml"); Datas data = new Datas(dir, encoding); data.autoCompleteDefine(type); define.save(xmlFile, encoding); Cfgs newType = new Cfgs(define); newType.resolve(); Logger.verbose("verify constraint"); CfgVs value = new CfgVs(newType, data); value.verifyConstraint(); for (Generator generator : generators) { Logger.verbose("generate " + generator.context.arg); generator.generate(dir, value); } Logger.verbose("end"); } }
package io.github.javageeks.mase.repository; import io.github.javageeks.mase.model.Todo; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; /** * Interface for todo repository. */ public interface TodoRepository extends MongoRepository<Todo, String> { /** * Find todo list by user id. * @param userId the user id * @return the todo list for the given user */ List<Todo> findByUserId(String userId); /** * Find todo list by title. * @param userId the userId * @param title the todo title * @return the todo list with the given todo title */ List<Todo> findByUserIdAndTitleLike(String userId, String title); /** * Find todo list by description. * @param userId the user id * @param description the todo description * @return the todo list with the given todo description */ List<Todo> findByUserIdAndDescriptionLike(String userId, String description); /** * Find todo list by todo status. * @param userId the user id * @param status the todo status * @return the todo list with the given todo status */ List<Todo> findByUserIdAndStatusIsTrue(String userId, boolean status); }
package com.codahale.metrics.ganglia; import com.codahale.metrics.*; import info.ganglia.gmetric4j.gmetric.GMetric; import info.ganglia.gmetric4j.gmetric.GMetricSlope; import info.ganglia.gmetric4j.gmetric.GMetricType; import info.ganglia.gmetric4j.gmetric.GangliaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.SortedMap; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static com.codahale.metrics.MetricRegistry.name; public class GangliaReporter extends ScheduledReporter { private static final Pattern SLASHES = Pattern.compile("\\\\"); /** * Returns a new {@link Builder} for {@link GangliaReporter}. * * @param registry the registry to report * @return a {@link Builder} instance for a {@link GangliaReporter} */ public static Builder forRegistry(MetricRegistry registry) { return new Builder(registry); } /** * A builder for {@link GangliaReporter} instances. Defaults to using a {@code tmax} of {@code 60}, * a {@code dmax} of {@code 0}, converting rates to events/second, converting durations to * milliseconds, and not filtering metrics. */ public static class Builder { private final MetricRegistry registry; private String prefix; private int tMax; private int dMax; private TimeUnit rateUnit; private TimeUnit durationUnit; private MetricFilter filter; private Builder(MetricRegistry registry) { this.registry = registry; this.tMax = 60; this.dMax = 0; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; } /** * Use the given {@code tmax} value when announcing metrics. * * @param tMax the desired gmond {@code tmax} value * @return {@code this} */ public Builder withTMax(int tMax) { this.tMax = tMax; return this; } /** * Prefix all metric names with the given string. * * @param prefix the prefix for all metric names * @return {@code this} */ public Builder prefixedWith(String prefix) { this.prefix = prefix; return this; } /** * Use the given {@code dmax} value when announcing metrics. * * @param dMax the desired gmond {@code dmax} value * @return {@code this} */ public Builder withDMax(int dMax) { this.dMax = dMax; return this; } /** * Convert rates to the given time unit. * * @param rateUnit a unit of time * @return {@code this} */ public Builder convertRatesTo(TimeUnit rateUnit) { this.rateUnit = rateUnit; return this; } /** * Convert durations to the given time unit. * * @param durationUnit a unit of time * @return {@code this} */ public Builder convertDurationsTo(TimeUnit durationUnit) { this.durationUnit = durationUnit; return this; } /** * Only report metrics which match the given filter. * * @param filter a {@link MetricFilter} * @return {@code this} */ public Builder filter(MetricFilter filter) { this.filter = filter; return this; } /** * Builds a {@link GangliaReporter} with the given properties, announcing metrics to the * given {@link GMetric} client. * * @param gmetric the client to use for announcing metrics * @return a {@link GangliaReporter} */ public GangliaReporter build(GMetric gmetric) { return new GangliaReporter(registry, gmetric, null, prefix, tMax, dMax, rateUnit, durationUnit, filter); } /** * Builds a {@link GangliaReporter} with the given properties, announcing metrics to the * given {@link GMetric} client. * * @param gmetrics the clients to use for announcing metrics * @return a {@link GangliaReporter} */ public GangliaReporter build(GMetric... gmetrics) { return new GangliaReporter(registry, null, gmetrics, prefix, tMax, dMax, rateUnit, durationUnit, filter); } } private static final Logger LOGGER = LoggerFactory.getLogger(GangliaReporter.class); private final GMetric gmetric; private final GMetric[] gmetrics; private final String prefix; private final int tMax; private final int dMax; private GangliaReporter(MetricRegistry registry, GMetric gmetric, GMetric[] gmetrics, String prefix, int tMax, int dMax, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter) { super(registry, "ganglia-reporter", filter, rateUnit, durationUnit); this.gmetric = gmetric; this.gmetrics = gmetrics; this.prefix = prefix; this.tMax = tMax; this.dMax = dMax; } @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { for (Map.Entry<String, Gauge> entry : gauges.entrySet()) { reportGauge(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Counter> entry : counters.entrySet()) { reportCounter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Histogram> entry : histograms.entrySet()) { reportHistogram(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Meter> entry : meters.entrySet()) { reportMeter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Timer> entry : timers.entrySet()) { reportTimer(entry.getKey(), entry.getValue()); } } private void reportTimer(String name, Timer timer) { final String sanitizedName = escapeSlashes(name); final String group = group(name); try { final Snapshot snapshot = timer.getSnapshot(); announce(prefix(sanitizedName, "max"), group, convertDuration(snapshot.getMax()), getDurationUnit()); announce(prefix(sanitizedName, "mean"), group, convertDuration(snapshot.getMean()), getDurationUnit()); announce(prefix(sanitizedName, "min"), group, convertDuration(snapshot.getMin()), getDurationUnit()); announce(prefix(sanitizedName, "stddev"), group, convertDuration(snapshot.getStdDev()), getDurationUnit()); announce(prefix(sanitizedName, "p50"), group, convertDuration(snapshot.getMedian()), getDurationUnit()); announce(prefix(sanitizedName, "p75"), group, convertDuration(snapshot.get75thPercentile()), getDurationUnit()); announce(prefix(sanitizedName, "p95"), group, convertDuration(snapshot.get95thPercentile()), getDurationUnit()); announce(prefix(sanitizedName, "p98"), group, convertDuration(snapshot.get98thPercentile()), getDurationUnit()); announce(prefix(sanitizedName, "p99"), group, convertDuration(snapshot.get99thPercentile()), getDurationUnit()); announce(prefix(sanitizedName, "p999"), group, convertDuration(snapshot.get999thPercentile()), getDurationUnit()); reportMetered(sanitizedName, timer, group, "calls"); } catch (GangliaException e) { LOGGER.warn("Unable to report timer {}", sanitizedName, e); } } private void reportMeter(String name, Meter meter) { final String sanitizedName = escapeSlashes(name); final String group = group(name); try { reportMetered(sanitizedName, meter, group, "events"); } catch (GangliaException e) { LOGGER.warn("Unable to report meter {}", name, e); } } private void reportMetered(String name, Metered meter, String group, String eventName) throws GangliaException { final String unit = eventName + '/' + getRateUnit(); announce(prefix(name, "count"), group, meter.getCount(), eventName); announce(prefix(name, "m1_rate"), group, convertRate(meter.getOneMinuteRate()), unit); announce(prefix(name, "m5_rate"), group, convertRate(meter.getFiveMinuteRate()), unit); announce(prefix(name, "m15_rate"), group, convertRate(meter.getFifteenMinuteRate()), unit); announce(prefix(name, "mean_rate"), group, convertRate(meter.getMeanRate()), unit); } private void reportHistogram(String name, Histogram histogram) { final String sanitizedName = escapeSlashes(name); final String group = group(name); try { final Snapshot snapshot = histogram.getSnapshot(); announce(prefix(sanitizedName, "count"), group, histogram.getCount(), ""); announce(prefix(sanitizedName, "max"), group, snapshot.getMax(), ""); announce(prefix(sanitizedName, "mean"), group, snapshot.getMean(), ""); announce(prefix(sanitizedName, "min"), group, snapshot.getMin(), ""); announce(prefix(sanitizedName, "stddev"), group, snapshot.getStdDev(), ""); announce(prefix(sanitizedName, "p50"), group, snapshot.getMedian(), ""); announce(prefix(sanitizedName, "p75"), group, snapshot.get75thPercentile(), ""); announce(prefix(sanitizedName, "p95"), group, snapshot.get95thPercentile(), ""); announce(prefix(sanitizedName, "p98"), group, snapshot.get98thPercentile(), ""); announce(prefix(sanitizedName, "p99"), group, snapshot.get99thPercentile(), ""); announce(prefix(sanitizedName, "p999"), group, snapshot.get999thPercentile(), ""); } catch (GangliaException e) { LOGGER.warn("Unable to report histogram {}", sanitizedName, e); } } private void reportCounter(String name, Counter counter) { final String sanitizedName = escapeSlashes(name); final String group = group(name); try { announce(prefix(sanitizedName, "count"), group, counter.getCount(), ""); } catch (GangliaException e) { LOGGER.warn("Unable to report counter {}", name, e); } } private void reportGauge(String name, Gauge gauge) { final String sanitizedName = escapeSlashes(name); final String group = group(name); final Object obj = gauge.getValue(); final String value = String.valueOf(obj); final GMetricType type = detectType(obj); try { announce(name(prefix, sanitizedName), group, value, type, ""); } catch (GangliaException e) { LOGGER.warn("Unable to report gauge {}", name, e); } } private static final double MIN_VAL = 1E-300; private void announce(String name, String group, double value, String units) throws GangliaException { final String string = Math.abs(value) < MIN_VAL ? "0" : Double.toString(value); announce(name, group, string, GMetricType.DOUBLE, units); } private void announce(String name, String group, long value, String units) throws GangliaException { announce(name, group, Long.toString(value), GMetricType.DOUBLE, units); } private void announce(String name, String group, String value, GMetricType type, String units) throws GangliaException { if (gmetric != null) { gmetric.announce(name, value, type, units, GMetricSlope.BOTH, tMax, dMax, group); } else { for (GMetric gmetric : gmetrics) { gmetric.announce(name, value, type, units, GMetricSlope.BOTH, tMax, dMax, group); } } } private GMetricType detectType(Object o) { if (o instanceof Float) { return GMetricType.FLOAT; } else if (o instanceof Double) { return GMetricType.DOUBLE; } else if (o instanceof Byte) { return GMetricType.INT8; } else if (o instanceof Short) { return GMetricType.INT16; } else if (o instanceof Integer) { return GMetricType.INT32; } else if (o instanceof Long) { return GMetricType.DOUBLE; } return GMetricType.STRING; } private String group(String name) { final int i = name.lastIndexOf('.'); if (i < 0) { return ""; } return name.substring(0, i); } private String prefix(String name, String n) { return name(prefix, name, n); } // ganglia metric names can't contain slashes. private String escapeSlashes(String name) { return SLASHES.matcher(name).replaceAll("_"); } }
package com.github.dreamhead.moco.action; import com.github.dreamhead.moco.HttpHeader; import com.github.dreamhead.moco.HttpMethod; import com.github.dreamhead.moco.HttpProtocolVersion; import com.github.dreamhead.moco.MocoConfig; import com.github.dreamhead.moco.MocoEventAction; import com.github.dreamhead.moco.MocoException; import com.github.dreamhead.moco.Request; import com.github.dreamhead.moco.Response; import com.github.dreamhead.moco.dumper.Dumper; import com.github.dreamhead.moco.dumper.HttpRequestDumper; import com.github.dreamhead.moco.dumper.HttpResponseDumper; import com.github.dreamhead.moco.model.DefaultHttpRequest; import com.github.dreamhead.moco.model.DefaultHttpResponse; import com.github.dreamhead.moco.model.MessageContent; import com.github.dreamhead.moco.resource.Resource; import com.google.common.collect.ArrayListMultimap; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.NameValuePair; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public abstract class MocoRequestAction implements MocoEventAction { private static Logger logger = LoggerFactory.getLogger(MocoRequestAction.class); private static final Dumper<Response> responseDumper = new HttpResponseDumper(); private static final Dumper<Request> requestDumper = new HttpRequestDumper(); private final Resource url; private final HttpHeader[] headers; protected abstract HttpUriRequest createRequest(String url, Request request); protected MocoRequestAction(final Resource url, final HttpHeader[] headers) { this.url = url; this.headers = headers; } @Override public final void execute(final Request request) { try (CloseableHttpClient client = HttpClients.createDefault()) { final HttpUriRequest actionRequest = prepareRequest(request); dump(actionRequest); final CloseableHttpResponse response = client.execute(actionRequest); dump(response); } catch (IOException e) { throw new MocoException(e); } } private void dump(final HttpUriRequest request) { final URIBuilder uriBuilder = new URIBuilder(request.getURI()); final DefaultHttpRequest.Builder builder = DefaultHttpRequest.builder() .withVersion(HttpProtocolVersion.versionOf(request.getProtocolVersion().toString())) .withUri(toPath(request.getURI())) .withQueries(asQueries(uriBuilder.getQueryParams())) .withMethod(HttpMethod.valueOf(request.getMethod().toUpperCase())) .withHeaders(asHeaders(request.getAllHeaders())); if (request instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; try { builder.withContent(MessageContent.content() .withContent(entityRequest.getEntity().getContent()) .build()); } catch (IOException e) { // IGNORE } } logger.info("Action Request:{}\n", requestDumper.dump(builder.build())); } private static String toPath(final URI uri) { final String path = uri.toString(); final int index = path.indexOf("?"); if (index >= 0) { return path.substring(0, index); } return path; } private Map<String, String[]> asQueries(final List<NameValuePair> queries) { final ArrayListMultimap<String, String> multimap = ArrayListMultimap.create(); for (NameValuePair query : queries) { multimap.put(query.getName(), query.getValue()); } Map<String, String[]> result = new HashMap<>(); for (String key : multimap.keys()) { final List<String> strings = multimap.get(key); result.put(key, strings.toArray(new String[0])); } return result; } private void dump(final CloseableHttpResponse response) throws IOException { final DefaultHttpResponse dumped = DefaultHttpResponse.builder() .withVersion(HttpProtocolVersion.versionOf(response.getProtocolVersion().toString())) .withStatus(response.getStatusLine().getStatusCode()) .withHeaders(asHeaders(response.getAllHeaders())) .withContent(MessageContent.content().withContent(response.getEntity().getContent()).build()) .build(); logger.info("Action Response: {}\n", responseDumper.dump(dumped)); } private Map<String, String> asHeaders(final Header[] allHeaders) { return Arrays.stream(allHeaders) .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue)); } private HttpUriRequest prepareRequest(final Request request) { HttpUriRequest httpRequest = createRequest(url.readFor(request).toString(), request); for (HttpHeader header : headers) { httpRequest.addHeader(header.getName(), header.getValue().readFor(request).toString()); } return httpRequest; } protected final Resource applyUrl(final MocoConfig config) { return this.url.apply(config); } protected final boolean isSameUrl(final Resource url) { return this.url == url; } protected final HttpHeader[] applyHeaders(final MocoConfig config) { HttpHeader[] appliedHeaders = new HttpHeader[this.headers.length]; boolean applied = false; for (int i = 0; i < headers.length; i++) { HttpHeader appliedHeader = headers[i].apply(config); if (!headers[i].equals(appliedHeader)) { applied = true; } appliedHeaders[i] = appliedHeader; } if (applied) { return appliedHeaders; } return this.headers; } protected final boolean isSameHeaders(final HttpHeader[] headers) { return this.headers == headers; } }
package hex.tree.gbm; import hex.Model; import hex.schemas.GBMV2; import hex.tree.*; import hex.tree.DTree.DecidedNode; import hex.tree.DTree.LeafNode; import hex.tree.DTree.UndecidedNode; import water.*; import water.fvec.Chunk; import water.fvec.Vec; import water.util.Log; import water.util.Timer; import water.util.ArrayUtils; /** Gradient Boosted Trees * * Based on "Elements of Statistical Learning, Second Edition, page 387" */ public class GBM extends SharedTree<GBMModel,GBMModel.GBMParameters,GBMModel.GBMOutput> { @Override public Model.ModelCategory[] can_build() { return new Model.ModelCategory[]{ Model.ModelCategory.Regression, Model.ModelCategory.Binomial, Model.ModelCategory.Multinomial, }; } // Called from an http request public GBM( GBMModel.GBMParameters parms) { super("GBM",parms); init(false); } @Override public GBMV2 schema() { return new GBMV2(); } /** Start the GBM training Job on an F/J thread. */ @Override public Job<GBMModel> trainModel() { return start(new GBMDriver(), _parms._ntrees/*work for progress bar*/); } @Override public Vec vresponse() { return super.vresponse() == null ? response() : super.vresponse(); } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the learning rate and loss family. */ @Override public void init(boolean expensive) { super.init(expensive); // Initialize response based on given loss function. // Regression: initially predict the response mean // Binomial: just class 0 (class 1 in the exact inverse prediction) // Multinomial: Class distribution which is not a single value. // However there is this weird tension on the initial value for // classification: If you guess 0's (no class is favored over another), // then with your first GBM tree you'll typically move towards the correct // answer a little bit (assuming you have decent predictors) - and // immediately the Confusion Matrix shows good results which gradually // improve... BUT the Means Squared Error will suck for unbalanced sets, // even as the CM is good. That's because we want the predictions for the // common class to be large and positive, and the rare class to be negative // and instead they start around 0. Guessing initial zero's means the MSE // is so bad, that the R^2 metric is typically negative (usually it's // between 0 and 1). // If instead you guess the mean (reversed through the loss function), then // the zero-tree GBM model reports an MSE equal to the response variance - // and an initial R^2 of zero. More trees gradually improves the R^2 as // expected. However, all the minority classes have large guesses in the // wrong direction, and it takes a long time (lotsa trees) to correct that // - so your CM sucks for a long time. double mean = 0; if (expensive) { mean = _response.mean(); _initialPrediction = _nclass == 1 ? mean : (_nclass == 2 ? -0.5 * Math.log(mean / (1.0 - mean)) : 0.0); if (_parms._loss == GBMModel.GBMParameters.Family.AUTO) { if (_nclass == 1) _parms._loss = GBMModel.GBMParameters.Family.gaussian; if (_nclass == 2) _parms._loss = GBMModel.GBMParameters.Family.bernoulli; if (_nclass >= 3) _parms._loss = GBMModel.GBMParameters.Family.multinomial; } } switch( _parms._loss ) { case bernoulli: if( _nclass != 2 /*&& !couldBeBool(_response)*/) error("_loss", "Binomial requires the response to be a 2-class categorical"); else if( _response != null ) // Bernoulli: initial prediction is log( mean(y)/(1-mean(y)) ) _initialPrediction = Math.log(mean / (1.0 - mean)); break; case multinomial: if (!isClassifier()) error("_loss", "Multinomial requires an enum response."); break; case gaussian: if (isClassifier()) error("_loss", "Gaussian requires the response to be numeric."); break; case AUTO: break; default: error("_loss","Invalid loss: " + _parms._loss); } if( !(0. < _parms._learn_rate && _parms._learn_rate <= 1.0) ) error("_learn_rate", "learn_rate must be between 0 and 1"); } private class GBMDriver extends Driver { @Override protected void buildModel() { final double init = _initialPrediction; if( init != 0.0 ) // Only non-zero for regression or bernoulli new MRTask() { @Override public void map(Chunk tree) { for( int i=0; i<tree._len; i++ ) tree.set(i, init); } }.doAll(vec_tree(_train,0)); // Only setting tree-column 0 // Reconstruct the working tree state from the checkpoint if( _parms._checkpoint ) { Timer t = new Timer(); new ResidualsCollector(_ncols, _nclass, _model._output._treeKeys).doAll(_train); Log.info("Reconstructing tree residuals stats from checkpointed model took " + t); } // Loop over the K trees for( int tid=0; tid<_parms._ntrees; tid++) { // During first iteration model contains 0 trees, then 1-tree, ... // No need to score a checkpoint with no extra trees added if( tid!=0 || !_parms._checkpoint ) { // do not make initial scoring if model already exist double training_r2 = doScoringAndSaveModel(false, false, false); if( training_r2 >= 0.999999 ) return; // Stop when approaching round-off error } // ESL2, page 387 // Step 2a: Compute prediction (prob distribution) from prior tree results: // Work <== f(Tree) new ComputeProb().doAll(_train); // ESL2, page 387 // Step 2b i: Compute residuals from the prediction (probability distribution) // Work <== f(Work) new ComputeRes().doAll(_train); // ESL2, page 387, Step 2b ii, iii, iv Timer kb_timer = new Timer(); buildNextKTrees(); Log.info((tid+1) + ". tree was built in " + kb_timer.toString()); GBM.this.update(1); if( !isRunning() ) return; // If canceled during building, do not bulkscore } // Final scoring (skip if job was cancelled) doScoringAndSaveModel(true, false, false); } // Compute Prediction from prior tree results. // Classification (multinomial): Probability Distribution of loglikelyhoods // Prob_k = exp(Work_k)/sum_all_K exp(Work_k) // Classification (bernoulli): Probability of y = 1 given logit link function // Prob_0 = 1/(1 + exp(Work)), Prob_1 = 1/(1 + exp(-Work)) // Regression: Just prior tree results // Work <== f(Tree) class ComputeProb extends MRTask<ComputeProb> { @Override public void map( Chunk chks[] ) { Chunk ys = chk_resp(chks); if( _parms._loss == GBMModel.GBMParameters.Family.bernoulli ) { Chunk tr = chk_tree(chks,0); Chunk wk = chk_work(chks,0); for( int row = 0; row < ys._len; row++) // wk.set(row, 1.0f/(1f+Math.exp(-tr.atd(row))) ); // Prob_1 wk.set(row, 1.0f / (1f + Math.exp(tr.atd(row)))); // Prob_0 } else if( _nclass > 1 ) { // Classification double fs[] = new double[_nclass+1]; for( int row=0; row<ys._len; row++ ) { double sum = score1(chks,fs,row); if( Double.isInfinite(sum) ) // Overflow (happens for constant responses) for( int k=0; k<_nclass; k++ ) chk_work(chks,k).set(row,Double.isInfinite(fs[k+1])?1.0f:0.0f); else for( int k=0; k<_nclass; k++ ) // Save as a probability distribution chk_work(chks,k).set(row,(float)(fs[k+1]/sum)); } } else { // Regression Chunk tr = chk_tree(chks,0); // Prior tree sums Chunk wk = chk_work(chks,0); // Predictions for( int row=0; row<ys._len; row++ ) wk.set(row,(float)tr.atd(row)); } } } // Compute Residuals from Actuals // Work <== f(Work) class ComputeRes extends MRTask<ComputeRes> { @Override public void map( Chunk chks[] ) { Chunk ys = chk_resp(chks); if( _parms._loss == GBMModel.GBMParameters.Family.bernoulli ) { for(int row = 0; row < ys._len; row++) { if( ys.isNA(row) ) continue; int y = (int)ys.at8(row); // zero-based response variable Chunk wk = chk_work(chks,0); // wk.set(row, y-(float)wk.atd(row)); // wk.atd(row) is Prob_1 wk.set(row, y-1f+(float)wk.atd(row)); // wk.atd(row) is Prob_0 } } else if( _nclass > 1 ) { // Classification for( int row=0; row<ys._len; row++ ) { if( ys.isNA(row) ) continue; int y = (int)ys.at8(row); // zero-based response variable // Actual is '1' for class 'y' and '0' for all other classes for( int k=0; k<_nclass; k++ ) { if( _model._output._distribution[k] != 0 ) { Chunk wk = chk_work(chks,k); wk.set(row, (y==k?1f:0f)-(float)wk.atd(row) ); } } } } else { // Regression Chunk wk = chk_work(chks,0); // Prediction==>Residuals for( int row=0; row<ys._len; row++ ) wk.set(row, (float)(ys.atd(row)-wk.atd(row)) ); } } } // Build the next k-trees, which is trying to correct the residual error from // the prior trees. From ESL2, page 387. Step 2b ii, iii. private void buildNextKTrees() { // We're going to build K (nclass) trees - each focused on correcting // errors for a single class. final DTree[] ktrees = new DTree[_nclass]; // Initial set of histograms. All trees; one leaf per tree (the root // leaf); all columns DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols]; // Adjust nbins for the top-levels final int top_level_extra_bins = 1<<10; int nbins = Math.max(top_level_extra_bins,_parms._nbins); for( int k=0; k<_nclass; k++ ) { // Initially setup as-if an empty-split had just happened if( _model._output._distribution[k] != 0 ) { // The Boolean Optimization // This optimization assumes the 2nd tree of a 2-class system is the // inverse of the first. This is false for DRF (and true for GBM) - // DRF picks a random different set of columns for the 2nd tree. if( k==1 && _nclass==2 ) continue; ktrees[k] = new DTree(_train._names,_ncols,(char)_parms._nbins,(char)_nclass,_parms._min_rows); new GBMUndecidedNode(ktrees[k],-1,DHistogram.initialHist(_train,_ncols,nbins,hcs[k][0],false) ); // The "root" node } } int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from here to tree._len // ESL2, page 387. Step 2b ii. // One Big Loop till the ktrees are of proper depth. // Adds a layer to the trees each pass. int depth=0; for( ; depth<_parms._max_depth; depth++ ) { if( !isRunning() ) return; hcs = buildLayer(_train, nbins, ktrees, leafs, hcs, false, false); // If we did not make any new splits, then the tree is split-to-death if( hcs == null ) break; } // Each tree bottomed-out in a DecidedNode; go 1 more level and insert // LeafNodes to hold predictions. for( int k=0; k<_nclass; k++ ) { DTree tree = ktrees[k]; if( tree == null ) continue; int leaf = leafs[k] = tree.len(); for( int nid=0; nid<leaf; nid++ ) { if( tree.node(nid) instanceof DecidedNode ) { DecidedNode dn = tree.decided(nid); if( dn._split._col == -1 ) { // No decision here, no row should have this NID now if( nid==0 ) // Handle the trivial non-splitting tree new GBMLeafNode(tree,-1,0); continue; } for( int i=0; i<dn._nids.length; i++ ) { int cnid = dn._nids[i]; if( cnid == -1 || // Bottomed out (predictors or responses known constant) tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth (tree.node(cnid) instanceof DecidedNode && // Or not possible to split ((DecidedNode)tree.node(cnid))._split._col==-1) ) dn._nids[i] = new GBMLeafNode(tree,nid).nid(); // Mark a leaf here } } } } // -- k-trees are done // ESL2, page 387. Step 2b iii. Compute the gammas, and store them back // into the tree leaves. Includes learn_rate. // For classification (bernoulli): // gamma_i = sum res_i / sum p_i*(1 - p_i) where p_i = y_i - res_i // For classification (multinomial): // gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|))) // For regression (gaussian): // gamma_i = sum res_i / count(res_i) GammaPass gp = new GammaPass(ktrees,leafs,_parms._loss == GBMModel.GBMParameters.Family.bernoulli).doAll(_train); double m1class = _nclass > 1 && _parms._loss != GBMModel.GBMParameters.Family.bernoulli ? (double)(_nclass-1)/_nclass : 1.0; // K-1/K for multinomial for( int k=0; k<_nclass; k++ ) { final DTree tree = ktrees[k]; if( tree == null ) continue; for( int i=0; i<tree._len-leafs[k]; i++ ) { float gf = (float)(_parms._learn_rate * m1class * gp._rss[k][i] / gp._gss[k][i]); if( gp._gss[k][i]==0 ) // Bad split; all corrections sum to zero gf = (float)(Math.signum(gp._rss[k][i])*1e4); // In the multinomial case, check for very large values (which will get exponentiated later) // Note that gss can be *zero* while rss is non-zero - happens when some rows in the same // split are perfectly predicted true, and others perfectly predicted false. if( _parms._loss == GBMModel.GBMParameters.Family.multinomial ) { if ( gf > 1e4 ) gf = 1e4f; // Cap prediction, will already overflow during Math.exp(gf) else if( gf < -1e4 ) gf = -1e4f; } assert !Float.isNaN(gf) && !Float.isInfinite(gf); ((LeafNode) tree.node(leafs[k] + i))._pred = gf; } } // ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the // new tree, in the 'tree' columns. Also, zap the NIDs for next pass. // Tree <== f(Tree) // Nids <== 0 new MRTask() { @Override public void map( Chunk chks[] ) { // For all tree/klasses for( int k=0; k<_nclass; k++ ) { final DTree tree = ktrees[k]; if( tree == null ) continue; final Chunk nids = chk_nids(chks,k); final Chunk ct = chk_tree(chks,k); for( int row=0; row<nids._len; row++ ) { int nid = (int)nids.at8(row); if( nid < 0 ) continue; // Prediction stored in Leaf is cut to float to be deterministic in reconstructing // <tree_klazz> fields from tree prediction ct.set(row, (float)(ct.atd(row) + ((LeafNode)tree.node(nid))._pred)); nids.set(row, 0); } } } }.doAll(_train); // Collect leaves stats for (int i=0; i<ktrees.length; i++) if( ktrees[i] != null ) ktrees[i]._leaves = ktrees[i].len() - leafs[i]; // DEBUG: Print the generated K trees //printGenerateTrees(ktrees); // Grow the model by K-trees _model._output.addKTrees(ktrees); } // ESL2, page 387. Step 2b iii. // Nids <== f(Nids) private class GammaPass extends MRTask<GammaPass> { final DTree _trees[]; // Read-only, shared (except at the histograms in the Nodes) final int _leafs[]; // Number of active leaves (per tree) final boolean _isBernoulli; // Per leaf: sum(res); double _rss[/*tree/klass*/][/*tree-relative node-id*/]; // Per leaf: multinomial: sum(|res|*1-|res|), gaussian: sum(1), bernoulli: sum((y-res)*(1-y+res)) double _gss[/*tree/klass*/][/*tree-relative node-id*/]; GammaPass(DTree trees[], int leafs[], boolean isBernoulli) { _leafs=leafs; _trees=trees; _isBernoulli = isBernoulli; } @Override public void map( Chunk[] chks ) { _gss = new double[_nclass][]; _rss = new double[_nclass][]; final Chunk resp = chk_resp(chks); // Response for this frame // For all tree/klasses for( int k=0; k<_nclass; k++ ) { final DTree tree = _trees[k]; final int leaf = _leafs[k]; if( tree == null ) continue; // Empty class is ignored // A leaf-biased array of all active Tree leaves. final double gs[] = _gss[k] = new double[tree._len-leaf]; final double rs[] = _rss[k] = new double[tree._len-leaf]; final Chunk nids = chk_nids(chks,k); // Node-ids for this tree/class final Chunk ress = chk_work(chks,k); // Residuals for this tree/class // If we have all constant responses, then we do not split even the // root and the residuals should be zero. if( tree.root() instanceof LeafNode ) continue; for( int row=0; row<nids._len; row++ ) { // For all rows int nid = (int)nids.at8(row); // Get Node to decide from if( nid < 0 ) continue; // Missing response if( tree.node(nid) instanceof UndecidedNode ) // If we bottomed out the tree nid = tree.node(nid)._pid; // Then take parent's decision DecidedNode dn = tree.decided(nid); // Must have a decision point if( dn._split._col == -1 ) // Unable to decide? dn = tree.decided(dn._pid); // Then take parent's decision int leafnid = dn.ns(chks,row); // Decide down to a leafnode assert leaf <= leafnid && leafnid < tree._len : "leaf: " + leaf + " leafnid: " + leafnid + " tree._len: " + tree._len + "\ndn: " + dn; assert tree.node(leafnid) instanceof LeafNode; // Note: I can which leaf/region I end up in, but I do not care for // the prediction presented by the tree. For GBM, we compute the // sum-of-residuals (and sum/abs/mult residuals) for all rows in the // leaf, and get our prediction from that. nids.set(row, leafnid); assert !ress.isNA(row); // Compute numerator (rs) and denominator (gs) of gamma double res = ress.atd(row); double ares = Math.abs(res); if( _isBernoulli ) { double prob = resp.atd(row) - res; gs[leafnid-leaf] += prob*(1-prob); } else gs[leafnid-leaf] += _nclass > 1 ? ares*(1-ares) : 1; rs[leafnid-leaf] += res; } } } @Override public void reduce( GammaPass gp ) { ArrayUtils.add(_gss,gp._gss); ArrayUtils.add(_rss,gp._rss); } } @Override protected GBMModel makeModel( Key modelKey, GBMModel.GBMParameters parms, double mse_train, double mse_valid ) { return new GBMModel(modelKey,parms,new GBMModel.GBMOutput(GBM.this,mse_train,mse_valid)); } } @Override protected DecidedNode makeDecided( UndecidedNode udn, DHistogram hs[] ) { return new GBMDecidedNode(udn,hs); } // GBM DTree decision node: same as the normal DecidedNode, but // specifies a decision algorithm given complete histograms on all // columns. GBM algo: find the lowest error amongst *all* columns. static class GBMDecidedNode extends DecidedNode { GBMDecidedNode( UndecidedNode n, DHistogram[] hs ) { super(n,hs); } @Override public UndecidedNode makeUndecidedNode(DHistogram[] hs ) { return new GBMUndecidedNode(_tree,_nid,hs); } // Find the column with the best split (lowest score). Unlike RF, GBM // scores on all columns and selects splits on all columns. @Override public DTree.Split bestCol( UndecidedNode u, DHistogram[] hs ) { DTree.Split best = new DTree.Split(-1,-1,null,(byte)0,Double.MAX_VALUE,Double.MAX_VALUE,Double.MAX_VALUE,0L,0L,0,0); if( hs == null ) return best; for( int i=0; i<hs.length; i++ ) { if( hs[i]==null || hs[i].nbins() <= 1 ) continue; DTree.Split s = hs[i].scoreMSE(i,_tree._min_rows); if( s == null ) continue; if( s.se() < best.se() ) best = s; if( s.se() <= 0 ) break; // No point in looking further! } return best; } } // GBM DTree undecided node: same as the normal UndecidedNode, but specifies // a list of columns to score on now, and then decide over later. // GBM algo: use all columns static class GBMUndecidedNode extends UndecidedNode { GBMUndecidedNode( DTree tree, int pid, DHistogram hs[] ) { super(tree,pid,hs); } // Randomly select mtry columns to 'score' in following pass over the data. // In GBM, we use all columns (as opposed to RF, which uses a random subset). @Override public int[] scoreCols( DHistogram[] hs ) { return null; } } static class GBMLeafNode extends LeafNode { GBMLeafNode( DTree tree, int pid ) { super(tree,pid); } GBMLeafNode( DTree tree, int pid, int nid ) { super(tree, pid, nid); } // Insert just the predictions: a single byte/short if we are predicting a // single class, or else the full distribution. @Override protected AutoBuffer compress(AutoBuffer ab) { assert !Double.isNaN(_pred); return ab.put4f(_pred); } @Override protected int size() { return 4; } } // Read the 'tree' columns, do model-specific math and put the results in the // fs[] array, and return the sum. Dividing any fs[] element by the sum // turns the results into a probability distribution. @Override protected double score1( Chunk chks[], double fs[/*nclass*/], int row ) { if( _parms._loss == GBMModel.GBMParameters.Family.bernoulli ) { fs[1] = 1.0/(1.0+Math.exp(chk_tree(chks,0).atd(row))); fs[2] = 1.0-fs[1]; return 1; // f2 = 1.0 - f1; so f1+f2 = 1.0 } if( _nclass == 1 ) // Regression return fs[0]=chk_tree(chks,0).atd(row); if( _nclass == 2 ) { // The Boolean Optimization // This optimization assumes the 2nd tree of a 2-class system is the // inverse of the first. Fill in the missing tree fs[1] = Math.exp(chk_tree(chks,0).atd(row)); fs[2] = 1.0/fs[1]; return fs[1]+fs[2]; } // Multinomial loss function; sum(exp(data)). Load tree data for( int k=0; k<_nclass; k++ ) fs[k+1]=chk_tree(chks,k).atd(row); // Rescale to avoid Infinities; return sum(exp(data)) return hex.genmodel.GenModel.log_rescale(fs); } }
package name.abuchen.portfolio.model; import java.io.Serializable; import java.time.LocalDate; import java.util.Comparator; import java.util.ResourceBundle; import name.abuchen.portfolio.money.Money; import name.abuchen.portfolio.money.MoneyCollectors; public class AccountTransaction extends Transaction { public enum Type { DEPOSIT(false), REMOVAL(true), INTEREST(false), DIVIDENDS(false), FEES(true), TAXES(true), TAX_REFUND( false), BUY(true), SELL(false), TRANSFER_IN(false), TRANSFER_OUT(true); private static final ResourceBundle RESOURCES = ResourceBundle.getBundle("name.abuchen.portfolio.model.labels"); //$NON-NLS-1$ private final boolean isDebit; private Type(boolean isDebit) { this.isDebit = isDebit; } public boolean isDebit() { return isDebit; } public boolean isCredit() { return !isDebit; } @Override public String toString() { return RESOURCES.getString("account." + name()); //$NON-NLS-1$ } } /** * Comparator to sort by date, amount, and type in order to have a stable * enough sort order to calculate the balance per transaction. */ public static final class ByDateAmountAndType implements Comparator<AccountTransaction>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(AccountTransaction t1, AccountTransaction t2) { int compare = t1.getDate().compareTo(t2.getDate()); if (compare != 0) return compare; compare = Long.compare(t1.getAmount(), t2.getAmount()); if (compare != 0) return compare; return t1.getType().compareTo(t2.getType()); } } private Type type; public AccountTransaction() { // needed for xstream de-serialization } public AccountTransaction(LocalDate date, String currencyCode, long amount, Security security, Type type) { super(date, currencyCode, amount, security, 0, null); this.type = type; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } /** * Returns the gross value, i.e. the value including taxes. See * {@link #getGrossValue()}. */ public long getGrossValueAmount() { // at the moment, only dividend transaction support taxes if (!(this.type == Type.DIVIDENDS || this.type == Type.INTEREST)) throw new UnsupportedOperationException(); long taxes = getUnits().filter(u -> u.getType() == Unit.Type.TAX) .collect(MoneyCollectors.sum(getCurrencyCode(), u -> u.getAmount())).getAmount(); return getAmount() + taxes; } /** * Returns the gross value, i.e. the value before taxes are applied. At the * moment, only dividend transactions are supported. */ public Money getGrossValue() { return Money.of(getCurrencyCode(), getGrossValueAmount()); } }
package water.api; import water.*; import water.H2O.H2OCountedCompleter; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OKeyNotFoundArgumentException; import water.exceptions.H2OKeyWrongTypeArgumentException; import water.util.Log; import water.util.PojoUtils; import water.util.ReflectionUtils; import water.util.annotations.IgnoreJRERequirement; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; public class Handler extends H2OCountedCompleter<Handler> { public static Class<? extends Schema> getHandlerMethodInputSchema(Method method) { return (Class<? extends Schema>)ReflectionUtils.findMethodParameterClass(method, 1); } public static Class<? extends Schema> getHandlerMethodOutputSchema(Method method) { return (Class<? extends Schema>)ReflectionUtils.findMethodOutputClass(method); } // Invoke the handler with parameters. Can throw any exception the called handler can throw. Schema handle(int version, Route route, Properties parms, String post_body) throws Exception { Class<? extends Schema> handler_schema_class = getHandlerMethodInputSchema(route._handler_method); Schema schema = Schema.newInstance(handler_schema_class); // If the schema has a real backing class fill from it to get the default field values: Class<? extends Iced> iced_class = schema.getImplClass(); if (iced_class != Iced.class) { Iced defaults = schema.createImpl(); schema.fillFromImpl(defaults); } boolean is_post_of_json = (null != post_body); // Fill from http request params: schema = schema.fillFromParms(parms, !is_post_of_json); if (schema == null) throw H2O.fail("fillFromParms returned a null schema for version: " + version + " in: " + this.getClass() + " with params: " + parms); // Fill from JSON body, if there is one. NOTE: there should *either* be a JSON body *or* parms, // with the exception of control-type query parameters. // We use PojoUtils.fillFromJson() rather than just using "schema = Gson.fromJson(post_body)" // so that we have defaults: we only overwrite fields that the client has specified. if (is_post_of_json) { PojoUtils.fillFromJson(schema, post_body); } // NOTE! The handler method is free to modify the input schema and hand it back. Schema result = null; try { route._handler_method.setAccessible(true); result = (Schema)route._handler_method.invoke(this, version, schema); } // Exception thrown out of the invoked method turn into InvocationTargetException // rather uselessly. Peel out the original exception & throw it. catch( InvocationTargetException ite ) { Throwable t = ite.getCause(); if( t instanceof RuntimeException ) throw (RuntimeException)t; if( t instanceof Error ) throw (Error)t; throw new RuntimeException(t); } // Version-specific unwind from the Iced back into the Schema return result; } @IgnoreJRERequirement protected StringBuffer markdown(Handler handler, int version, StringBuffer docs, String filename) { // TODO: version handling StringBuffer sb = new StringBuffer(); Path path = Paths.get(filename); try { sb.append(Files.readAllBytes(path)); } catch (IOException e) { Log.warn("Caught IOException trying to read doc file: ", path); } if (docs != null) docs.append(sb); return sb; } public static <T extends Keyed> T getFromDKV(String param_name, String key, Class<T> klazz) { return getFromDKV(param_name, Key.make(key), klazz); } public static <T extends Keyed> T getFromDKV(String param_name, Key key, Class<T> klazz) { if (key == null) throw new H2OIllegalArgumentException(param_name, "Handler.getFromDKV()", "null"); Value v = DKV.get(key); if (v == null) throw new H2OKeyNotFoundArgumentException(param_name, key.toString()); try { return klazz.cast(v.get()); } catch (ClassCastException e) { throw new H2OKeyWrongTypeArgumentException(param_name, key.toString(), klazz, v.get().getClass()); } } }
package net.nemerosa.ontrack.model.security; import lombok.Data; import java.io.Serializable; import java.util.Set; /** * A global role defines the association between a name, a set of * {@linkplain net.nemerosa.ontrack.model.security.GlobalFunction global functions} * and a set of {@linkplain net.nemerosa.ontrack.model.security.ProjectFunction project functions} * that are attributed for all projects. */ @Data public class GlobalRole implements Serializable { /** * Global role's identifier */ private final String id; /** * Global role's name */ private final String name; /** * Description of the role */ private final String description; /** * Global functions */ private final Set<Class<? extends GlobalFunction>> globalFunctions; /** * Project functions to grant for all projects */ private final Set<Class<? extends ProjectFunction>> projectFunctions; public boolean isGlobalFunctionGranted(Class<? extends GlobalFunction> fn) { return globalFunctions.contains(fn); } public boolean isProjectFunctionGranted(Class<? extends ProjectFunction> fn) { return projectFunctions.stream().anyMatch(fn::isAssignableFrom); } }
package rxbonjour; import android.content.Context; import android.os.Build; import rxbonjour.exc.TypeMalformedException; import rxbonjour.internal.BonjourDiscovery; import rxbonjour.internal.BonjourSchedulers; import rxbonjour.internal.JBBonjourDiscovery; import rxbonjour.internal.SupportBonjourDiscovery; import rxbonjour.model.BonjourEvent; import static android.os.Build.VERSION_CODES.JELLY_BEAN; /** * RxBonjour: * Enables clients to perform network service discovery for Bonjour devices using Reactive Extensions. */ public final class RxBonjour { private static final String TYPE_PATTERN = "_[a-zA-Z0-9\\-]+\\.(_tcp|_udp)(\\.[a-zA-Z0-9\\-]+\\.)?"; private RxBonjour() { throw new AssertionError("no instances"); } public static rx.Observable<BonjourEvent> startDiscovery(Context context, String type) { return startDiscovery(context, type, false); } public static rx.Observable<BonjourEvent> startDiscovery(Context context, String type, boolean useNsdManager) { // Verify input if (!isBonjourType(type)) throw new TypeMalformedException(type); // Choose discovery strategy BonjourDiscovery discovery; if (useNsdManager && Build.VERSION.SDK_INT >= JELLY_BEAN) { discovery = new JBBonjourDiscovery(); } else { discovery = new SupportBonjourDiscovery(); } // Create the discovery Observable and pre-configure it return discovery.start(context, type) .compose(BonjourSchedulers.<BonjourEvent>startSchedulers()); } /** * Checks the provided type String against Bonjour specifications, and returns whether or not the type is valid. * * @param type Type of service to check * @return True if the type refers to a valid Bonjour type, false otherwise */ public static boolean isBonjourType(String type) { return type.matches(TYPE_PATTERN); } }
import java.io.IOException; import java.lang.Integer; import java.util.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.*; //import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class TopWords{ public static class TextArrayWritable extends ArrayWritable{ public TextArrayWritable(){ super(Text.class); } public TextArrayWritable(String[] strings){ super(Text.class); Text[] texts = new Text[strings.length]; for (int i = 0; i < strings.length; i++ ) { texts[i] = new Text(strings[i]); } } } public static class WordCountMap extends Mapper<Object,Text,Text,IntWritable>{ List<String> commonWords = Arrays.asList("the","a","an","and","of","to","in","am","is","are","at","not"); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException{ String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line,"\t,;.?!-:@[] () {}_*/"); while(tokenizer.hasMoreTokens()){ String nextToken = tokenizer.nextToken().trim().toLowerCase(); if(!commonWords.contains(nextToken)){ context.write(new Text(nextToken), new IntWritable(1)); } } } } public static class WordCountReduce extends Reducer<Text,IntWritable,Text,IntWritable>{ @Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException{ int sum = 0; for(IntWritable val : values){ sum += val.get(); } context.write(key,new IntWritable(sum)); } } public static class TopWordsMap extends Mapper<Text,Text,NullWritable,TextArrayWritable>{ private TreeSet<Pair<Integer,String>> countToWordMap = new TreeSet<Pair<Integer,String>>(); @Override public void map(Text key, Text value, Context context) throws IOException, InterruptedException{ Integer count = Integer.parseInt(value.toString()); String word = key.toString(); countToWordMap.add(new Pair<Integer,String>(count,word)); if (countToWordMap.size() > 10) { countToWordMap.remove(countToWordMap.first()); } } @Override protected void cleanup(Context context) throws IOException, InterruptedException{ for (Pair<Integer,String> item: countToWordMap) { String[] strings = {item.second,item.first.toString()}; TextArrayWritable val = new TextArrayWritable(strings); context.write(NullWritable.get(),val); } } } public static class TopWordsReduce extends Reducer<NullWritable, TextArrayWritable, Text, IntWritable> { private TreeSet<Pair<Integer, String>> countToWordMap = new TreeSet<Pair<Integer, String>>(); @Override public void reduce(NullWritable key, Iterable<TextArrayWritable> values, Context context) throws IOException, InterruptedException { for (TextArrayWritable val: values) { Text[] pair= (Text[]) val.toArray(); String word = pair[0].toString(); Integer count = Integer.parseInt(pair[1].toString()); countToWordMap.add(new Pair<Integer, String>(count, word)); if (countToWordMap.size() > 10) { countToWordMap.remove(countToWordMap.first()); } } for (Pair<Integer, String> item: countToWordMap) { Text word = new Text(item.second); IntWritable value = new IntWritable(item.first); context.write(word, value); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); Path tmpPath = new Path("/w1/tmp"); fs.delete(tmpPath, true); Job jobA = Job.getInstance(conf, "wordcount"); jobA.setOutputKeyClass(Text.class); jobA.setOutputValueClass(IntWritable.class); jobA.setMapperClass(WordCountMap.class); jobA.setReducerClass(WordCountReduce.class); FileInputFormat.setInputPaths(jobA, new Path(args[0])); FileOutputFormat.setOutputPath(jobA, tmpPath); jobA.setJarByClass(TopWords.class); jobA.waitForCompletion(true); Job jobB = Job.getInstance(conf, "Top Words"); jobB.setOutputKeyClass(Text.class); jobB.setOutputValueClass(IntWritable.class); jobB.setMapOutputKeyClass(NullWritable.class); jobB.setMapOutputValueClass(TextArrayWritable.class); jobB.setMapperClass(TopWordsMap.class); jobB.setReducerClass(TopWordsReduce.class); jobB.setNumReduceTasks(1); FileInputFormat.setInputPaths(jobB, tmpPath); FileOutputFormat.setOutputPath(jobB, new Path(args[1])); jobB.setInputFormatClass(KeyValueTextInputFormat.class); jobB.setOutputFormatClass(TextOutputFormat.class); jobB.setJarByClass(TopWords.class); System.exit(jobB.waitForCompletion(true) ? 0 : 1); } } class Pair<A extends Comparable<? super A>, B extends Comparable<? super B>> implements Comparable<Pair<A, B>> { public final A first; public final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public static <A extends Comparable<? super A>, B extends Comparable<? super B>> Pair<A, B> of(A first, B second) { return new Pair<A, B>(first, second); } @Override public int compareTo(Pair<A, B> o) { int cmp = o == null ? 1 : (this.first).compareTo(o.first); return cmp == 0 ? (this.second).compareTo(o.second) : cmp; } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair<?, ?>) obj).first) && equal(second, ((Pair<?, ?>) obj).second); } private boolean equal(Object o1, Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
package org.opennms.web.rest; import java.text.ParseException; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.joda.time.Duration; import org.opennms.netmgt.provision.persist.ForeignSourceRepository; import org.opennms.netmgt.provision.persist.StringIntervalPropertyEditor; import org.opennms.netmgt.provision.persist.foreignsource.DetectorCollection; import org.opennms.netmgt.provision.persist.foreignsource.DetectorWrapper; import org.opennms.netmgt.provision.persist.foreignsource.ForeignSource; import org.opennms.netmgt.provision.persist.foreignsource.ForeignSourceCollection; import org.opennms.netmgt.provision.persist.foreignsource.PluginConfig; import org.opennms.netmgt.provision.persist.foreignsource.PolicyCollection; import org.opennms.netmgt.provision.persist.foreignsource.PolicyWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.sun.jersey.spi.resource.PerRequest; @Component @PerRequest @Scope("prototype") @Path("foreignSources") public class ForeignSourceRestService extends OnmsRestService { private static final Logger LOG = LoggerFactory.getLogger(ForeignSourceRestService.class); @Autowired @Qualifier("pending") private ForeignSourceRepository m_pendingForeignSourceRepository; @Autowired @Qualifier("deployed") private ForeignSourceRepository m_deployedForeignSourceRepository; @Context UriInfo m_uriInfo; @Context HttpHeaders m_headers; @Context SecurityContext m_securityContext; /** * <p>getDefaultForeignSource</p> * * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.ForeignSource} object. * @throws java.text.ParseException if any. */ @GET @Path("default") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public ForeignSource getDefaultForeignSource() throws ParseException { readLock(); try { m_deployedForeignSourceRepository.flush(); return m_deployedForeignSourceRepository.getDefaultForeignSource(); } finally { readUnlock(); } } /** * Returns all the deployed foreign sources * * @return Collection of OnmsForeignSources (ready to be XML-ified) * @throws java.text.ParseException if any. */ @GET @Path("deployed") public ForeignSourceCollection getDeployedForeignSources() throws ParseException { readLock(); try { m_deployedForeignSourceRepository.flush(); return new ForeignSourceCollection(m_deployedForeignSourceRepository.getForeignSources()); } finally { readUnlock(); } } /** * returns a plaintext string being the number of pending foreign sources * * @return a int. */ @GET @Path("deployed/count") @Produces(MediaType.TEXT_PLAIN) public String getDeployedCount() { readLock(); try { m_pendingForeignSourceRepository.flush(); return Integer.toString(m_pendingForeignSourceRepository.getForeignSourceCount()); } finally { readUnlock(); } } /** * Returns the union of deployed and pending foreign sources * * @return Collection of OnmsForeignSources (ready to be XML-ified) * @throws java.text.ParseException if any. */ @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public ForeignSourceCollection getForeignSources() throws ParseException { readLock(); try { final Set<ForeignSource> foreignSources = new TreeSet<ForeignSource>(); for (final String fsName : getActiveForeignSourceNames()) { foreignSources.add(getActiveForeignSource(fsName)); } return new ForeignSourceCollection(foreignSources); } finally { readUnlock(); } } /** * returns a plaintext string being the number of pending foreign sources * * @return a int. * @throws java.text.ParseException if any. */ @GET @Path("count") @Produces(MediaType.TEXT_PLAIN) public String getTotalCount() throws ParseException { readLock(); try { return Integer.toString(getActiveForeignSourceNames().size()); } finally { readUnlock(); } } /** * Returns the requested {@link ForeignSource} * * @param foreignSource the foreign source name * @return the foreign source */ @GET @Path("{foreignSource}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public ForeignSource getForeignSource(@PathParam("foreignSource") String foreignSource) { readLock(); try { return getActiveForeignSource(foreignSource); } finally { readUnlock(); } } /** * <p>getDetectors</p> * * @param foreignSource a {@link java.lang.String} object. * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.DetectorCollection} object. */ @GET @Path("{foreignSource}/detectors") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public DetectorCollection getDetectors(@PathParam("foreignSource") String foreignSource) { readLock(); try { return new DetectorCollection(getActiveForeignSource(foreignSource).getDetectors()); } finally { readUnlock(); } } /** * <p>getDetector</p> * * @param foreignSource a {@link java.lang.String} object. * @param detector a {@link java.lang.String} object. * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.DetectorWrapper} object. */ @GET @Path("{foreignSource}/detectors/{detector}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public DetectorWrapper getDetector(@PathParam("foreignSource") String foreignSource, @PathParam("detector") String detector) { readLock(); try { for (final PluginConfig pc : getActiveForeignSource(foreignSource).getDetectors()) { if (pc.getName().equals(detector)) { return new DetectorWrapper(pc); } } return null; } finally { readUnlock(); } } /** * <p>getPolicies</p> * * @param foreignSource a {@link java.lang.String} object. * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.PolicyCollection} object. */ @GET @Path("{foreignSource}/policies") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public PolicyCollection getPolicies(@PathParam("foreignSource") String foreignSource) { readLock(); try { return new PolicyCollection(getActiveForeignSource(foreignSource).getPolicies()); } finally { readUnlock(); } } /** * <p>getPolicy</p> * * @param foreignSource a {@link java.lang.String} object. * @param policy a {@link java.lang.String} object. * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.PolicyWrapper} object. */ @GET @Path("{foreignSource}/policies/{policy}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) public PolicyWrapper getPolicy(@PathParam("foreignSource") String foreignSource, @PathParam("policy") String policy) { readLock(); try { for (final PluginConfig pc : getActiveForeignSource(foreignSource).getPolicies()) { if (pc.getName().equals(policy)) { return new PolicyWrapper(pc); } } return null; } finally { readUnlock(); } } /** * <p>addForeignSource</p> * * @param foreignSource a {@link org.opennms.netmgt.provision.persist.foreignsource.ForeignSource} object. * @return a {@link javax.ws.rs.core.Response} object. */ @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) @Transactional public Response addForeignSource(ForeignSource foreignSource) { writeLock(); try { LOG.debug("addForeignSource: Adding foreignSource {}", foreignSource.getName()); m_pendingForeignSourceRepository.save(foreignSource); return Response.seeOther(getRedirectUri(m_uriInfo, foreignSource.getName())).build(); } finally { writeUnlock(); } } /** * <p>addDetector</p> * * @param foreignSource a {@link java.lang.String} object. * @param detector a {@link org.opennms.netmgt.provision.persist.foreignsource.DetectorWrapper} object. * @return a {@link javax.ws.rs.core.Response} object. */ @POST @Path("{foreignSource}/detectors") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) @Transactional public Response addDetector(@PathParam("foreignSource") String foreignSource, DetectorWrapper detector) { writeLock(); try { LOG.debug("addDetector: Adding detector {}", detector.getName()); ForeignSource fs = getActiveForeignSource(foreignSource); fs.updateDateStamp(); fs.addDetector(detector); m_pendingForeignSourceRepository.save(fs); return Response.seeOther(getRedirectUri(m_uriInfo, detector.getName())).build(); } finally { writeUnlock(); } } /** * <p>addPolicy</p> * * @param foreignSource a {@link java.lang.String} object. * @param policy a {@link org.opennms.netmgt.provision.persist.foreignsource.PolicyWrapper} object. * @return a {@link javax.ws.rs.core.Response} object. */ @POST @Path("{foreignSource}/policies") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML}) @Transactional public Response addPolicy(@PathParam("foreignSource") String foreignSource, PolicyWrapper policy) { writeLock(); try { LOG.debug("addPolicy: Adding policy {}", policy.getName()); ForeignSource fs = getActiveForeignSource(foreignSource); fs.updateDateStamp(); fs.addPolicy(policy); m_pendingForeignSourceRepository.save(fs); return Response.seeOther(getRedirectUri(m_uriInfo, policy.getName())).build(); } finally { writeUnlock(); } } /** * <p>updateForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. * @param params a {@link org.opennms.web.rest.MultivaluedMapImpl} object. * @return a {@link javax.ws.rs.core.Response} object. */ @PUT @Path("{foreignSource}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Transactional public Response updateForeignSource(@PathParam("foreignSource") String foreignSource, MultivaluedMapImpl params) { writeLock(); try { ForeignSource fs = getActiveForeignSource(foreignSource); LOG.debug("updateForeignSource: updating foreign source {}", foreignSource); if (params.isEmpty()) return Response.seeOther(getRedirectUri(m_uriInfo)).build(); final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(fs); wrapper.registerCustomEditor(Duration.class, new StringIntervalPropertyEditor()); for(final String key : params.keySet()) { if (wrapper.isWritableProperty(key)) { Object value = null; String stringValue = params.getFirst(key); value = wrapper.convertIfNecessary(stringValue, (Class<?>)wrapper.getPropertyType(key)); wrapper.setPropertyValue(key, value); } } LOG.debug("updateForeignSource: foreign source {} updated", foreignSource); fs.updateDateStamp(); m_pendingForeignSourceRepository.save(fs); return Response.seeOther(getRedirectUri(m_uriInfo)).build(); } finally { writeUnlock(); } } /** * <p>deletePendingForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.Response} object. */ @DELETE @Path("{foreignSource}") @Transactional public Response deletePendingForeignSource(@PathParam("foreignSource") String foreignSource) { writeLock(); try { ForeignSource fs = getForeignSource(foreignSource); LOG.debug("deletePendingForeignSource: deleting foreign source {}", foreignSource); m_pendingForeignSourceRepository.delete(fs); return Response.ok().build(); } finally { writeUnlock(); } } /** * <p>deleteDeployedForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.Response} object. */ @DELETE @Path("deployed/{foreignSource}") @Transactional public Response deleteDeployedForeignSource(@PathParam("foreignSource") String foreignSource) { writeLock(); try { ForeignSource fs = getForeignSource(foreignSource); LOG.debug("deleteDeployedForeignSource: deleting foreign source {}", foreignSource); m_deployedForeignSourceRepository.delete(fs); return Response.ok().build(); } finally { writeUnlock(); } } /** * <p>deleteDetector</p> * * @param foreignSource a {@link java.lang.String} object. * @param detector a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.Response} object. */ @DELETE @Path("{foreignSource}/detectors/{detector}") @Transactional public Response deleteDetector(@PathParam("foreignSource") String foreignSource, @PathParam("detector") String detector) { writeLock(); try { ForeignSource fs = getActiveForeignSource(foreignSource); List<PluginConfig> detectors = fs.getDetectors(); PluginConfig removed = removeEntry(detectors, detector); if (removed != null) { fs.updateDateStamp(); fs.setDetectors(detectors); m_pendingForeignSourceRepository.save(fs); return Response.ok().build(); } return Response.notModified().build(); } finally { writeUnlock(); } } /** * <p>deletePolicy</p> * * @param foreignSource a {@link java.lang.String} object. * @param policy a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.Response} object. */ @DELETE @Path("{foreignSource}/policies/{policy}") @Transactional public Response deletePolicy(@PathParam("foreignSource") String foreignSource, @PathParam("policy") String policy) { writeLock(); try { ForeignSource fs = getActiveForeignSource(foreignSource); List<PluginConfig> policies = fs.getPolicies(); PluginConfig removed = removeEntry(policies, policy); if (removed != null) { fs.updateDateStamp(); fs.setPolicies(policies); m_pendingForeignSourceRepository.save(fs); return Response.ok().build(); } return Response.notModified().build(); } finally { writeUnlock(); } } private PluginConfig removeEntry(List<PluginConfig> plugins, String name) { PluginConfig removed = null; java.util.Iterator<PluginConfig> i = plugins.iterator(); while (i.hasNext()) { PluginConfig pc = i.next(); if (pc.getName().equals(name)) { removed = pc; i.remove(); break; } } return removed; } private Set<String> getActiveForeignSourceNames() { Set<String> fsNames = m_pendingForeignSourceRepository.getActiveForeignSourceNames(); fsNames.addAll(m_deployedForeignSourceRepository.getActiveForeignSourceNames()); return fsNames; } private ForeignSource getActiveForeignSource(String foreignSourceName) { ForeignSource fs = m_pendingForeignSourceRepository.getForeignSource(foreignSourceName); if (fs.isDefault()) { return m_deployedForeignSourceRepository.getForeignSource(foreignSourceName); } return fs; } }
package org.eclipse.egit.ui.internal.commit; import static java.util.Arrays.asList; import static org.eclipse.egit.ui.UIPreferences.THEME_DiffAddBackgroundColor; import static org.eclipse.egit.ui.UIPreferences.THEME_DiffRemoveBackgroundColor; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.core.AdapterUtils; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIUtils; import org.eclipse.egit.ui.internal.UIText; import org.eclipse.egit.ui.internal.commit.DiffRegionFormatter.DiffRegion; import org.eclipse.egit.ui.internal.commit.DiffRegionFormatter.FileDiffRegion; import org.eclipse.egit.ui.internal.history.FileDiff; import org.eclipse.egit.ui.internal.repository.RepositoriesView; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceStore; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.IVerticalRulerColumn; import org.eclipse.jface.text.source.projection.ProjectionAnnotation; import org.eclipse.jface.text.source.projection.ProjectionSupport; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.team.ui.history.IHistoryView; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.progress.UIJob; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.AbstractDocumentProvider; import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.themes.IThemeManager; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; /** * A {@link TextEditor} wrapped as an {@link IFormPage} and specialized to * showing a unified diff of a whole commit. The editor has an associated * {@link DiffEditorOutlinePage}. */ public class DiffEditorPage extends TextEditor implements IFormPage, IShowInSource, IShowInTargetList { private static final String ADD_ANNOTATION_TYPE = "org.eclipse.egit.ui.commitEditor.diffAdded"; //$NON-NLS-1$ private static final String REMOVE_ANNOTATION_TYPE = "org.eclipse.egit.ui.commitEditor.diffRemoved"; //$NON-NLS-1$ private FormEditor formEditor; private String title; private String pageId; private int pageIndex = -1; private Control textControl; private DiffEditorOutlinePage outlinePage; private Annotation[] currentFoldingAnnotations; private Annotation[] currentOverviewAnnotations; /** An {@link IPreferenceStore} for the annotation colors.*/ private ThemePreferenceStore overviewStore; private FileDiffRegion currentFileDiffRange; private OldNewLogicalLineNumberRulerColumn lineNumberColumn; private boolean plainLineNumbers = false; /** * Creates a new {@link DiffEditorPage} with the given id and title, which * is shown on the page's tab. * * @param editor * containing this page * @param id * of the page * @param title * of the page */ public DiffEditorPage(FormEditor editor, String id, String title) { pageId = id; this.title = title; setPartName(title); initialize(editor); } /** * Creates a new {@link DiffEditorPage} with default id and title. * * @param editor * containing the page */ public DiffEditorPage(FormEditor editor) { this(editor, "diffPage", UIText.DiffEditorPage_Title); //$NON-NLS-1$ } @SuppressWarnings("unchecked") @Override public Object getAdapter(Class adapter) { // TODO Switch to generified signature once EGit's base dependency is // Eclipse 4.6 if (IContentOutlinePage.class.equals(adapter)) { if (outlinePage == null) { outlinePage = createOutlinePage(); outlinePage.setInput( getDocumentProvider().getDocument(getEditorInput())); if (currentFileDiffRange != null) { outlinePage.setSelection( new StructuredSelection(currentFileDiffRange)); } } return outlinePage; } return super.getAdapter(adapter); } private DiffEditorOutlinePage createOutlinePage() { DiffEditorOutlinePage page = new DiffEditorOutlinePage(); page.addSelectionChangedListener( event -> doSetSelection(event.getSelection())); page.addOpenListener(event -> { FormEditor editor = getEditor(); editor.getSite().getPage().activate(editor); editor.setActivePage(getId()); doSetSelection(event.getSelection()); }); return page; } @Override public void dispose() { // Nested editors are responsible for disposing their outline pages // themselves. if (outlinePage != null) { outlinePage.dispose(); outlinePage = null; } if (overviewStore != null) { overviewStore.dispose(); overviewStore = null; } super.dispose(); } // TextEditor specifics: @Override protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { DiffViewer viewer = new DiffViewer(parent, ruler, getOverviewRuler(), isOverviewRulerVisible(), styles); getSourceViewerDecorationSupport(viewer); ProjectionSupport projector = new ProjectionSupport(viewer, getAnnotationAccess(), getSharedColors()); projector.install(); viewer.getTextWidget().addCaretListener(event -> { if (outlinePage != null) { FileDiffRegion region = getFileDiffRange(event.caretOffset); if (region != null && !region.equals(currentFileDiffRange)) { currentFileDiffRange = region; outlinePage.setSelection(new StructuredSelection(region)); } else { currentFileDiffRange = region; } } }); return viewer; } @Override protected IVerticalRulerColumn createLineNumberRulerColumn() { lineNumberColumn = new OldNewLogicalLineNumberRulerColumn( plainLineNumbers); initializeLineNumberRulerColumn(lineNumberColumn); return lineNumberColumn; } @Override protected void initializeEditor() { super.initializeEditor(); overviewStore = new ThemePreferenceStore(); setPreferenceStore(new ChainedPreferenceStore(new IPreferenceStore[] { overviewStore, EditorsUI.getPreferenceStore() })); setDocumentProvider(new DiffDocumentProvider()); setSourceViewerConfiguration( new DiffViewer.Configuration(getPreferenceStore()) { @Override public IReconciler getReconciler( ISourceViewer sourceViewer) { // Switch off spell-checking return null; } }); } @Override protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (input instanceof DiffEditorInput) { setFolding(); FileDiffRegion region = getFileDiffRange(0); currentFileDiffRange = region; setOverviewAnnotations(); } else if (input instanceof CommitEditorInput) { formatDiff(); currentFileDiffRange = null; } if (outlinePage != null) { outlinePage.setInput(getDocumentProvider().getDocument(input)); if (currentFileDiffRange != null) { outlinePage.setSelection( new StructuredSelection(currentFileDiffRange)); } } } @Override protected void doSetSelection(ISelection selection) { if (!selection.isEmpty() && selection instanceof StructuredSelection) { Object selected = ((StructuredSelection) selection) .getFirstElement(); if (selected instanceof FileDiffRegion) { FileDiffRegion newRange = (FileDiffRegion) selected; if (!newRange.equals(currentFileDiffRange)) { currentFileDiffRange = newRange; selectAndReveal(newRange.getOffset(), 0); } return; } } super.doSetSelection(selection); } @Override protected void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.SELECT_ALL); // TextEditor always adds these, even if the document is not editable. menu.remove(ITextEditorActionConstants.SHIFT_RIGHT); menu.remove(ITextEditorActionConstants.SHIFT_LEFT); } @Override protected void rulerContextMenuAboutToShow(IMenuManager menu) { super.rulerContextMenuAboutToShow(menu); // AbstractDecoratedTextEditor's menu presumes a // LineNumberChangeRulerColumn, which we don't have. IContributionItem showLineNumbers = menu .find(ITextEditorActionConstants.LINENUMBERS_TOGGLE); boolean isShowingLineNumbers = EditorsUI.getPreferenceStore() .getBoolean( AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER); if (showLineNumbers instanceof ActionContributionItem) { ((ActionContributionItem) showLineNumbers).getAction() .setChecked(isShowingLineNumbers); } if (isShowingLineNumbers) { // Add an action to toggle between physical and logical line numbers boolean plain = lineNumberColumn.isPlain(); IAction togglePlain = new Action( UIText.DiffEditorPage_ToggleLineNumbers, IAction.AS_CHECK_BOX) { @Override public void run() { plainLineNumbers = !plain; lineNumberColumn.setPlain(!plain); } }; togglePlain.setChecked(!plain); menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, togglePlain); } } // FormPage specifics: @Override public void initialize(FormEditor editor) { formEditor = editor; } @Override public FormEditor getEditor() { return formEditor; } @Override public IManagedForm getManagedForm() { return null; } @Override public void setActive(boolean active) { if (active) { setFocus(); } } @Override public boolean isActive() { return this.equals(formEditor.getActivePageInstance()); } @Override public boolean canLeaveThePage() { return true; } @Override public Control getPartControl() { return textControl; } @Override public String getId() { return pageId; } @Override public int getIndex() { return pageIndex; } @Override public void setIndex(int index) { pageIndex = index; } @Override public boolean isEditor() { return true; } @Override public boolean selectReveal(Object object) { if (object instanceof IMarker) { IDE.gotoMarker(this, (IMarker) object); return true; } else if (object instanceof ISelection) { doSetSelection((ISelection) object); return true; } return false; } // WorkbenchPart specifics: @Override public String getTitle() { return title; } @Override public void createPartControl(Composite parent) { super.createPartControl(parent); Control[] children = parent.getChildren(); textControl = children[children.length - 1]; } // "Show In..." specifics: @Override public ShowInContext getShowInContext() { RepositoryCommit commit = AdapterUtils.adapt(getEditorInput(), RepositoryCommit.class); if (commit != null) { return new ShowInContext(getEditorInput(), new StructuredSelection(commit)); } return null; } @Override public String[] getShowInTargetIds() { return new String[] { IHistoryView.VIEW_ID, RepositoriesView.VIEW_ID }; } // Diff specifics: private void setFolding() { ProjectionViewer viewer = (ProjectionViewer) getSourceViewer(); if (viewer == null) { return; } IDocument document = viewer.getDocument(); if (document instanceof DiffDocument) { FileDiffRegion[] regions = ((DiffDocument) document) .getFileRegions(); if (regions == null || regions.length <= 1) { viewer.disableProjection(); return; } viewer.enableProjection(); Map<Annotation, Position> newAnnotations = new HashMap<>(); for (FileDiffRegion region : regions) { newAnnotations.put(new ProjectionAnnotation(), new Position(region.getOffset(), region.getLength())); } viewer.getProjectionAnnotationModel().modifyAnnotations( currentFoldingAnnotations, newAnnotations, null); currentFoldingAnnotations = newAnnotations.keySet() .toArray(new Annotation[newAnnotations.size()]); } else { viewer.disableProjection(); currentFoldingAnnotations = null; } } private void setOverviewAnnotations() { IDocumentProvider documentProvider = getDocumentProvider(); IDocument document = documentProvider.getDocument(getEditorInput()); if (!(document instanceof DiffDocument)) { return; } IAnnotationModel annotationModel = documentProvider .getAnnotationModel(getEditorInput()); if (annotationModel == null) { return; } DiffRegion[] diffs = ((DiffDocument) document).getRegions(); if (diffs == null || diffs.length == 0) { return; } Map<Annotation, Position> newAnnotations = new HashMap<>(); for (DiffRegion region : diffs) { if (DiffRegion.Type.ADD.equals(region.getType())) { newAnnotations.put( new Annotation(ADD_ANNOTATION_TYPE, true, null), new Position(region.getOffset(), region.getLength())); } else if (DiffRegion.Type.REMOVE.equals(region.getType())) { newAnnotations.put( new Annotation(REMOVE_ANNOTATION_TYPE, true, null), new Position(region.getOffset(), region.getLength())); } } if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension) annotationModel).replaceAnnotations( currentOverviewAnnotations, newAnnotations); } else { if (currentOverviewAnnotations != null) { for (Annotation existing : currentOverviewAnnotations) { annotationModel.removeAnnotation(existing); } } for (Map.Entry<Annotation, Position> entry : newAnnotations .entrySet()) { annotationModel.addAnnotation(entry.getKey(), entry.getValue()); } } currentOverviewAnnotations = newAnnotations.keySet() .toArray(new Annotation[newAnnotations.size()]); } private FileDiffRegion getFileDiffRange(int widgetOffset) { DiffViewer viewer = (DiffViewer) getSourceViewer(); if (viewer != null) { int offset = viewer.widgetOffset2ModelOffset(widgetOffset); IDocument document = getDocumentProvider() .getDocument(getEditorInput()); if (document instanceof DiffDocument) { return ((DiffDocument) document).findFileRegion(offset); } } return null; } /** * Gets the full unified diff of a {@link RepositoryCommit}. * * @param commit * to get the diff * @return the diff as a sorted (by file path) array of {@link FileDiff}s */ protected FileDiff[] getDiffs(RepositoryCommit commit) { List<FileDiff> diffResult = new ArrayList<>(); diffResult.addAll(asList(commit.getDiffs())); if (commit.getRevCommit().getParentCount() > 2) { RevCommit untrackedCommit = commit.getRevCommit() .getParent(StashEditorPage.PARENT_COMMIT_UNTRACKED); diffResult .addAll(asList(new RepositoryCommit(commit.getRepository(), untrackedCommit).getDiffs())); } Collections.sort(diffResult, FileDiff.PATH_COMPARATOR); return diffResult.toArray(new FileDiff[diffResult.size()]); } /** * Asynchronously gets the diff of the commit set on our * {@link CommitEditorInput}, formats it into a {@link DiffDocument}, and * then re-sets this editors's input to a {@link DiffEditorInput} which will * cause this document to be shown. */ private void formatDiff() { RepositoryCommit commit = AdapterUtils.adapt(getEditor(), RepositoryCommit.class); if (commit == null) { return; } if (!commit.isStash() && commit.getRevCommit().getParentCount() > 1) { setInput(new DiffEditorInput(commit, null)); return; } final DiffDocument document = new DiffDocument(); final DiffRegionFormatter formatter = new DiffRegionFormatter( document); Job job = new Job(UIText.DiffEditorPage_TaskGeneratingDiff) { @Override protected IStatus run(IProgressMonitor monitor) { FileDiff diffs[] = getDiffs(commit); monitor.beginTask("", diffs.length); //$NON-NLS-1$ Repository repository = commit.getRepository(); for (FileDiff diff : diffs) { if (monitor.isCanceled()) break; monitor.setTaskName(diff.getPath()); try { formatter.write(repository, diff); } catch (IOException ignore) { // Ignored } monitor.worked(1); } monitor.done(); new UIJob(UIText.DiffEditorPage_TaskUpdatingViewer) { @Override public IStatus runInUIThread(IProgressMonitor uiMonitor) { if (UIUtils.isUsable(getPartControl())) { document.connect(formatter); setInput(new DiffEditorInput(commit, document)); } return Status.OK_STATUS; } }.schedule(); return Status.OK_STATUS; } }; job.schedule(); } private static class DiffEditorInput extends CommitEditorInput { private IDocument document; public DiffEditorInput(RepositoryCommit commit, IDocument diff) { super(commit); document = diff; } public IDocument getDocument() { return document; } @Override public String getName() { return UIText.DiffEditorPage_Title; } @Override public boolean equals(Object obj) { return super.equals(obj) && (obj instanceof DiffEditorInput) && Objects.equals(document, ((DiffEditorInput) obj).document); } @Override public int hashCode() { return super.hashCode() ^ Objects.hashCode(document); } } /** * A document provider that knows about {@link DiffEditorInput}. */ private static class DiffDocumentProvider extends AbstractDocumentProvider { @Override public IStatus getStatus(Object element) { if (element instanceof CommitEditorInput) { RepositoryCommit commit = ((CommitEditorInput) element) .getCommit(); if (commit != null && !commit.isStash() && commit.getRevCommit() != null && commit.getRevCommit().getParentCount() > 1) { return Activator.createErrorStatus( UIText.DiffEditorPage_WarningNoDiffForMerge); } } return Status.OK_STATUS; } @Override protected IDocument createDocument(Object element) throws CoreException { if (element instanceof DiffEditorInput) { IDocument document = ((DiffEditorInput) element).getDocument(); if (document != null) { return document; } } return new Document(); } @Override protected IAnnotationModel createAnnotationModel(Object element) throws CoreException { return new AnnotationModel(); } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { // Cannot save } @Override protected IRunnableContext getOperationRunner( IProgressMonitor monitor) { return null; } } /** * An ephemeral {@link PreferenceStore} that sets the annotation colors * based on the theme-dependent colors defined for the line backgrounds in a * unified diff. This ensures that the annotation colors are always * consistent with the line backgrounds. Plus the user doesn't have to * configure several related colors, and the annotations update when the * theme changes. */ private static class ThemePreferenceStore extends PreferenceStore { // The colors defined in plugin.xml for these annotations are not taken // into account. We always use auto-computed colors based on the current // settings for the line background colors. private static final String ADD_ANNOTATION_COLOR_PREFERENCE = "org.eclipse.egit.ui.commitEditor.diffAddedColor"; //$NON-NLS-1$ private static final String REMOVE_ANNOTATION_COLOR_PREFERENCE = "org.eclipse.egit.ui.commitEditor.diffRemovedColor"; //$NON-NLS-1$ private final IPropertyChangeListener listener = event -> { String property = event.getProperty(); if (IThemeManager.CHANGE_CURRENT_THEME.equals(property)) { setColorRegistry(); initColors(); } else if (THEME_DiffAddBackgroundColor.equals(property) || THEME_DiffRemoveBackgroundColor.equals(property)) { initColors(); } }; private ColorRegistry currentColors; public ThemePreferenceStore() { super(); setColorRegistry(); initColors(); PlatformUI.getWorkbench().getThemeManager() .addPropertyChangeListener(listener); } private void setColorRegistry() { if (currentColors != null) { currentColors.removeListener(listener); } currentColors = PlatformUI.getWorkbench().getThemeManager() .getCurrentTheme().getColorRegistry(); currentColors.addListener(listener); } private void initColors() { // The overview ruler tones down colors. Since our background colors // usually are already rather pale, let's saturate them more and // brighten them, otherwise the annotations will be barely visible. RGB rgb = adjust(currentColors.getRGB(THEME_DiffAddBackgroundColor), 4.0); setValue(ADD_ANNOTATION_COLOR_PREFERENCE, StringConverter.asString(rgb)); rgb = adjust(currentColors.getRGB(THEME_DiffRemoveBackgroundColor), 4.0); setValue(REMOVE_ANNOTATION_COLOR_PREFERENCE, StringConverter.asString(rgb)); } /** * Increases the saturation (simple multiplier), and brightens dark * colors. * * @param rgb * to modify * @param saturation * multiplier * @return A new {@link RGB} for the new saturated and possibly * brightened color */ private RGB adjust(RGB rgb, double saturation) { float[] hsb = rgb.getHSB(); // We also brighten the color because otherwise the color // manipulations in OverviewRuler result in a fill color barely // discernible from a dark background. return new RGB(hsb[0], (float) Math.min(hsb[1] * saturation, 1.0), hsb[2] < 0.5 ? hsb[2] * 2 : hsb[2]); } public void dispose() { PlatformUI.getWorkbench().getThemeManager() .removePropertyChangeListener(listener); if (currentColors != null) { currentColors.removeListener(listener); currentColors = null; } } } }
package org.eclipse.jdt.ls.core.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.URI; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import org.apache.commons.io.FileUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.ls.core.internal.managers.ProjectsManager; import org.junit.Test; import com.google.common.base.Throwables; /** * @author Fred Bricon * */ public class JDTUtilsTest extends AbstractWorkspaceTest { @Test public void testGetPackageNameString() throws Exception { String content = "package foo.bar.internal"; assertEquals("foo.bar.internal", JDTUtils.getPackageName(null, content)); content = "some junk"; assertEquals("", JDTUtils.getPackageName(null, content)); content = ""; assertEquals("", JDTUtils.getPackageName(null, content)); assertEquals("", JDTUtils.getPackageName(null, (String)null)); } @Test public void testGetPackageNameURI() throws Exception { URI src = Paths.get("projects", "eclipse", "hello", "src", "java", "Foo.java").toUri(); String packageName = JDTUtils.getPackageName(null, src); assertEquals("java", packageName); } @Test public void testGetPackageNameNoSrc() throws Exception { Path foo = getTmpFile("projects/eclipse/hello/Foo.java"); foo.toFile().getParentFile().mkdirs(); FileUtils.copyFile(Paths.get("projects", "eclipse", "hello", "Foo.java").toFile(), foo.toFile()); URI uri = foo.toUri(); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri.toString()); String packageName = JDTUtils.getPackageName(cu.getJavaProject(), uri); assertEquals("", packageName); } private Path getTmpFile(String tmpPath) throws IOException { File tmp = Files.createTempDirectory("temp").toFile(); Runtime.getRuntime().addShutdownHook(new Thread(() -> FileUtils.deleteQuietly(tmp))); Path path = tmp.toPath(); Path result = path.resolve(tmpPath); return result; } @Test public void testGetPackageNameSrc() throws Exception { Path foo = getTmpFile("projects/eclipse/hello/src/Foo.java"); foo.toFile().getParentFile().mkdirs(); FileUtils.copyFile(Paths.get("projects", "eclipse", "hello", "src", "Foo.java").toFile(), foo.toFile()); URI uri = foo.toUri(); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri.toString()); String packageName = JDTUtils.getPackageName(cu.getJavaProject(), uri); assertEquals("", packageName); } @Test public void testResolveStandaloneCompilationUnit() throws CoreException { Path helloSrcRoot = Paths.get("projects", "eclipse", "hello", "src").toAbsolutePath(); URI uri = helloSrcRoot.resolve(Paths.get("java", "Foo.java")).toUri(); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri.toString()); assertNotNull("Could not find compilation unit for " + uri, cu); assertEquals(ProjectsManager.DEFAULT_PROJECT_NAME, cu.getResource().getProject().getName()); IJavaElement[] elements = cu.getChildren(); assertEquals(2, elements.length); assertTrue(IPackageDeclaration.class.isAssignableFrom(elements[0].getClass())); assertTrue(IType.class.isAssignableFrom(elements[1].getClass())); assertTrue(cu.getResource().isLinked()); assertEquals(cu.getResource(), JDTUtils.findResource(uri, ResourcesPlugin.getWorkspace().getRoot()::findFilesForLocationURI)); uri = helloSrcRoot.resolve("NoPackage.java").toUri(); cu = JDTUtils.resolveCompilationUnit(uri.toString()); assertNotNull("Could not find compilation unit for " + uri, cu); assertEquals(ProjectsManager.DEFAULT_PROJECT_NAME, cu.getResource().getProject().getName()); elements = cu.getChildren(); assertEquals(1, elements.length); assertTrue(IType.class.isAssignableFrom(elements[0].getClass())); } @Test public void testUnresolvableCompilationUnits() throws Exception { assertNull(JDTUtils.resolveCompilationUnit((String)null)); assertNull(JDTUtils.resolveCompilationUnit((URI)null)); assertNull(JDTUtils.resolveCompilationUnit(new URI("gopher://meh"))); assertNull(JDTUtils.resolveCompilationUnit("foo/bar/Clazz.java")); assertNull(JDTUtils.resolveCompilationUnit("file:///foo/bar/Clazz.java")); } @Test public void testNonJavaCompilationUnit() throws Exception { Path root = Paths.get("projects", "maven", "salut").toAbsolutePath(); URI uri = root.resolve("pom.xml").toUri(); assertNull(JDTUtils.resolveCompilationUnit(uri)); IProject project = WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME); assertFalse(project.getFile("src/pom.xml").isLinked()); } @Test public void testIgnoredUnknownSchemes() { PrintStream originalOut = System.out; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos, true)); System.out.flush(); JDTUtils.resolveCompilationUnit("inmemory:///foo/bar/Clazz.java"); assertEquals("",baos.toString()); } finally { System.setOut(originalOut); } } @Test public void testResolveStandaloneCompilationUnitWithinJob() throws Exception { WorkspaceJob job = new WorkspaceJob("Create link") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { testResolveStandaloneCompilationUnit(); } catch (Exception e) { return StatusFactory.newErrorStatus("Failed to resolve CU", e); } return Status.OK_STATUS; } }; job.setRule(WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME)); job.schedule(); job.join(2_000, new NullProgressMonitor()); assertNotNull(job.getResult()); assertNull(getStackTrace(job.getResult()), job.getResult().getException()); assertTrue(job.getResult().getMessage(), job.getResult().isOK()); } private String getStackTrace(IStatus status) { if (status != null && status.getException() != null) { return Throwables.getStackTraceAsString(status.getException()); } return null; } @Test public void testFakeCompilationUnit() throws Exception { String tempDir = System.getProperty("java.io.tmpdir"); File dir = new File(tempDir, "/test/src/org/eclipse"); dir.mkdirs(); File file = new File(dir, "Test.java"); file.createNewFile(); URI uri = file.toURI(); JDTUtils.resolveCompilationUnit(uri); IProject project = WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME); IFile iFile = project.getFile("/src/org/eclipse/Test.java"); assertTrue(iFile.getFullPath().toString() + " doesn't exist.", iFile.exists()); Path path = Paths.get(tempDir + "/test"); Files.walk(path, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } }
package org.jerkar.api.depmanagement; import java.io.Serializable; /** * Defines filter to accept or not module to be published on a given * {@link JkPublishRepo} * * @author Jerome Angibaud */ @FunctionalInterface public interface JkPublishFilter extends Serializable { /** * Returns <code>true</code> if this filter should accept the specified versioned module. */ boolean accept(JkVersionedModule versionedModule); /** * A filter accepting everything. */ JkPublishFilter ACCEPT_ALL = (JkPublishFilter) versionedModule -> true; /** * A filter accepting only snapshot versioned module. */ JkPublishFilter ACCEPT_SNAPSHOT_ONLY = (JkPublishFilter) versionedModule -> versionedModule.version().isSnapshot(); /** * A filter accepting only non-snapshot versioned module. */ JkPublishFilter ACCEPT_RELEASE_ONLY = (JkPublishFilter) versionedModule -> !versionedModule.version().isSnapshot(); }
package Debrief.ReaderWriter.Word; import java.awt.Color; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import Debrief.GUI.Frames.Application; import Debrief.Wrappers.FixWrapper; import Debrief.Wrappers.TrackWrapper; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.ToolParent; import MWC.GUI.Properties.DebriefColors; import MWC.GenericData.HiResDate; import MWC.GenericData.WorldLocation; import MWC.Utilities.TextFormatting.GMTDateFormat; import junit.framework.TestCase; public class ImportASWDataDocument { /** * helper that can ask the user a question * */ public static interface QuestionHelper { String getTrackName(String title, String message); } public static class TestImportWord extends TestCase { public void testParseDates() { final String d1 = "TIMPD/290000Z/300200Z/APR/2016/APR2016"; final String d2 = "TIMPD//230001Z//232359Z//APR//2017//APR//2017//"; final String d3 = "TIMPD/220000Z/222400Z/APR/2018"; final String d4 = "TIMPD/261200ZAPR/IN/262359ZAPR/IN/APR/2019/APR/2019/"; // start off with good ones assertEquals("date 1", 2016, yearFor(d1).intValue()); assertEquals("date 2", 2017, yearFor(d2).intValue()); assertEquals("date 3", 2018, yearFor(d3).intValue()); assertEquals("date 4", 2019, yearFor(d4).intValue()); assertNull("wrong format", yearFor( "TMPOS/290000Z/300200Z/APR/2016/APR2016")); assertNull("no year", yearFor("TMPOS/290000Z/300200Z/APR/201A6/APR2016")); assertNull("too early", yearFor("TMPOS/290000Z/300200Z/APR/16/APR2016")); assertNull("too late", yearFor( "TMPOS/290000Z/300200Z/APR/124316/APR2016")); } @SuppressWarnings("unused") public void testParseFixes() { final String d1 = "TMPOS/261200ZAPR/IN/12.23.34N-121.12.1E/057T/04KTS/00.0M final String d2 = "TMPOS/262327ZAPR/INS/13.14.15S-011.22.33W/180T/13KTS/000FT"; final String d3 = "TMPOS/220000ZAPR/GPS/1230N/01215W"; final String d4 = "TMPOS/230001ZAPR/GPS/22.33.44N/020.11.22W/006T/10KTS final String d5 = "TMPOS/290000ZAPR/GPS/04 .02. 01N/111.22. 11W/89T/9KTS"; // repeat of last line, but with spaces removed final String d6 = "TMPOS/290000ZAPR/GPS/04.02.01N/111.22.11W/89T/9KTS"; } @SuppressWarnings("unused") public void testParseLocations() { assertNull("fails for empty", locationFor(null)); final String d1 = "12.23.34N-121.12.1E"; final String d2 = "13.14.15S-011.22.33W"; final String d3 = "1230N/01215W"; final String d4 = "22.33.44N/020.11.22W"; final String d5 = "04 .02. 01N/111.22. 11W"; // repeat of last line, but with spaces removed final String d6 = "04.02.01N/111.22.11W"; assertEquals("d1", loc(1, 2, 3), locationFor(d1)); } public void testDates() { final String d1 = "261200ZAPR"; final String d2 = "262327ZAPR"; final String d3 = "220000ZMAY"; final String d4 = "012345ZAPR"; final String d5 = "292359ZAPR"; DateFormat df = new GMTDateFormat("yy-MM-dd HH:mm:ss"); assertEquals("aaa", "70-04-26 12:00:00", df.format(dateFor(d1) .getDate())); assertEquals("aaa", "70-04-26 23:27:00", df.format(dateFor(d2) .getDate())); assertEquals("aaa", "70-05-22 00:00:00", df.format(dateFor(d3) .getDate())); assertEquals("aaa", "70-04-01 23:45:00", df.format(dateFor(d4) .getDate())); assertEquals("aaa", "70-04-29 23:59:00", df.format(dateFor(d5) .getDate())); } @SuppressWarnings("unused") private static WorldLocation loc(final double lat, final double lon, final double dep) { return new WorldLocation(lat, lon, dep); } public void testIsValid() { List<String> input = new ArrayList<String>(); for (int i = 0; i < 20; i++) { input.add("Some old duff information"); } assertFalse("not suitable for import", canImport(input)); for (int i = 0; i < 10; i++) { input.add("TMPOS/Here we go!"); } assertTrue("now suitable for import", canImport(input)); } } /** * helper class that can ask the user a question populated via Dependency Injection */ private static QuestionHelper questionHelper = null; /** * match a 6 figure DTG * */ static final String DATE_MATCH_SIX = "(\\d{6})"; static final String DATE_MATCH_FOUR = "(\\d{4})"; public static void logThisError(final int status, final String msg, final Exception e) { Application.logError3(status, msg, e, true); } /** * do some pre-processing of text, to protect robustness of data written to file * * @param raw_text * @return text with some control chars removed */ public static String removeBadChars(final String raw_text) { // swap soft returns for hard ones String res = raw_text.replace('\u000B', '\n'); // we learned that whilst MS Word includes the following // control chars, and we can persist them via XML, we // can't restore them via SAX. So, swap them for // spaces res = res.replace((char) 1, (char) 32); res = res.replace((char) 19, (char) 32); res = res.replace((char) 8, (char) 32); // backspace char, occurred in Oct 17, near an inserted // picture res = res.replace((char) 20, (char) 32); res = res.replace((char) 21, (char) 32); res = res.replace((char) 5, (char) 32); // MS Word comment marker res = res.replace((char) 31, (char) 32); // described as units marker, but we had it prior to // subscript "2" // done. return res; } public static void setQuestionHelper(final QuestionHelper helper) { questionHelper = helper; } /** * check if the layers contains a single track object * * @param layers * @return */ private static boolean singleTrackIn(final Layers layers) { int ctr = 0; final int len = layers.size(); for (int i = 0; i < len; i++) { final Layer next = layers.elementAt(i); if (next instanceof TrackWrapper) { ctr++; if (ctr > 1) { break; } } } return ctr == 1; } /** * where we write our data * */ private final Layers _layers; public ImportASWDataDocument(final Layers destination) { _layers = destination; } /** * repeatably find a color for the specified track id The color will be RED if it's a master track * ("M01"). Shades of gray nor ownship blue are returned. * * @param trackId * @return */ private static Color colorFor(final String trackId) { final Color res; // ok, is it a master track? if (trackId.startsWith("M")) { res = DebriefColors.RED; } else { // ok, get the hash code final int hash = trackId.hashCode(); res = DebriefColors.RandomColorProvider.getRandomColor(hash); } return res; } public static void logError(final int status, final String msg, final Exception e) { logThisError(status, msg, e); } /** * parse a list of strings * * @param strings */ @SuppressWarnings("unused") public void processThese(final ArrayList<String> strings) { if (strings.isEmpty()) { return; } boolean proceed = true; // keep track of if we've added anything boolean dataAdded = false; // ok, now we can loop through the strings if (proceed) { int ctr = 0; TrackWrapper track = null; for (final String raw_text : strings) { // increment counter, for num lines processed ctr++; // also remove any other control chars that may throw MS Word final String text = removeBadChars(raw_text); // process it } if (dataAdded) { _layers.fireModified(track); } } } final private static String marker = "TMPOS"; private static HiResDate dateFor(final String str) { DateFormat df = new GMTDateFormat("ddHHmm'Z'MMM"); HiResDate res = null; try { Date date = df.parse(str); res = new HiResDate(date); } catch (ParseException e) { logError(ToolParent.ERROR, "While Parsing:" + str, e); } return res; } private static WorldLocation locationFor(final String str) { // TMPOS/261200ZAPR/IN/00.00.0N-000.00.0W/057T/04KTS/00.0M// // TMPOS/262327ZAPR/INS/00.00.00N-000.00.00W/180T/13KTS/000FT // TMPOS/220000ZAPR/GPS/ddmmN/dddmmW // TMPOS/230001ZAPR/GPS/00.00.00N/000.00.00W/006T/10KTS// // TMPOS/290000ZAPR/GPS/00 .00. 00N/000.00. 00W/89T/9KTS return null; } @SuppressWarnings({"unused"}) private static FixWrapper fixFor(final String str) { if (str == null) { return null; } else if (!str.startsWith("TMPOS")) { return null; } else { String[] tokens = str.split("/"); // start off with the date HiResDate date = null; Double dLat = null; Double dLon = null; for (final String s : tokens) { if (date == null) { int zIndex = s.indexOf("Z"); if (zIndex != -1) { date = dateFor(s); } } else { // ok on with lat/lon } } } return null; } private static Integer yearFor(String str) { // formats encountered in the wild // "TIMPD/290000Z/300200Z/APR/2016/APR2019"; // "TIMPD//230001Z//232359Z//APR//2017//APR//2019//"; // "TIMPD/220000Z/222400Z/APR/2017"; // "TIMPD/261200ZAPR/IN/262359ZAPR/IN/APR/2019/APR/2019/"; // double-check it's one of ours if (!str.startsWith("TIMPD")) { return null; } else { // ok, tokenise String[] tokens = str.split("/"); for (final String s : tokens) { if (s.length() == 4 && s.matches("^-?\\d+$")) { final int year = Integer.parseInt(s); if (year > 1000 && year < 3000) { return year; } } } return null; } } public static boolean canImport(List<String> strings) { // run through strings, see if we have TMPOS in more than 5 lines in the first 50 final int numLines = 100; final int requiredLines = 5; int matches = 0; int lines = 0; for (final String l : strings) { lines++; if (l.startsWith(marker)) { matches++; } if (matches >= requiredLines) { return true; } if (lines > numLines) { break; } } return false; } }
package io.spine.protobuf; import com.google.common.base.Converter; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.protobuf.Any; import com.google.protobuf.BoolValue; import com.google.protobuf.ByteString; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.EnumValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.Message; import com.google.protobuf.ProtocolMessageEnum; import com.google.protobuf.StringValue; import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import io.spine.annotation.Internal; import io.spine.type.TypeUrl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.protobuf.AnyPacker.unpack; import static io.spine.util.Exceptions.newIllegalArgumentException; @Internal public final class TypeConverter { private static final TypeUrl ENUM_VALUE_TYPE_URL = TypeUrl.of(EnumValue.class); /** Prevents instantiation of this utility class. */ private TypeConverter() { } /** * Converts the given {@link Any} value to a Java {@link Object}. * * @param message the {@link Any} value to convert * @param target the conversion target class * @param <T> the conversion target type * @return the converted value */ public static <T> T toObject(Any message, Class<T> target) { checkNotNull(message); checkNotNull(target); checkNotRawEnum(message, target); MessageCaster<? super Message, T> caster = MessageCaster.forType(target); Message genericMessage = unpack(message); T result = caster.convert(genericMessage); return result; } /** * Converts the given value to Protobuf {@link Any}. * * @param value the {@link Object} value to convert * @param <T> the converted object type * @return the packed value * @see #toMessage(Object) */ public static <T> Any toAny(T value) { checkNotNull(value); Message message = toMessage(value); Any result = AnyPacker.pack(message); return result; } /** * Converts the given value to a corresponding Protobuf {@link Message} type. * * @param value the {@link Object} value to convert * @param <T> the converted object type * @return the wrapped value */ public static <T> Message toMessage(T value) { @SuppressWarnings("unchecked" /* Must be checked at runtime. */) Class<T> srcClass = (Class<T>) value.getClass(); MessageCaster<Message, T> caster = MessageCaster.forType(srcClass); Message message = caster.toMessage(value); checkNotNull(message); return message; } /** * Converts the given value to a corresponding Protobuf {@link Message} type. * * <p>Unlike {@link #toMessage(Object)}, casts the message to the specified class. * * @param value the {@link Object} value to convert * @param <T> the converted object type * @param <M> the resulting message type * @return the wrapped value */ public static <T, M extends Message> M toMessage(T value, Class<M> messageClass) { checkNotNull(messageClass); Message message = toMessage(value); return messageClass.cast(message); } /** * Makes sure no incorrectly packed enum values are passed to the message caster. * * <p>Currently, the enum values can only be converted from the {@link EnumValue} proto type. * All other enum representations, including plain strings and numbers, are not supported. */ private static void checkNotRawEnum(Any message, Class<?> target) { if (!target.isEnum()) { return; } String typeUrl = message.getTypeUrl(); String enumValueTypeUrl = ENUM_VALUE_TYPE_URL.value(); checkArgument( enumValueTypeUrl.equals(typeUrl), "Currently the conversion of enum types packed as `%s` is not supported. " + "Please make sure the enum value is wrapped with `%s` on the calling site.", typeUrl, enumValueTypeUrl); } /** * The {@link Function} performing the described type conversion. */ private abstract static class MessageCaster<M extends Message, T> extends Converter<M, T> { private static <M extends Message, T> MessageCaster<M, T> forType(Class<T> cls) { checkNotNull(cls); MessageCaster<?, ?> caster; if (Message.class.isAssignableFrom(cls)) { caster = new MessageTypeCaster(); } else if (ByteString.class.isAssignableFrom(cls)) { caster = new BytesCaster(); } else if (Enum.class.isAssignableFrom(cls)) { @SuppressWarnings("unchecked") // Checked at runtime. Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>) cls; caster = new EnumCaster(enumCls); } else { caster = new PrimitiveTypeCaster<>(); } @SuppressWarnings("unchecked") // Logically checked. MessageCaster<M, T> result = (MessageCaster<M, T>) caster; return result; } @Override protected T doForward(M input) { return toObject(input); } @Override protected M doBackward(T t) { return toMessage(t); } protected abstract T toObject(M input); protected abstract M toMessage(T input); } private static final class BytesCaster extends MessageCaster<BytesValue, ByteString> { @Override protected ByteString toObject(BytesValue input) { ByteString result = input.getValue(); return result; } @Override protected BytesValue toMessage(ByteString input) { BytesValue bytes = BytesValue .newBuilder() .setValue(input) .build(); return bytes; } } private static final class EnumCaster extends MessageCaster<EnumValue, Enum<?>> { @SuppressWarnings("rawtypes") // Needed to be able to pass the value to `Enum.valueOf(...)`. private final Class<? extends Enum> type; EnumCaster(Class<? extends Enum<?>> type) { super(); this.type = type; } @Override protected Enum<?> toObject(EnumValue input) { String name = input.getName(); if (name.isEmpty()) { int number = input.getNumber(); return convertByNumber(number); } else { return convertByName(name); } } private Enum<?> convertByNumber(int number) { Enum<?>[] constants = type.getEnumConstants(); for (Enum<?> constant : constants) { ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) constant; int valueNumber = asProtoEnum.getNumber(); if (number == valueNumber) { return constant; } } throw newIllegalArgumentException( "Could not find a enum value of type `%s` for number `%d`.", type.getCanonicalName(), number); } @SuppressWarnings("unchecked") // Checked at runtime. private Enum<?> convertByName(String name) { return Enum.valueOf(type, name); } @Override protected EnumValue toMessage(Enum<?> input) { String name = input.name(); ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) input; EnumValue value = EnumValue .newBuilder() .setName(name) .setNumber(asProtoEnum.getNumber()) .build(); return value; } } private static final class MessageTypeCaster extends MessageCaster<Message, Message> { @Override protected Message toObject(Message input) { return input; } @Override protected Message toMessage(Message input) { return input; } } @SuppressWarnings("OverlyCoupledClass") // OK, as references a lot of type for casting. private static final class PrimitiveTypeCaster<M extends Message, T> extends MessageCaster<M, T> { private static final ImmutableMap<Class<?>, Converter<? extends Message, ?>> PROTO_WRAPPER_TO_HANDLER = ImmutableMap.<Class<?>, Converter<? extends Message, ?>>builder() .put(Int32Value.class, new Int32Handler()) .put(Int64Value.class, new Int64Handler()) .put(UInt32Value.class, new UInt32Handler()) .put(UInt64Value.class, new UInt64Handler()) .put(FloatValue.class, new FloatHandler()) .put(DoubleValue.class, new DoubleHandler()) .put(BoolValue.class, new BoolHandler()) .put(StringValue.class, new StringHandler()) .build(); private static final ImmutableMap<Class<?>, Converter<? extends Message, ?>> PRIMITIVE_TO_HANDLER = ImmutableMap.<Class<?>, Converter<? extends Message, ?>>builder() .put(Integer.class, new Int32Handler()) .put(Long.class, new Int64Handler()) .put(Float.class, new FloatHandler()) .put(Double.class, new DoubleHandler()) .put(Boolean.class, new BoolHandler()) .put(String.class, new StringHandler()) .build(); @Override protected T toObject(M input) { Class<?> boxedType = input.getClass(); @SuppressWarnings("unchecked") Converter<M, T> typeUnpacker = (Converter<M, T>) PROTO_WRAPPER_TO_HANDLER.get(boxedType); checkArgument(typeUnpacker != null, "Could not find a primitive type for %s.", boxedType.getName()); T result = typeUnpacker.convert(input); return result; } @Override protected M toMessage(T input) { Class<?> cls = input.getClass(); @SuppressWarnings("unchecked") Converter<M, T> converter = (Converter<M, T>) PRIMITIVE_TO_HANDLER.get(cls); checkArgument(converter != null, "Could not find a wrapper type for %s.", cls.getName()); M result = converter.reverse() .convert(input); return result; } } /** * A converter handling the primitive types transformations. * * <p>It's sufficient to override methods {@link #pack(Object) pack(T)} and * {@link #unpack(Message) unpack(M)} when extending this class. * * <p>Since the Protobuf and Java primitives differ, there may be more then one * {@code PrimitiveHandler} for a Java primitive type. In this case, if the resulting Protobuf * value type is not specified explicitly, the closest type is selected as a target for * the conversion. The closeness of two types is determined by the lexicographic closeness. * * @param <M> the type of the Protobuf primitive wrapper * @param <T> the type of the Java primitive wrapper */ private abstract static class PrimitiveHandler<M extends Message, T> extends Converter<M, T> { @Override protected T doForward(M input) { return unpack(input); } @Override protected M doBackward(T input) { return pack(input); } /** * Unpacks a primitive value of type {@code T} from the given wrapper value. * * @param message packed value * @return unpacked value */ protected abstract T unpack(M message); /** * Packs the given primitive value into a Protobuf wrapper of type {@code M}. * * @param value primitive value * @return packed value */ protected abstract M pack(T value); } private static final class Int32Handler extends PrimitiveHandler<Int32Value, Integer> { @Override protected Integer unpack(Int32Value message) { checkNotNull(message); return message.getValue(); } @Override protected Int32Value pack(Integer value) { return Int32Value.newBuilder() .setValue(value) .build(); } } private static final class Int64Handler extends PrimitiveHandler<Int64Value, Long> { @Override protected Long unpack(Int64Value message) { checkNotNull(message); return message.getValue(); } @Override protected Int64Value pack(Long value) { return Int64Value.newBuilder() .setValue(value) .build(); } } private static final class UInt32Handler extends PrimitiveHandler<UInt32Value, Integer> { @Override protected Integer unpack(UInt32Value message) { checkNotNull(message); return message.getValue(); } @Override protected UInt32Value pack(Integer value) { // Hidden by Int32Handler return UInt32Value.newBuilder() .setValue(value) .build(); } } private static final class UInt64Handler extends PrimitiveHandler<UInt64Value, Long> { @Override protected Long unpack(UInt64Value message) { checkNotNull(message); return message.getValue(); } @Override protected UInt64Value pack(Long value) { // Hidden by Int64Handler return UInt64Value.newBuilder() .setValue(value) .build(); } } private static final class FloatHandler extends PrimitiveHandler<FloatValue, Float> { @Override protected Float unpack(FloatValue message) { checkNotNull(message); return message.getValue(); } @Override protected FloatValue pack(Float value) { return FloatValue.newBuilder() .setValue(value) .build(); } } private static final class DoubleHandler extends PrimitiveHandler<DoubleValue, Double> { @Override protected Double unpack(DoubleValue message) { checkNotNull(message); return message.getValue(); } @Override protected DoubleValue pack(Double value) { return DoubleValue.newBuilder() .setValue(value) .build(); } } private static final class BoolHandler extends PrimitiveHandler<BoolValue, Boolean> { @Override protected Boolean unpack(BoolValue message) { checkNotNull(message); return message.getValue(); } @Override protected BoolValue pack(Boolean value) { return BoolValue.newBuilder() .setValue(value) .build(); } } private static final class StringHandler extends PrimitiveHandler<StringValue, String> { @Override protected String unpack(StringValue message) { checkNotNull(message); return message.getValue(); } @Override protected StringValue pack(String value) { return StringValue.newBuilder() .setValue(value) .build(); } } }
package org.jfree.chart; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.annotations.AnnotationsPackageTests; import org.jfree.chart.axis.AxisPackageTests; import org.jfree.chart.block.BlockPackageTests; import org.jfree.chart.entity.EntityPackageTests; import org.jfree.chart.labels.LabelsPackageTests; import org.jfree.chart.needle.NeedlePackageTests; import org.jfree.chart.plot.dial.DialPackageTests; import org.jfree.chart.plot.PlotPackageTests; import org.jfree.chart.renderer.category.RendererCategoryPackageTests; import org.jfree.chart.renderer.RendererPackageTests; import org.jfree.chart.renderer.xy.RendererXYPackageTests; import org.jfree.chart.title.TitlePackageTests; import org.jfree.chart.urls.UrlsPackageTests; public class JFreeChartTestSuite extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return The test suite. */ public static Test suite() { TestSuite suite = new TestSuite("JFreeChart"); suite.addTest(ChartPackageTests.suite()); suite.addTest(AnnotationsPackageTests.suite()); suite.addTest(AxisPackageTests.suite()); suite.addTest(BlockPackageTests.suite()); suite.addTest(EntityPackageTests.suite()); suite.addTest(LabelsPackageTests.suite()); suite.addTest(NeedlePackageTests.suite()); suite.addTest(PlotPackageTests.suite()); suite.addTest(DialPackageTests.suite()); suite.addTest(RendererPackageTests.suite()); suite.addTest(RendererCategoryPackageTests.suite()); suite.addTest(RendererXYPackageTests.suite()); suite.addTest(TitlePackageTests.suite()); suite.addTest(UrlsPackageTests.suite()); return suite; } /** * Runs the test suite using JUnit's text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
// checkstyle: Checks Java source code for adherence to a set of rules. // 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 package com.github.checkstyle.data; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.github.checkstyle.parser.CheckstyleReportsParser; /** * POJO that accumulates all statistics gathered during parsing stage. * * @author attatrol */ public class Statistics { /** * Map storing severity numbers for difference. */ private Map<String, Integer> severityNumDiff = new HashMap<>(); /** * Number of files in difference. */ private int fileNumDiff; /** * Map storing severity numbers for base source. */ private Map<String, Integer> severityNumBase = new HashMap<>(); /** * Number of files in the base source. */ private int fileNumBase; /** * Map storing severity numbers for patch source. */ private Map<String, Integer> severityNumPatch = new HashMap<>(); /** * Number of files in the patch source. */ private int fileNumPatch; public final Map<String, Integer> getSeverityNumDiff() { return severityNumDiff; } /** * Getter for total number of severity records for difference. * * @return total number of severity records. */ public final int getTotalNumDiff() { int totalSeverityNumber = 0; for (Integer number : severityNumDiff.values()) { totalSeverityNumber += number; } return totalSeverityNumber; } public final int getFileNumDiff() { return fileNumDiff; } public final Map<String, Integer> getSeverityNumBase() { return severityNumBase; } /** * Getter for total number of severity records for base source. * * @return total number of severity records. */ public final int getTotalNumBase() { int totalSeverityNumber = 0; for (Integer number : severityNumBase.values()) { totalSeverityNumber += number; } return totalSeverityNumber; } public final Map<String, Integer> getSeverityNumPatch() { return severityNumPatch; } public final int getFileNumBase() { return fileNumBase; } /** * Getter for total number of severity records for patch source. * * @return total number of severity records. */ public final int getTotalNumPatch() { int totalSeverityNumber = 0; for (Integer number : severityNumPatch.values()) { totalSeverityNumber += number; } return totalSeverityNumber; } public final int getFileNumPatch() { return fileNumPatch; } /** * Setter for number of files in difference. * * @param fileNumDiff1 number of files in difference. */ public final void setFileNumDiff(final int fileNumDiff1) { this.fileNumDiff = fileNumDiff1; } /** * Registers single severity record from indexed source. * * @param severity value of severity record. * @param index index of the source. */ public final void addSeverityRecord(String severity, int index) { final Map<String, Integer> severityRecorder; if (index == CheckstyleReportsParser.BASE_REPORT_INDEX) { severityRecorder = severityNumBase; } else if (index == CheckstyleReportsParser.PATCH_REPORT_INDEX) { severityRecorder = severityNumPatch; } else { severityRecorder = severityNumDiff; } final Integer newNumber = severityRecorder.get(severity); if (newNumber != null) { severityRecorder.put(severity, newNumber + 1); } else { severityRecorder.put(severity, 1); } } /** * Registers single file from numbered source. * * @param index index of the source. */ public final void incrementFileCount(int index) { if (index == CheckstyleReportsParser.BASE_REPORT_INDEX) { this.fileNumBase++; } else if (index == CheckstyleReportsParser.PATCH_REPORT_INDEX) { this.fileNumPatch++; } } /** * Getter for all severity level names encountered during * statistics generation. * * @return severity level names. */ public final Set<String> getSeverityNames() { final Set<String> names = new HashSet<>(severityNumDiff.keySet()); names.addAll(severityNumBase.keySet()); names.addAll(severityNumPatch.keySet()); return names; } }
package com.intellij.ui.popup; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.ui.FocusTrackback; import com.intellij.ui.ScreenUtil; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.labels.BoldLabel; import com.intellij.ui.components.panels.OpaquePanel; import com.intellij.ui.popup.list.ListPopupImpl; import com.intellij.ui.popup.tree.TreePopupImpl; import com.intellij.ui.popup.util.ElementFilter; import com.intellij.ui.popup.util.MnemonicsSearch; import com.intellij.ui.popup.util.SpeedSearch; import com.intellij.util.ui.BlockBorder; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Method; public abstract class BasePopup implements ActionListener, ElementFilter, JBPopup { private static final Logger LOG = Logger.getInstance("#com.intellij.ui.popup.BasePopup"); private static final int AUTO_POPUP_DELAY = 1000; private static final Dimension MAX_SIZE = new Dimension(Integer.MAX_VALUE, 600); protected static final int STEP_X_PADDING = 2; private Popup myPopup; private BasePopup myParent; protected JPanel myContainer; protected final PopupStep<Object> myStep; protected BasePopup myChild; private JScrollPane myScrollPane; @NotNull private JLabel myTitle; protected JComponent myContent; private Timer myAutoSelectionTimer = new Timer(AUTO_POPUP_DELAY, this); private final SpeedSearch mySpeedSearch = new SpeedSearch() { protected void update() { onSpeedSearchPatternChanged(); mySpeedSearchPane.update(); } }; private SpeedSearchPane mySpeedSearchPane; private MnemonicsSearch myMnemonicsSearch; private Object myParentValue; private FocusTrackback myFocusTrackback; private Component myOwner; private Point myLastOwnerPoint; private Window myOwnerWindow; private MyComponentAdapter myOwnerListener; public BasePopup(PopupStep aStep) { this(null, aStep); } public BasePopup(JBPopup aParent, PopupStep aStep) { myParent = (BasePopup) aParent; myStep = aStep; if (myStep.isSpeedSearchEnabled() && myStep.isMnemonicsNavigationEnabled()) { throw new IllegalArgumentException("Cannot have both options enabled at the same time: speed search and mnemonics navigation"); } mySpeedSearch.setEnabled(myStep.isSpeedSearchEnabled()); myContainer = new MyContainer(); mySpeedSearchPane = new SpeedSearchPane(this); myContent = createContent(); myScrollPane = new JScrollPane(myContent); myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); myScrollPane.getHorizontalScrollBar().setBorder(null); myScrollPane.getActionMap().get("unitScrollLeft").setEnabled(false); myScrollPane.getActionMap().get("unitScrollRight").setEnabled(false); myScrollPane.setBorder(null); myContainer.add(myScrollPane, BorderLayout.CENTER); if (!SystemInfo.isMac) { myContainer.setBorder(new BlockBorder()); } final String title = aStep.getTitle(); if (title == null) { myTitle = new JLabel(); } else { myTitle = new BoldLabel(title); myTitle.setHorizontalAlignment(SwingConstants.CENTER); myTitle.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); //myTitle.setBackground(TITLE_BACKGROUND); } myTitle.setOpaque(true); myContainer.add(myTitle, BorderLayout.NORTH); registerAction("disposeAll", KeyEvent.VK_ESCAPE, InputEvent.SHIFT_MASK, new AbstractAction() { public void actionPerformed(ActionEvent e) { if (mySpeedSearch.isHoldingFilter()) { mySpeedSearch.reset(); } else { disposeAll(); } } }); AbstractAction goBackAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { goBack(); } }; registerAction("goBack3", KeyEvent.VK_ESCAPE, 0, goBackAction); myMnemonicsSearch = new MnemonicsSearch(this) { protected void select(Object value) { onSelectByMnemonic(value); } }; } private void disposeAll() { BasePopup root = PopupDispatcher.getActiveRoot(); disposeAllParents(); root.getStep().canceled(); } public void goBack() { if (mySpeedSearch.isHoldingFilter()) { mySpeedSearch.reset(); return; } if (myParent != null) { myParent.disposeChildren(); } else { disposeAll(); } } protected abstract JComponent createContent(); public void dispose() { myAutoSelectionTimer.stop(); if (isDisposed()) return; myPopup.hide(); mySpeedSearchPane.dispose(); PopupDispatcher.unsetShowing(this); PopupDispatcher.clearRootIfNeeded(this); myPopup = null; myContainer = null; if (myParent == null) { myFocusTrackback.restoreFocus(); } if (myOwnerWindow != null && myOwnerListener != null) { myOwnerWindow.removeComponentListener(myOwnerListener); } } protected final boolean isDisposed() { return myPopup == null || myContainer == null; } public void disposeChildren() { if (myChild != null) { myChild.disposeChildren(); myChild.dispose(); myChild = null; } } public final void show(@NotNull RelativePoint aPoint) { final Point screenPoint = aPoint.getScreenPoint(); show(aPoint.getComponent(), screenPoint.x, screenPoint.y); } public void showInScreenCoordinates(@NotNull Component owner, @NotNull Point point) { show(owner, point.x, point.y); } public void showInBestPositionFor(@NotNull DataContext dataContext) { show(JBPopupFactory.getInstance().guessBestPopupLocation(dataContext)); } public void showInBestPositionFor(@NotNull Editor editor) { show(JBPopupFactory.getInstance().guessBestPopupLocation(editor)); } protected boolean beforeShow() { return true; } protected void afterShow() { } public void show(final Component owner) { showInCenterOf(owner); } public final void show(Component owner, int aScreenX, int aScreenY) { if (myContainer == null) { throw new IllegalStateException("Wizard dialog was already disposed. Recreate a new instance to show the wizard again"); } myFocusTrackback = new FocusTrackback(this, owner, true); myScrollPane.getViewport().setPreferredSize(myContent.getPreferredSize()); boolean shouldShow = beforeShow(); if (!shouldShow) { myFocusTrackback.setMustBeShown(false); } Rectangle targetBounds = new Rectangle(new Point(aScreenX, aScreenY), myContainer.getPreferredSize()); ScreenUtil.moveRectangleToFitTheScreen(targetBounds); if (getParent() != null) { if (getParent().getBounds().intersects(targetBounds)) { targetBounds.x = getParent().getBounds().x - targetBounds.width - STEP_X_PADDING; } } if (getParent() == null) { PopupDispatcher.setActiveRoot(this); } else { PopupDispatcher.setShowing(this); } myPopup = setupPopupFactory().getPopup(owner, myContainer, targetBounds.x, targetBounds.y); myOwner = owner; if (shouldShow) { myPopup.show(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (isDisposed()) return; requestFocus(); myFocusTrackback.registerFocusComponent(getPreferredFocusableComponent()); registerAutoMove(); afterShow(); } }); } else { cancel(); } } private void registerAutoMove() { if (myOwner != null) { myOwnerWindow = SwingUtilities.getWindowAncestor(myOwner); if (myOwnerWindow != null) { myLastOwnerPoint = myOwnerWindow.getLocationOnScreen(); myOwnerListener = new MyComponentAdapter(); myOwnerWindow.addComponentListener(myOwnerListener); } } } private void processParentWindowMoved() { if (isDisposed()) return; final Point newOwnerPoint = myOwnerWindow.getLocationOnScreen(); int deltaX = myLastOwnerPoint.x - newOwnerPoint.x; int deltaY = myLastOwnerPoint.y - newOwnerPoint.y; myLastOwnerPoint = newOwnerPoint; final Window wnd = SwingUtilities.getWindowAncestor(myContainer); final Point current = wnd.getLocationOnScreen(); setLocation(new Point(current.x - deltaX, current.y - deltaY)); } private static PopupFactory setupPopupFactory() { final PopupFactory factory = PopupFactory.getSharedInstance(); if (!SystemInfo.isWindows) { try { final Method method = PopupFactory.class.getDeclaredMethod("setPopupType", int.class); method.setAccessible(true); method.invoke(factory, 2); } catch (Throwable e) { LOG.error(e); } } return factory; } protected abstract void requestFocus(); protected abstract JComponent getPreferredFocusableComponent(); public boolean canClose() { return true; } public void cancel() { disposeChildren(); dispose(); getStep().canceled(); } public boolean isVisible() { return myPopup != null; } public Component getContent() { return myContent; } public void showInCenterOf(@NotNull Component aContainer) { final JComponent component = getTargetComponent(aContainer); Point containerScreenPoint = component.getVisibleRect().getLocation(); SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer); final Point popupPoint = getCenterPoint(new Rectangle(containerScreenPoint, component.getVisibleRect().getSize()), myContainer.getPreferredSize()); show(aContainer, popupPoint.x, popupPoint.y); } private static JComponent getTargetComponent(Component aComponent) { if (aComponent instanceof JComponent) { return (JComponent)aComponent; } else if (aComponent instanceof JFrame) { return ((JFrame)aComponent).getRootPane(); } else { return ((JDialog)aComponent).getRootPane(); } } public void showCenteredInCurrentWindow(@NotNull Project project) { Window window = null; Component focusedComponent = WindowManagerEx.getInstanceEx().getFocusedComponent(project); if (focusedComponent != null) { if (focusedComponent instanceof Window) { window = (Window)focusedComponent; } else { window = SwingUtilities.getWindowAncestor(focusedComponent); } } if (window == null) { window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); } showInCenterOf(window); } public void showUnderneathOf(@NotNull Component aComponent) { final JComponent component = getTargetComponent(aComponent); final Point point = aComponent.getLocationOnScreen(); point.y += component.getVisibleRect().height; show(aComponent, point.x, point.y); } private static Point getCenterPoint(Rectangle aContainerRec, Dimension aPopupSize) { Point result = new Point(); Point containerLocation = aContainerRec.getLocation(); Dimension containerSize = aContainerRec.getSize(); result.x = containerLocation.x + (containerSize.width / 2 - aPopupSize.width / 2); result.y = containerLocation.y + (containerSize.height / 2 - aPopupSize.height / 2); return result; } protected void disposeAllParents() { dispose(); if (myParent != null) { myParent.disposeAllParents(); } } public final void registerAction(@NonNls String aActionName, int aKeyCode, int aModifier, Action aAction) { getInputMap().put(KeyStroke.getKeyStroke(aKeyCode, aModifier), aActionName); getActionMap().put(aActionName, aAction); } protected abstract InputMap getInputMap(); protected abstract ActionMap getActionMap(); protected final void setParentValue(Object parentValue) { myParentValue = parentValue; } private static class MyContainer extends OpaquePanel implements DataProvider { MyContainer() { super(new BorderLayout(), Color.white); setFocusCycleRoot(true); } public Object getData(String dataId) { return null; } public Dimension getPreferredSize() { return computeNotBiggerDimension(super.getPreferredSize()); } private static Dimension computeNotBiggerDimension(Dimension ofContent) { int resultWidth = ofContent.width > MAX_SIZE.width ? MAX_SIZE.width : ofContent.width; int resultHeight = ofContent.height > MAX_SIZE.height ? MAX_SIZE.height : ofContent.height; return new Dimension(resultWidth, resultHeight); } } public BasePopup getParent() { return myParent; } public PopupStep getStep() { return myStep; } public final void dispatch(KeyEvent event) { if (event.getID() != KeyEvent.KEY_PRESSED) { return; } final KeyStroke stroke = KeyStroke.getKeyStroke(event.getKeyChar(), event.getModifiers(), false); if (getInputMap().get(stroke) != null) { final Action action = getActionMap().get(getInputMap().get(stroke)); if (action.isEnabled()) { action.actionPerformed(new ActionEvent(myContent, event.getID(), "", event.getWhen(), event.getModifiers())); return; } } process(event); mySpeedSearch.process(event); myMnemonicsSearch.process(event); } protected void process(KeyEvent aEvent) { } public Rectangle getBounds() { return new Rectangle(myContainer.getLocationOnScreen(), myContainer.getSize()); } // public Window getWindow() { // return myPopup; public JComponent getContainer() { return myContainer; } protected static BasePopup createPopup(BasePopup parent, PopupStep step, Object parentValue) { if (step instanceof ListPopupStep) { return new ListPopupImpl(parent, (ListPopupStep)step, parentValue); } else if (step instanceof TreePopupStep) { return new TreePopupImpl(parent, (TreePopupStep)step, parentValue); } else { throw new IllegalArgumentException(step.getClass().toString()); } } public final void actionPerformed(ActionEvent e) { myAutoSelectionTimer.stop(); if (getStep().isAutoSelectionEnabled()) { onAutoSelectionTimer(); } } protected final void restartTimer() { if (!myAutoSelectionTimer.isRunning()) { myAutoSelectionTimer.start(); } else { myAutoSelectionTimer.restart(); } } protected final void stopTimer() { myAutoSelectionTimer.stop(); } protected void onAutoSelectionTimer() { } protected void onSpeedSearchPatternChanged() { } public boolean shouldBeShowing(Object value) { if (!myStep.isSpeedSearchEnabled()) return true; SpeedSearchFilter<Object> filter = myStep.getSpeedSearchFilter(); if (!filter.canBeHidden(value)) return true; String text = filter.getIndexedString(value); return mySpeedSearch.shouldBeShowing(text); } public SpeedSearch getSpeedSearch() { return mySpeedSearch; } @NotNull JLabel getTitle() { return myTitle; } protected void onSelectByMnemonic(Object value) { } protected abstract void onChildSelectedFor(Object value); protected final void notifyParentOnChildSelection() { if (myParent == null || myParentValue == null) return; myParent.onChildSelectedFor(myParentValue); } public void setLocation(@NotNull final Point screenPoint) { JBPopupImpl.moveTo(myContainer, screenPoint, null); } public void setSize(@NotNull final Dimension size) { JBPopupImpl.setSize(myContainer, size); } private class MyComponentAdapter extends ComponentAdapter { public void componentMoved(final ComponentEvent e) { processParentWindowMoved(); } } }
package jp.wizcorp.phonegap.plugin.wizViewManager; import android.app.Activity; import android.content.res.AssetManager; import android.graphics.Color; import android.os.Build; import android.view.Gravity; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.RelativeLayout; import org.apache.cordova.CallbackContext; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.util.Log; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("SetJavaScriptEnabled") public class WizWebView extends WebView { private String TAG = "WizWebView"; private CallbackContext create_cb; private CallbackContext load_cb; private Context mContext; static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); public WizWebView(String viewName, JSONObject settings, Context context, CallbackContext callbackContext) { // Constructor method super(context); mContext = context; Log.d("WizWebView", "[WizWebView] *************************************"); Log.d("WizWebView", "[WizWebView] building - new Wizard View"); Log.d("WizWebView", "[WizWebView] -> " + viewName); Log.d("WizWebView", "[WizWebView] *************************************"); // Hold create callback and execute after page load this.create_cb = callbackContext; // Set invisible by default, developer MUST call show to see the view this.setVisibility(View.INVISIBLE); // WizWebView Settings WebSettings webSettings = this.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); // Whether or not on-screen controls are displayed can be set with setDisplayZoomControls(boolean). // The default is false. // The built-in mechanisms are the only currently supported zoom mechanisms, // so it is recommended that this setting is always enabled. webSettings.setBuiltInZoomControls(true); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { Level16Apis.enableUniversalAccess(webSettings); } this.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); this.loadUrl("javascript:window.name = '" + viewName + "';"); ViewGroup frame = (ViewGroup) ((Activity) context).findViewById(android.R.id.content); // Creating a new RelativeLayout fill its parent by default RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); // Default full screen frame.addView(this, rlp); this.setPadding(999, 0, 0, 0); // Set a transparent background this.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= 11) this.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); // Override url loading on WebViewClient this.setWebViewClient(new WebViewClient () { @Override public boolean shouldOverrideUrlLoading(WebView wView, String url) { Log.d("WizWebView", "[WizWebView] ****** " + url); String[] urlArray; String splitter = ": // Split url by only 2 in the event "://" occurs elsewhere (SHOULD be impossible because you string encoded right!?) urlArray = url.split(splitter,2); if (urlArray[0].equalsIgnoreCase("wizpostmessage")) { String[] msgData; splitter = "\\?"; // Split url by only 2 again to make sure we only spit at the first "?" msgData = urlArray[1].split(splitter); // target View = msgData[0] and message = msgData[1] // Get webview list from View Manager JSONObject viewList = WizViewManagerPlugin.getViews(); if (viewList.has(msgData[1]) ) { WebView targetView; try { targetView = (WebView) viewList.get(msgData[1]); // send data to mainView String data2send = msgData[2]; try { data2send = URLDecoder.decode(data2send, "UTF-8"); } catch (UnsupportedEncodingException e) { } data2send = data2send.replace("'", "\\'"); targetView.loadUrl("javascript:wizViewMessenger.__triggerMessageEvent('" + msgData[0] + "', '" + msgData[1] + "', '" + data2send + "', '" + msgData[3] + "');"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // app will handle this url, don't change the browser url return true; } if (urlArray[0].equalsIgnoreCase("wizmessageview") ) { String[] msgData; splitter = "\\?"; // Split url by only 2 again to make sure we only spit at the first "?" msgData = urlArray[1].split(splitter); // target View = msgData[0] and message = msgData[1] // Get webview list from View Manager JSONObject viewList = WizViewManagerPlugin.getViews(); if (viewList.has(msgData[0])) { WebView targetView; try { targetView = (WebView) viewList.get(msgData[0]); // send data to mainView String data2send = msgData[1]; data2send = data2send.replace("'", "\\'"); targetView.loadUrl("javascript:(wizMessageReceiver('" + data2send + "'))"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // app will handle this url, don't change the browser url return true; } // allow all other url requests return false; } @Override public void onPageFinished(WebView wView, String url) { WizViewManagerPlugin.updateViewList(); // Push wizViewMessenger String jsString = "var WizViewMessenger = function () {};\n" + "console.log('trythis');" + "WizViewMessenger.prototype.postMessage = function (message, targetView) { \n" + " var type;\n" + " if (Object.prototype.toString.call(message) === \"[object Array]\") {\n" + " type = \"Array\";\n" + " message = JSON.stringify(message);\n" + " } else if (Object.prototype.toString.call(message) === \"[object String]\") {\n" + " type = \"String\";\n" + " } else if (Object.prototype.toString.call(message) === \"[object Number]\") {\n" + " type = \"Number\";\n" + " message = JSON.stringify(message);\n" + " } else if (Object.prototype.toString.call(message) === \"[object Boolean]\") {\n" + " type = \"Boolean\";\n" + " message = message.toString();\n" + " } else if (Object.prototype.toString.call(message) === \"[object Function]\") {\n" + " type = \"Function\";\n" + " message = message.toString();\n" + " } else if (Object.prototype.toString.call(message) === \"[object Object]\") {\n" + " type = \"Object\";\n" + " message = JSON.stringify(message);\n" + " } else {\n" + " console.error(\"WizViewMessenger posted unknown type!\");\n" + " return;\n" + " }\n" + " \n" + "\tvar iframe = document.createElement('IFRAME');\n" + "\tiframe.setAttribute('src', 'wizPostMessage://'+ window.encodeURIComponent(window.name) + '?' + window.encodeURIComponent(targetView) + '?' + window.encodeURIComponent(message) + '?' + type );\n" + "\tsetTimeout(function () {" + "\tdocument.documentElement.appendChild(iframe);\n" + "\tiframe.parentNode.removeChild(iframe);\n" + "\tiframe = null;\t\t\n" + "\t}, 1);" + "};\n" + " \n" + "WizViewMessenger.prototype.__triggerMessageEvent = function (origin, target, data, type) { \n" + " if (type === \"Array\") {\n" + " data = JSON.parse(data);\n" + " } else if (type === \"String\") {\n" + " // Stringy String String\n" + " } else if (type === \"Number\") {\n" + " data = JSON.parse(data);\n" + " } else if (type === \"Boolean\") {\n" + " data = Boolean(data);\n" + " } else if (type === \"Function\") {\n" + " } else if (type === \"Object\") {\n" + " data = JSON.parse(data);\n" + " } else {\n" + " \tconsole.error(\"Message Event received unknown type!\");\n" + " return;\n" + " }\n" + "\t\n" + "\tvar event = document.createEvent(\"HTMLEvents\");\n" + "\tevent.initEvent(\"message\", true, true);\n" + "\tevent.eventName = \"message\";\n" + "\tevent.memo = { };\n" + "\tevent.origin = origin;\n" + "\tevent.source = target;\n" + "\tevent.data = data;\n" + "\tdispatchEvent(event);\n" + "};\n" + "\n" + "window.wizViewMessenger = new WizViewMessenger();"; wView.loadUrl("javascript:" + jsString); if (create_cb != null) { create_cb.success(); Log.d(TAG, "View created and loaded"); // Callback used, don't call it again. create_cb = null; } if (load_cb != null) { load_cb.success(); Log.d(TAG, "View finished load"); // Callback used, don't call it again. load_cb = null; } } public void onReceivedError(WebView view, int errorCod, String description, String failingUrl) { Log.e(TAG, "Error: Cannot load " + failingUrl + " \n Reason: " + description); if (create_cb != null) { create_cb.error(description); // Callback used, don't call it again. create_cb = null; } } }); // Analyse settings object if (settings != null) { this.setLayout(settings, create_cb); } else { // Apply Defaults this.setLayoutParams(COVER_SCREEN_GRAVITY_CENTER); } Log.d(TAG, "Create complete"); } public void setLayout(JSONObject settings, CallbackContext callback) { Log.d(TAG, "Setting up layout..."); String url; // Set default settings to max screen ViewGroup parent = (ViewGroup) this.getParent(); // Size int _parentHeight = parent.getHeight(); int _parentWidth = parent.getWidth(); int _height = _parentHeight; int _width = _parentWidth; // Margins int _x = 0; int _y = 0; int _top = 0; int _bottom = 0; int _right = 0; int _left = 0; if (settings.has("height")) { try { _height = settings.getInt("height"); } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'height' in settings"); } } if (settings.has("width")) { try { _width = settings.getInt("width"); } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'width' in settings"); } } if (settings.has("x")) { try { _x = settings.getInt("x"); _left = _x; _width = _width + _x; } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'x' in settings"); } } if (settings.has("y")) { try { _y = settings.getInt("y"); _top = _y; _height = _height + _y; } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'y' in settings"); } } if (settings.has("left")) { try { _left = _left + settings.getInt("left"); _width -= _left; } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'left' in settings"); } } else { // default if (_x != 0) { _left = _x; } } if (settings.has("right")) { try { _right = settings.getInt("right"); _width = _width - _right; } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'right' in settings"); } } if (settings.has("top")) { try { _top = _top + settings.getInt("top"); } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'top' in settings"); } } else { // default if (_y != 0) { _top = _y; } } if (settings.has("bottom")) { try { _top = _top + _parentHeight - _height - settings.getInt("bottom"); _bottom = - settings.getInt("bottom"); } catch (JSONException e) { // ignore Log.e(TAG, "Error obtaining 'bottom' in settings"); } } FrameLayout.LayoutParams newLayoutParams = (FrameLayout.LayoutParams) this.getLayoutParams(); newLayoutParams.setMargins(_left, _top, _right, _bottom); newLayoutParams.height = _height; newLayoutParams.width = _width; this.setLayoutParams(newLayoutParams); Log.d(TAG, "new layout -> width: " + newLayoutParams.width + " - height: " + newLayoutParams.height + " - margins: " + newLayoutParams.leftMargin + "," + newLayoutParams.topMargin + "," + newLayoutParams.rightMargin + "," + newLayoutParams.bottomMargin); if (settings.has("src")) { try { url = settings.getString("src"); load(url, callback); } catch (JSONException e) { // default // nothing to load Log.e(TAG, "Loading source from settings exception : " + e); } } else { Log.d(TAG, "No source to load"); } } public void load(String source, CallbackContext callbackContext) { // Link up our callback load_cb = callbackContext; // Check source extension try { URL url = new URL(source); // Check for the protocol url.toURI(); // Extra checking required for validation of URI // If we did not fall out here then source is a valid URI, check extension if (url.getPath().length() > 0) { // Not loading a straight domain, check extension of non-domain path String ext = MimeTypeMap.getFileExtensionFromUrl(url.getPath()); Log.d(TAG, "URL ext: " + ext); if (validateExtension("." + ext)) { // Load this this.loadUrl(source); } else { // Check if file type is in the helperList if (requiresHelper("." + ext)) { // Load this this.loadUrl("http://docs.google.com/gview?embedded=true&url=" + source); } else { // Not valid extension in whitelist and cannot be helped Log.e(TAG, "Not a valid file extension!"); if (load_cb != null) { load_cb.error("Not a valid file extension."); load_cb = null; } } } return; } else { Log.d(TAG, "load URL: " + source); this.loadUrl(source); } } catch (MalformedURLException ex1) { // Missing protocol, assume local file // Check cache for latest file File cache = mContext.getApplicationContext().getCacheDir(); File file = new File(cache.getAbsolutePath() + "/" + source); if (file.exists()) { // load it Log.d(TAG, "load: " + "file:///" + cache.getAbsolutePath() + "/" + source); source = ("file:///" + cache.getAbsolutePath() + "/" + source); } else { // Check file exists in bundle assets AssetManager mg = mContext.getResources().getAssets(); try { mg.open("www/" + source); Log.d(TAG, "load: file:///android_asset/www/" + source); source = "file:///android_asset/www/" + source; } catch (IOException ex) { // Not in bundle assets. Try full path file = new File(source); if (file.exists()) { Log.d(TAG, "load: file:///" + source); source = "file:///" + source; file = null; } else { // File cannot be found Log.e(TAG, "File: " + source + " cannot be found!"); if (load_cb != null) { load_cb.error("File: " + source + " cannot be found!"); load_cb = null; } return; } } } this.loadUrl(source); } catch (URISyntaxException ex2) { Log.e(TAG, "URISyntaxException loading: file://" + source); if (load_cb != null) { load_cb.error("URISyntaxException loading: file://" + source); load_cb = null; } } } private boolean validateExtension(String candidate) { for (String s: WizViewManagerPlugin.whitelist) { // Check extension exists in whitelist if (s.equalsIgnoreCase(candidate)) { return true; } } return false; } private boolean requiresHelper(String candidate) { for (String s: WizViewManagerPlugin.helperList) { // Check extension exists in helperList if (s.equalsIgnoreCase(candidate)) { return true; } } return false; } @TargetApi(16) private static class Level16Apis { static void enableUniversalAccess(WebSettings settings) { settings.setAllowUniversalAccessFromFileURLs(true); } } }
package org.eclipse.xtext.scoping.impl; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.scoping.IScope; import com.google.common.collect.Iterables; /** * A scope implemented using a {@link Map} used for efficient lookup of ordinary named * {@link org.eclipse.xtext.resource.EObjectDescription EObjectDescriptions}. * * This implementation assumes, that the keys of the {@link Map} correspond to the keys of the contained {@link org.eclipse.xtext.resource.EObjectDescription}. * Additionally it assumes, that those keys are equal to <code>description.getName().toLowerCase()</code>. * * When looking up elements using {@link #getElements(QualifiedName)} this implementation looks up the the elements from the map, hence are much * more efficient for many {@link IEObjectDescription}s. * * @author Sven Efftinge - Initial contribution and API * @author Sebastian Zarnekow */ public class MapBasedScope extends AbstractScope { public static IScope createScope(IScope parent, Iterable<IEObjectDescription> descriptions, boolean ignoreCase) { Map<QualifiedName, IEObjectDescription> map = null; for(IEObjectDescription description: descriptions) { if (map == null) map = new LinkedHashMap<QualifiedName, IEObjectDescription>(4); QualifiedName name = ignoreCase ? description.getName().toLowerCase() : description.getName(); IEObjectDescription previous = map.put(name, description); // we are optimistic that no duplicate names are used // however, if the name was already used, the first one should win if (previous != null) { map.put(name, previous); } } if (map == null || map.isEmpty()) { return parent; } return new MapBasedScope(parent, map, ignoreCase); } /** * @since 2.3 */ public static IScope createScope(IScope parent, Collection<IEObjectDescription> descriptions) { if (descriptions.size() == 1) { IEObjectDescription description = Iterables.getOnlyElement(descriptions); return new MapBasedScope(parent, Collections.singletonMap(description.getName(), description), false); } else if (descriptions.isEmpty()) { return parent; } return createScope(parent, descriptions, false); } public static IScope createScope(IScope parent, Iterable<IEObjectDescription> descriptions) { return createScope(parent, descriptions, false); } private Map<QualifiedName, IEObjectDescription> elements; protected MapBasedScope(IScope parent, Map<QualifiedName, IEObjectDescription> elements, boolean ignoreCase) { super(parent, ignoreCase); this.elements = elements; } @Override protected Iterable<IEObjectDescription> getAllLocalElements() { return elements.values(); } @Override protected Iterable<IEObjectDescription> getLocalElementsByName(QualifiedName name) { IEObjectDescription result = null; if (isIgnoreCase()) { result = elements.get(name.toLowerCase()); } else { result = elements.get(name); } if (result == null) return Collections.emptyList(); return Collections.singleton(result); } @Override protected boolean isShadowed(IEObjectDescription fromParent) { if (isIgnoreCase()) { boolean result = elements.containsKey(fromParent.getName().toLowerCase()); return result; } else { boolean result = elements.containsKey(fromParent.getName()); return result; } } }
package biz.aQute.resolve; import static test.lib.Utils.createRepo; import java.io.File; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.mockito.Mockito; import org.osgi.framework.Version; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.service.log.LogService; import org.osgi.service.repository.Repository; import org.osgi.service.resolver.ResolutionException; import org.osgi.service.resolver.Resolver; import aQute.bnd.build.Run; import aQute.bnd.build.Workspace; import aQute.bnd.build.model.BndEditModel; import aQute.bnd.build.model.EE; import aQute.bnd.build.model.clauses.ExportedPackage; import aQute.bnd.header.Parameters; import aQute.bnd.http.HttpClient; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.repository.ResourcesRepository; import aQute.bnd.osgi.resource.CapReqBuilder; import aQute.bnd.osgi.resource.ResourceBuilder; import aQute.bnd.repository.osgi.OSGiRepository; import aQute.lib.io.IO; import aQute.libg.reporter.ReporterAdapter; import junit.framework.TestCase; import test.lib.MockRegistry; @SuppressWarnings({ "restriction", "deprecation" }) public class ResolveTest extends TestCase { private static final LogService log = new LogReporter(new ReporterAdapter(System.out)); /** * Observed at the OSGi Community Event. When specifying the following: * -resolve.effective: active;skip:="osgi.service" OSGi service capabilities * are skipped but other active-time requirements are used. This is correct, * but it only works if the property is defined directly inside the bndrun * being resolved. If the property is inherited from a parent bndrun then it * no longer applies... * <p> * Tried this but seems to work in all combinations as expected */ public void testIncludeBndrun() throws Exception { assertInclude("intop.bndrun", "top"); assertInclude("ininclude.bndrun", "include"); assertInclude("inworkspace.bndrun", "workspace"); } /* * Create a BndrunResolveContext with a skip of 'workspace' in the * workspace, and then use different files that get -resolve.effective from * the include file or the bndrun file. */ private void assertInclude(String file, String value) throws Exception { LogService log = Mockito.mock(LogService.class); File f = IO.getFile("testdata/resolve/includebndrun/" + file); File wsf = IO.getFile("testdata/ws"); try (Workspace ws = new Workspace(wsf)) { ws.setProperty("-resolve.effective", "active;skip:='workspace'"); Run run = Run.createRun(ws, f); BndrunResolveContext context = new BndrunResolveContext(run, run, ws, log); context.init(); Map<String, Set<String>> effectiveSet = context.getEffectiveSet(); assertNotNull(effectiveSet.get("active")); assertTrue(effectiveSet.get("active") .contains(value)); } } /** * Missing default version */ public void testDefaultVersionsForJava() throws Exception { Run run = Run.createRun(null, IO.getFile("testdata/defltversions/run.bndrun")); try (Workspace w = run.getWorkspace(); ProjectResolver pr = new ProjectResolver(run);) { Map<Resource, List<Wire>> resolve = pr.resolve(); assertTrue(pr.check()); assertNotNull(resolve); assertTrue(resolve.size() > 0); System.out.println(resolve); } } /** * The enRoute base guard resolved but is missing bundles, the runbundles do * not run */ public void testenRouteGuard() throws Exception { MockRegistry registry = new MockRegistry(); Repository repo = createRepo(IO.getFile("testdata/enroute/index.xml"), getName()); registry.addPlugin(repo); List<Requirement> reqs = CapReqBuilder.getRequirementsFrom( new Parameters("osgi.wiring.package;filter:='(osgi.wiring.package=org.osgi.service.async)'")); Collection<Capability> pack = repo.findProviders(reqs) .get(reqs.get(0)); assertEquals(2, pack.size()); ResourceBuilder b = new ResourceBuilder(); File guard = IO.getFile("testdata/enroute/osgi.enroute.base.guard.jar"); Domain manifest = Domain.domain(guard); b.addManifest(manifest); Repository resourceRepository = new ResourcesRepository(b.build()); registry.addPlugin(resourceRepository); Processor model = new Processor(); model.setRunfw("org.eclipse.osgi"); model.setRunblacklist( "osgi.identity;filter:='(osgi.identity=osgi.enroute.base.api)',osgi.identity;filter:='(osgi.identity=osgi.cmpn)',osgi.identity;filter:='(osgi.identity=osgi.core)"); model.setRunRequires("osgi.identity;filter:='(osgi.identity=osgi.enroute.base.guard)'"); model.setRunee("JavaSE-1.8"); try (ResolverLogger logger = new ResolverLogger(4)) { BndrunResolveContext context = new BndrunResolveContext(model, null, registry, log); Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); } catch (ResolutionException e) { String msg = e.getMessage() .replaceAll("\\[caused by:", "\n->"); System.out.println(msg); fail(msg); } } /** * Test if we can augment * * @throws Exception */ public void testResolveWithAugments() throws Exception { // Add requirement assertAugmentResolve( "org.apache.felix.gogo.shell;capability:='foo;foo=gogo';requirement:='foo;filter:=\"(foo=*)\"'", "foo;filter:='(foo=gogo)'", null); // Default effective assertAugmentResolve("org.apache.felix.gogo.shell;capability:='foo;foo=gogo'", "foo;filter:='(foo=*)'", null); // Wildcard name assertAugmentResolve("*.shell;capability:='foo;foo=gogo'", "foo;filter:='(foo=gogo)'", null); assertAugmentResolve("org.apache.felix.gogo.*;capability:='foo;foo=gogo'", "foo;filter:='(foo=*)'", null); assertAugmentResolveFails("gogo.*;capability:='foo;foo=gogo'", "foo;filter:='(foo=*)'", null); // Version range assertAugmentResolve("org.apache.felix.gogo.*;version='[0,1)';capability:='foo;foo=gogo'", "foo;filter:='(foo=*)'", null); assertAugmentResolveFails("org.apache.felix.gogo.*;version='[1,2)';capability:='foo;foo=gogo'", "foo;filter:='(foo=*)'", null); // Effective assertAugmentResolve("org.apache.felix.gogo.shell;capability:='foo;foo=gogo;effective:=foo'", "foo;filter:='(foo=gogo)';effective:=foo", "foo"); assertAugmentResolveFails("org.apache.felix.gogo.shell;capability:='foo;foo=gogo;effective:=bar'", "foo;filter:='(foo=*)';effective:=foo", "foo"); } private void assertAugmentResolveFails(String augment, String require, String effective) throws Exception { try { assertAugmentResolve(augment, require, effective); fail("Failed to fail augment=" + augment + ", require=" + require + ", effective=" + effective); } catch (AssertionError | ResolutionException e) { // Yup, expected } } private void assertAugmentResolve(String augment, String require, String effective) throws Exception { MockRegistry registry = new MockRegistry(); registry.addPlugin(createRepo(IO.getFile("testdata/repo3.index.xml"), getName())); Processor model = new Processor(); model.setRunfw("org.apache.felix.framework"); model.setProperty("-augment", augment); model.setRunRequires(require); if (effective != null) model.setProperty("-resolve.effective", effective); BndrunResolveContext context = new BndrunResolveContext(model, null, registry, log); try (ResolverLogger logger = new ResolverLogger(4)) { Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); Resource resource = getResource(resources, "org.apache.felix.gogo.runtime", "0.10"); assertNotNull(resource); } } /** * Test minimal setup * * @throws URISyntaxException * @throws MalformedURLException */ public void testMinimalSetup() throws Exception { try (OSGiRepository repo = new OSGiRepository(); HttpClient httpClient = new HttpClient()) { Map<String, String> map = new HashMap<>(); map.put("locations", IO.getFile("testdata/repo3.index.xml") .toURI() .toString()); map.put("name", getName()); map.put("cache", new File("generated/tmp/test/cache/" + getName()).getAbsolutePath()); repo.setProperties(map); Processor model = new Processor(); model.addBasicPlugin(httpClient); repo.setRegistry(model); model.setProperty("-runfw", "org.apache.felix.framework"); model.setProperty("-runrequires", "osgi.identity;filter:='(osgi.identity=org.apache.felix.gogo.shell)'"); BndrunResolveContext context = new BndrunResolveContext(model, null, model, log); context.setLevel(0); context.addRepository(repo); context.init(); try (ResolverLogger logger = new ResolverLogger(4)) { Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); Resource shell = getResource(resources, "org.apache.felix.gogo.shell", "0.10.0"); assertNotNull(shell); } catch (ResolutionException e) { e.printStackTrace(); fail("Resolve failed"); } } } /** * Test if we can resolve with a distro * * @throws ResolutionException */ public void testResolveWithDistro() throws Exception { MockRegistry registry = new MockRegistry(); registry.addPlugin(createRepo(IO.getFile("testdata/repo3.index.xml"), getName())); BndEditModel model = new BndEditModel(); model.setDistro(Arrays.asList("testdata/distro.jar;version=file")); List<Requirement> requires = new ArrayList<>(); CapReqBuilder capReq = CapReqBuilder.createBundleRequirement("org.apache.felix.gogo.shell", "[0,1)"); requires.add(capReq.buildSyntheticRequirement()); model.setRunRequires(requires); BndrunResolveContext context = new BndrunResolveContext(model, registry, log); context.setLevel(0); context.init(); try (ResolverLogger logger = new ResolverLogger(4)) { Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); Resource shell = getResource(resources, "org.apache.felix.gogo.shell", "0.10.0"); assertNotNull(shell); } } /** * This is a basic test of resolving. This test is paired with * {@link #testResolveWithDistro()}. If you change the resources, make sure * this is done in the same way. The {@link #testResolveWithDistro()} has a * negative check while this one checks positive. */ public void testSimpleResolve() throws Exception { MockRegistry registry = new MockRegistry(); registry.addPlugin(createRepo(IO.getFile("testdata/repo3.index.xml"), getName())); BndEditModel model = new BndEditModel(); model.setRunFw("org.apache.felix.framework"); List<Requirement> requires = new ArrayList<>(); CapReqBuilder capReq = CapReqBuilder.createBundleRequirement("org.apache.felix.gogo.shell", "[0,1)"); requires.add(capReq.buildSyntheticRequirement()); model.setRunRequires(requires); BndrunResolveContext context = new BndrunResolveContext(model, registry, log); try (ResolverLogger logger = new ResolverLogger()) { Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); Resource resource = getResource(resources, "org.apache.felix.gogo.runtime", "0.10"); assertNotNull(resource); } catch (ResolutionException e) { fail("Resolve failed"); } } /** * Check if we can resolve against capabilities defined on the -provided */ // public static void testResolveWithProfile() throws Exception { // Resolver resolver = new BndResolver(new ResolverLogger(4)); // MockRegistry registry = new MockRegistry(); // registry.addPlugin(createRepo(IO.getFile("testdata/repo3.index.xml"))); // BndEditModel model = new BndEditModel(); // // Provided capabilities // model.setRunFw("org.apache.felix.framework"); // model.setGenericString(Constants.DISTRO, // "testdata/repo1/org.apache.felix.gogo.runtime-0.10.0.jar;version=file"); // // We require gogo, but now the gogo runtime is on the runpath // // so should be excluded // Requirement erq = // CapReqBuilder.createPackageRequirement("org.apache.felix.gogo.api", // "0.10.0") // .buildSyntheticRequirement(); // model.setRunRequires(Arrays.asList(erq)); // BndrunResolveContext context = new BndrunResolveContext(model, registry, // log); // context.setLevel(4); // context.init(); // Map<Resource,List<Wire>> resolved = resolver.resolve(context); // List<Wire> wires = resolved.get(context.getInputResource()); // assertNotNull(wires); // boolean found = false; // for ( Wire wire : wires ) { // if (equals(wire.getRequirement(), erq)) { // found = true; // assertTrue(wire.getProvider().equals(context.getSystemResource())); // assertTrue("System resource not found for wire", found); // Set<Resource> resources = resolved.keySet(); // Resource resource = getResource(resources, // "org.apache.felix.gogo.runtime", "0.10"); // assertNull(resource); // private static boolean equals(Requirement a, Requirement b) { // if ( a== b) // return true; // if ( a == null || b == null) // return false; // if ( a.equals(b)) // return true; // if ( !a.getNamespace().equals(b.getNamespace())) // return false; // return a.getDirectives().equals(b.getDirectives()) && // a.getAttributes().equals(b.getAttributes()); private static Resource getResource(Set<Resource> resources, String bsn, String versionString) { for (Resource resource : resources) { List<Capability> identities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE); if (identities != null && identities.size() == 1) { Capability idCap = identities.get(0); Object id = idCap.getAttributes() .get(IdentityNamespace.IDENTITY_NAMESPACE); Object version = idCap.getAttributes() .get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); if (bsn.equals(id)) { if (versionString == null) { return resource; } Version requested = Version.parseVersion(versionString); Version current; if (version instanceof Version) { current = (Version) version; } else { current = Version.parseVersion((String) version); } if (requested.equals(current)) { return resource; } } } } return null; } /** * Simple test that resolves a requirement * * @throws ResolutionException */ public void testMultipleOptionsNotDuplicated() throws Exception { // Resolve against repo 5 MockRegistry registry = new MockRegistry(); registry.addPlugin(createRepo(IO.getFile("testdata/repo5/index.xml"), getName())); // Set up a simple Java 7 Felix requirement as per Issue #971 BndEditModel runModel = new BndEditModel(); runModel.setRunFw("org.apache.felix.framework;version='4.2.1'"); runModel.setEE(EE.JavaSE_1_7); runModel.setSystemPackages(Collections.singletonList(new ExportedPackage("org.w3c.dom.traversal", null))); runModel.setGenericString("-resolve.effective", "active"); // Require the log service, GoGo shell and GoGo commands List<Requirement> requirements = new ArrayList<>(); requirements .add(new CapReqBuilder("osgi.identity").addDirective("filter", "(osgi.identity=org.apache.felix.log)") .buildSyntheticRequirement()); requirements.add( new CapReqBuilder("osgi.identity").addDirective("filter", "(osgi.identity=org.apache.felix.gogo.shell)") .buildSyntheticRequirement()); requirements.add( new CapReqBuilder("osgi.identity").addDirective("filter", "(osgi.identity=org.apache.felix.gogo.command)") .buildSyntheticRequirement()); runModel.setRunRequires(requirements); // Resolve the bndrun BndrunResolveContext context = new BndrunResolveContext(runModel, registry, log); Resolver resolver = new BndResolver(new org.apache.felix.resolver.Logger(4)); Collection<Resource> resolvedResources = new ResolveProcess() .resolveRequired(runModel, registry, resolver, Collections.emptyList(), log) .keySet(); Map<String, Resource> mandatoryResourcesBySymbolicName = new HashMap<>(); for (Resource r : resolvedResources) { Capability cap = r.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE) .get(0); // We shouldn't have more than one match for each symbolic name for // this resolve String symbolicName = (String) cap.getAttributes() .get(IdentityNamespace.IDENTITY_NAMESPACE); assertNull("Multiple results for " + symbolicName, mandatoryResourcesBySymbolicName.put(symbolicName, r)); } assertEquals(4, resolvedResources.size()); } /** * Test that latest bundle is selected when namespace is 'osgi.service' * * @throws Exception */ public void testLatestBundleServiceNamespace() throws Exception { try (OSGiRepository repo = new OSGiRepository(); HttpClient httpClient = new HttpClient()) { Map<String, String> map = new HashMap<>(); map.put("locations", IO.getFile("testdata/repo8/index.xml") .toURI() .toString()); map.put("name", getName()); map.put("cache", new File("generated/tmp/test/cache/" + getName()).getAbsolutePath()); repo.setProperties(map); Processor model = new Processor(); model.addBasicPlugin(httpClient); repo.setRegistry(model); model.setProperty("-runfw", "org.apache.felix.framework"); model.setProperty("-runrequires", "osgi.service;filter:='(objectClass=org.osgi.service.component.runtime.ServiceComponentRuntime)'"); BndrunResolveContext context = new BndrunResolveContext(model, null, model, log); context.setLevel(0); context.addRepository(repo); context.init(); try (ResolverLogger logger = new ResolverLogger(4)) { Resolver resolver = new BndResolver(logger); Map<Resource, List<Wire>> resolved = resolver.resolve(context); Set<Resource> resources = resolved.keySet(); Resource scr = getResource(resources, "org.apache.felix.scr", "2.0.14"); assertNotNull(scr); } catch (ResolutionException e) { e.printStackTrace(); fail("Resolve failed"); } } } }
package org.intermine.bio.web.logic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.web.logic.bag.InterMineBag; import org.flymine.model.genomic.Chromosome; import org.flymine.model.genomic.Gene; import org.flymine.model.genomic.Organism; /** * Utility methods for the flymine package. * @author Julie Sullivan */ public abstract class BioUtil { /** * For a bag of genes, returns a list of organisms * @param os ObjectStore * @param bag InterMineBag * @return collection of organism names */ public static Collection getOrganisms(ObjectStore os, InterMineBag bag) { Query q = new Query(); Model model = os.getModel(); QueryClass qcGene = null; try { qcGene = new QueryClass(Class.forName(model.getPackageName() + "." + bag.getType())); } catch (ClassNotFoundException e) { return null; } QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfOrganismName = new QueryField(qcOrganism, "name"); QueryField qfGeneId = new QueryField(qcGene, "id"); q.addFrom(qcGene); q.addFrom(qcOrganism); q.addToSelect(qfOrganismName); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); BagConstraint bc = new BagConstraint(qfGeneId, ConstraintOp.IN, bag.getOsb()); cs.addConstraint(bc); QueryObjectReference qr = new QueryObjectReference(qcGene, "organism"); ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism); cs.addConstraint(cc); q.setConstraint(cs); q.addToOrderBy(qfOrganismName); Results r = os.execute(q); Iterator it = r.iterator(); Collection<String> organismNames = new ArrayList<String>(); while (it.hasNext()) { ResultsRow rr = (ResultsRow) it.next(); organismNames.add((String) rr.get(0)); } return organismNames; } /** * Return a list of chromosomes for specified organism * @param os ObjectStore * @param organism Organism name * @return collection of chromosome names */ public static Collection getChromosomes(ObjectStore os, String organism) { // SELECT DISTINCT o // FROM org.flymine.model.genomic.Chromosome AS c, // org.flymine.model.genomic.Organism AS o // WHERE c.organism CONTAINS o /* TODO put this in a config file */ // TODO this may well go away once chromosomes sorted out in #1186 if (organism.equals("Drosophila melanogaster")) { ArrayList<String> chromosomes = new ArrayList<String>(); chromosomes.add("2L"); chromosomes.add("2R"); chromosomes.add("3L"); chromosomes.add("3R"); chromosomes.add("4"); chromosomes.add("U"); chromosomes.add("X"); return chromosomes; } Query q = new Query(); QueryClass qcChromosome = new QueryClass(Chromosome.class); QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfChromosome = new QueryField(qcChromosome, "identifier"); QueryField organismNameQF = new QueryField(qcOrganism, "name"); q.addFrom(qcChromosome); q.addFrom(qcOrganism); q.addToSelect(qfChromosome); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryObjectReference qr = new QueryObjectReference(qcChromosome, "organism"); ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism); cs.addConstraint(cc); SimpleConstraint sc = new SimpleConstraint(organismNameQF, ConstraintOp.EQUALS, new QueryValue(organism)); cs.addConstraint(sc); q.setConstraint(cs); q.addToOrderBy(qfChromosome); Results r = os.execute(q); Iterator it = r.iterator(); Collection<String> chromosomes = new ArrayList<String>(); while (it.hasNext()) { ResultsRow rr = (ResultsRow) it.next(); chromosomes.add((String) rr.get(0)); } return chromosomes; } /** * * @param os * @param organisms * @return total number of genes in the database for selected organims */ public static int getGeneTotal(ObjectStore os, Collection organisms) { Query q = new Query(); q.setDistinct(false); QueryClass qcGene = new QueryClass(Gene.class); QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfOrganism = new QueryField(qcOrganism, "name"); QueryFunction geneCount = new QueryFunction(); q.addFrom(qcGene); q.addFrom(qcOrganism); q.addToSelect(geneCount); ConstraintSet cs; cs = new ConstraintSet(ConstraintOp.AND); /* organism is in bag */ BagConstraint bc2 = new BagConstraint(qfOrganism, ConstraintOp.IN, organisms); cs.addConstraint(bc2); /* gene is from organism */ QueryObjectReference qr2 = new QueryObjectReference(qcGene, "organism"); ContainsConstraint cc2 = new ContainsConstraint(qr2, ConstraintOp.CONTAINS, qcOrganism); cs.addConstraint(cc2); q.setConstraint(cs); Results r = os.execute(q); Iterator it = r.iterator(); ResultsRow rr = (ResultsRow) it.next(); Long l = (java.lang.Long) rr.get(0); int n = l.intValue(); return n; } }
package barbarahliskov.cambialibros; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.Buffer; import java.util.ArrayList; import java.util.List; public class UsuariosFavoritos extends AppCompatActivity { private ListView mList; /** * Called when the activity is first created. * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); setTitle("Usuarios favoritos"); Button closeButton = (Button) findViewById(R.id.botonCerrar); closeButton.setVisibility(View.INVISIBLE); mList = (ListView)findViewById(R.id.list); mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView Clicked item index long itemPosition = id; // ListView Clicked item value //int itemValue = mList.getitem // Show Alert Toast.makeText(getApplicationContext(), "Hiciste click en el número " + itemPosition, Toast.LENGTH_LONG).show(); Intent i = new Intent(UsuariosFavoritos.this, PerfilUsuarios.class); startActivity(i); } }); /* PRUEBAS */ String prueba = "<busqueda nick=\"Barbara96\">\n" + "<gente>\n" + "<usuario>\n" + "\t<nick>paco91</nick>\n" + "\t<nombre>paco</nombre>\n" + "\t<apellidos>Peperoni</apellidos>\n" + "\t<valoracion>4.4</valoracion>\n" + "\t<favorito>True</favorito>\n" + "</usuario>\n" + "<usuario>\n" + "\t<nick>Debora</nick>\n" + "\t<nombre>UnTio</nombre>\n" + "\t<apellidos>ConApellidos</apellidos>\n" + "\t<valoracion>5.0</valoracion>\n" + "\t<favorito>False</favorito>\n" + "</usuario>\n" + "</gente>\n" + "</busqueda>"; String prueba2 = "<busqueda nick=\"Barbara96\">\n" + "<gente>\n" + "<usuario>\n" + "\t<nick>paco91</nick>\n" + "\t<nombre>paco</nombre>\n" + "\t<apellidos>Peperoni</apellidos>\n" + "\t<valoracion>4.4</valoracion>\n" + "\t<favorito>True</favorito>\n" + "</usuario>\n" + "</gente>\n" + "</busqueda>"; /* FIN DE PRUEBAS */ Bundle b = getIntent().getExtras(); if (b == null) { new UsuariosFavoritos.SearchFavsUsersTask().execute(prueba); }else{ new UsuariosFavoritos.SearchFavsUsersTask().execute(prueba2); } //new UsuariosFavoritos.SearchFavsUsersTask().execute(prueba); } private void fillData(ArrayList<String> parametros){ if (parametros != null) { List<Row> rows = new ArrayList<Row>(); Row row = null; for (int i = 0; i < parametros.size(); i = i + 5) { rows.add(new Row(parametros.get(i), "", "", (long) 0)); } /* rows.add(new Row("Juan123", "Zaragoza", "",(long) 0)); rows.add(new Row("Vic93", "Zaragoza", "", (long) 1)); rows.add(new Row("Aniita94", "Huesca", "", (long) 2)); rows.add(new Row("Teresa", "Barcelona", "", (long) 4)); rows.add(new Row("usuario6", "Teruel","", (long) 4)); rows.add(new Row("Pedro.Garcia", "Zaragoza", "", (long) 4)); */ if (!rows.isEmpty()) { TextView empty = (TextView) findViewById(R.id.empty); empty.setWidth(0); } CustomArrayAdapter c = new CustomArrayAdapter(this, rows) { @Override public void onClick(View v) { Button button = (Button) v; /*if (button.isActivated()) { button.setBackgroundResource(R.drawable.ic_slide_switch_on); Toast.makeText(getApplicationContext(), "Guardado como favorito", Toast.LENGTH_SHORT).show(); button.setActivated(false); } else { button.setBackgroundResource(R.drawable.ic_slide_switch_off); Toast.makeText(getApplicationContext(), "Favorito borrado", Toast.LENGTH_SHORT).show(); button.setActivated(true); }*/ button.setBackgroundResource(R.drawable.ic_slide_switch_off); //this.getView((int) v.getTag(), v); String user = (String) v.getTag(R.id.key_1); Toast.makeText(this.getContext(), user + " eliminado de favoritos", Toast.LENGTH_SHORT).show(); button.setActivated(true); // Eliminar de favoritos new UsuariosFavoritos.DeleteFavUserTask().execute(user); // Volver a cargar favoritos //new UsuariosFavoritos.SearchFavsUsersTask().execute(prueba); Intent intent = new Intent(UsuariosFavoritos.this, UsuariosFavoritos.class); Bundle b = new Bundle(); b.putSerializable("n", 1); intent.putExtras(b); startActivity(intent); finish(); /* startActivity(new Intent(UsuariosFavoritos.this, UsuariosFavoritos.class)); finish();*/ } }; c.setIds(R.layout.rows_usuarios_favoritos, R.id.ciudadF, R.id.nombreF, R.id.usuarioF, R.id.distF, R.id.botonFav); mList.setAdapter(c); } } private class SearchFavsUsersTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... data) { try { String miNombre = "Laura"; String url = "http://10.0.2.2:8080/CambiaLibros/SearchFavUserServlet?nick=" + miNombre; HttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(); URI website = new URI(url); request.setURI(website); HttpResponse response = httpClient.execute(request); /* Recibir respuesta */ /* Supongamos que lo tenemos */ String result = data[0]; ArrayList<String> parametros = XML_Parser.parseaResultadoFavsUsers(result); fillData(parametros); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return "BIEN"; } /* protected void onPostExecute(String page) { //textView.setText(page); Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT); toast.show(); } */ } private class DeleteFavUserTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... data) { // EN principio, el parametro llevara los datos String text = ""; BufferedReader reader = null; try { String miNombre = "Laura"; String user = data[0]; String url = "http://10.0.2.2:8080/CambiaLibros/DeleteFavUserServlet"; HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("nick", miNombre)); postParameters.add(new BasicNameValuePair("fav_nick", user)); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); request.setEntity(formEntity); httpClient.execute(request); // Defined URL where to send data } catch(Exception e) { // Do something about exceptions e.printStackTrace(); } return "BIEN"; } /* protected void onPostExecute(String page) { //textView.setText(page); Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT); toast.show(); } */ } }
package com.ibm.mil.cafejava; import android.content.Context; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.worklight.wlclient.api.WLClient; import com.worklight.wlclient.api.WLFailResponse; import com.worklight.wlclient.api.WLProcedureInvocationData; import com.worklight.wlclient.api.WLRequestOptions; import com.worklight.wlclient.api.WLResponse; import com.worklight.wlclient.api.WLResponseListener; import java.lang.reflect.Type; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; /** * @author John Petitto (github @jpetitto) * @author Tanner Preiss (github @t-preiss) */ public final class CafeJava { private int timeout = 30_000; private Object invocationContext; /** * setTimeout() sets the timeout for all MFP procedure and connection calls made using * this API. * * @param timeout The current timeout, in milliseconds, to wait for a procedure or connection to respond. * @return CafeJava returns the instance of CafaJava class, which is useful for chaining calls. */ public CafeJava setTimeout(int timeout) { if (timeout >= 0) { this.timeout = timeout; } return this; } /** * getTimeout() returns the current timeout used when waiting for a procedure or connection to respond. * If no value has been set using setTimeout() then getTimeout() will return * the default timeout of 30_000 (milliseconds). * * @return timeout The current timeout, in milliseconds, to wait for a procedure or connection to respond. */ public int getTimeout() { return timeout; } /** * setInvocationContext() User can add to the request any object, that will be available on the callback (success/failure) functions. * * @param invocationContext An object that is returned with WLResponse to the listener methods onSuccess and onFailure. * You can use this object to identify and distinguish different invokeProcedure calls. * This object is returned as is to the listener methods. * @return CafeJava returns the instance of CafaJava class, which is useful for chaining calls. */ public CafeJava setInvocationContext(Object invocationContext) { this.invocationContext = invocationContext; return this; } /** * getInvocationContext() return the user invocation context * * @return An object that is returned with WLResponse to the listener methods onSuccess and onFailure. * You can use this object to identify and distinguish different invokeProcedure calls. * This object is returned as is to the listener methods */ public Object getInvocationContext(Object invocationContext) { return this.invocationContext; } /** * connect() This method sends an initialization request to the MobileFirst Platform Server, * establishes a connection with the server, and validates the application version. * * @param context object that is returned with WLResponse to the listener methods onSuccess an * onFailure. * You can use this object to identify and distinguish different invokeProcedure calls. * This object is returned as is to the listener methods. * @return an Observable that will emit a WLResponse for the connection. */ public Observable<WLResponse> connect(final Context context) { return Observable.create(new Observable.OnSubscribe<WLResponse>() { @Override public void call(Subscriber<? super WLResponse> subscriber) { WLClient client = WLClient.createInstance(context); client.connect(new RxResponseListener(subscriber), getRequestOptions()); } }); } public Observable<WLResponse> invokeProcedure(final String adapterName, final String procedureName, final Object... parameters) { return Observable.create(new Observable.OnSubscribe<WLResponse>() { @Override public void call(Subscriber<? super WLResponse> subscriber) { WLClient client = WLClient.getInstance(); if (client == null) { subscriber.onError(new Throwable("WLClient instance does not exist")); return; } WLProcedureInvocationData invocationData = new WLProcedureInvocationData(adapterName, procedureName, false); invocationData.setParameters(parameters); client.invokeProcedure(invocationData, new RxResponseListener(subscriber), getRequestOptions()); } }); } public static <T> Observable.Transformer<WLResponse, T> serializeTo(final Class<T> clazz, final String... memberNames) { return transformJson(new Func1<WLResponse, T>() { @Override public T call(WLResponse wlResponse) { JsonElement element = parseNestedJson(wlResponse, memberNames); return new Gson().fromJson(element, clazz); } }); } public static <T> Observable.Transformer<WLResponse, T> serializeTo(final Type type, final String... memberNames) { return transformJson(new Func1<WLResponse, T>() { @Override public T call(WLResponse wlResponse) { JsonElement element = parseNestedJson(wlResponse, memberNames); return new Gson().fromJson(element, type); } }); } private static <T> Observable.Transformer<WLResponse, T> transformJson(final Func1<WLResponse, T> func) { return new Observable.Transformer<WLResponse, T>() { @Override public Observable<T> call(Observable<WLResponse> wlResponseObservable) { return wlResponseObservable.map(func); } }; } private static JsonElement parseNestedJson(WLResponse wlResponse, String... memberNames) { String json = wlResponse.getResponseJSON().toString(); JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); for (int i = 0, size = memberNames.length; i < size; i++) { String member = memberNames[i]; if (i == size - 1) { return jsonObject.get(member); } else { jsonObject = jsonObject.getAsJsonObject(member); } } return jsonObject; } ; private WLRequestOptions getRequestOptions() { WLRequestOptions requestOptions = new WLRequestOptions(); requestOptions.setTimeout(timeout); requestOptions.setInvocationContext(invocationContext); return requestOptions; } private static class RxResponseListener implements WLResponseListener { private Subscriber<? super WLResponse> subscriber; RxResponseListener(Subscriber<? super WLResponse> subscriber) { this.subscriber = subscriber; } @Override public void onSuccess(WLResponse wlResponse) { subscriber.onNext(wlResponse); subscriber.onCompleted(); } @Override public void onFailure(WLFailResponse wlFailResponse) { subscriber.onError(new Throwable(wlFailResponse.getErrorMsg())); } } }
package mondrian.util; import mondrian.olap.Util; import java.util.*; import junit.framework.TestCase; /** * Test case for {@link ObjectPool}. * * @version $Id$ * @author Richard Emberson */ public class ObjectPoolTest extends TestCase { public ObjectPoolTest() { super(); } public ObjectPoolTest(String name) { super(name); } static class KeyValue { long key; Object value; KeyValue(long key, Object value) { this.key = key; this.value = value; } public int hashCode() { return (int)(key ^ (key >>> 32)); } public boolean equals(Object o) { return (o instanceof KeyValue) ? (((KeyValue) o).key == this.key) : false; } public String toString() { return value.toString(); } } public void testString() throws Exception { // for reasons unknown this fails with java4 if (Util.PreJdk15) { return; } ObjectPool<String> strings = new ObjectPool<String>(); int nos = 100000; String[] ss1 = genStringsArray(nos); for (int i = 0; i < nos; i++) { strings.add(ss1[i]); } assertEquals("size not equal", nos, strings.size()); // second array of strings, same as the first but different objects String[] ss2 = genStringsArray(nos); for (int i = 0; i < nos; i++) { String s = strings.add(ss2[i]); assertEquals("string not equal: " +s, s, ss2[i]); assertFalse("same object", (s == ss2[i])); } strings.clear(); assertEquals("size not equal", 0, strings.size()); nos = 25; ss1 = genStringsArray(nos); for (int i = 0; i < nos; i++) { strings.add(ss1[i]); } assertEquals("size not equal", nos, strings.size()); List<String> l = genStringsList(nos); Iterator<String> it = strings.iterator(); while (it.hasNext()) { String s = it.next(); l.remove(s); } assertTrue("list not empty", l.isEmpty()); } public void testKeyValue() throws Exception { ObjectPool<KeyValue> op = new ObjectPool<KeyValue>(); int nos = 100000; KeyValue[] kv1 = genKeyValueArray(nos); for (int i = 0; i < nos; i++) { op.add(kv1[i]); } assertEquals("size not equal", nos, op.size()); // second array of KeyValues, same as the first but different objects KeyValue[] kv2 = genKeyValueArray(nos); for (int i = 0; i < nos; i++) { KeyValue kv = op.add(kv2[i]); assertEquals("KeyValue not equal: " +kv, kv, kv2[i]); assertFalse("same object", (kv == kv2[i])); } op.clear(); assertEquals("size not equal", 0, op.size()); nos = 25; kv1 = genKeyValueArray(nos); for (int i = 0; i < nos; i++) { op.add(kv1[i]); } assertEquals("size not equal", nos, op.size()); List<KeyValue> l = genKeyValueList(nos); Iterator<KeyValue> it = op.iterator(); while (it.hasNext()) { KeyValue kv = it.next(); l.remove(kv); } assertTrue("list not empty", l.isEmpty()); } /** * Tests ObjectPools containing large numbers of integer and string keys, * and makes sure they return the same results as HashSet. Optionally * measures performance. */ public void testLarge() { // Some typical results (2.4 GHz Intel dual-core). // Key type: Integer String // Implementation: ObjectPool HashSet ObjectPool HashSet // With density=0.01, 298,477 distinct entries, 7,068 hits // 300,000 adds 221 ms 252 ms 293 ms 1013 ms // 700,000 gets 164 ms 148 ms 224 ms 746 ms // With density=0.5, 236,022 distinct entries, 275,117 hits // 300,000 adds 175 ms 250 ms 116 ms 596 ms // 700,000 gets 147 ms 176 ms 190 ms 757 ms // With density=0.999, 189,850 distinct entries, 442,618 hits // 300,000 adds 128 ms 185 ms 99 ms 614 ms // 700,000 gets 133 ms 184 ms 130 ms 830 ms checkLargeMulti(300000, 0.01, 700000, 298477, 7068); checkLargeMulti(300000, 0.5, 700000, 236022, 275117); checkLargeMulti(300000, 0.999, 700000, 189850, 442618); } private void checkLargeMulti( int entryCount, double density, int retrieveCount, int expectedDistinct, int expectedHits) { checkLarge( true, true, entryCount, density, retrieveCount, expectedDistinct, expectedHits); checkLarge( false, true, entryCount, density, retrieveCount, expectedDistinct, expectedHits); checkLarge( false, true, entryCount, density, retrieveCount, expectedDistinct, expectedHits); checkLarge( false, false, entryCount, density, retrieveCount, expectedDistinct, expectedHits); } private void checkLarge( boolean usePool, boolean intKey, int entryCount, double density, int retrieveCount, int expectedDistinct, int expectedHits) { final boolean print = false; final long t1 = System.currentTimeMillis(); assert density > 0 && density <= 1; int space = (int) (entryCount / density); ObjectPool<Object> objectPool = new ObjectPool<Object>(); HashSet<Object> set = new HashSet<Object>(); Random random = new Random(1234); int distinctCount = 0; final String longString = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyy"; for (int i = 0; i < entryCount; i++) { final Object key = intKey ? random.nextInt(space) : longString + random.nextInt(space); if (usePool) { if (objectPool.add(key) != null) { ++distinctCount; } } else { if (set.add(key)) { ++distinctCount; } } } final long t2 = System.currentTimeMillis(); int hitCount = 0; for (int i = 0; i < retrieveCount; i++) { final Object key = intKey ? random.nextInt(space) : longString + random.nextInt(space); if (usePool) { if (objectPool.contains(key)) { ++hitCount; } } else { if (set.contains(key)) { ++hitCount; } } } final long t3 = System.currentTimeMillis(); if (usePool) { // todo: assertEquals(expectedDistinct, objectPool.size()); distinctCount = objectPool.size(); } else { assertEquals(expectedDistinct, set.size()); } if (print) { System.out.println( "Using " + (usePool ? "ObjectPool" : "HashSet") + ", density=" + density + ", " + distinctCount + " distinct entries, " + hitCount + " hits"); System.out.println( entryCount + " adds took " + (t2 - t1) + " milliseconds"); System.out.println( retrieveCount + " gets took " + (t3 - t2) + " milliseconds"); } assertEquals(expectedDistinct, distinctCount); assertEquals(expectedHits, hitCount); } // helpers private static String[] genStringsArray(int nos) { List l = genStringsList(nos); return (String[]) l.toArray(new String[l.size()]); } private static List<String> genStringsList(int nos) { List<String> l = new ArrayList<String>(nos); for (int i = 0; i < nos; i++) { l.add(Integer.valueOf(i).toString()); } return l; } private static KeyValue[] genKeyValueArray(int nos) { List<KeyValue> l = genKeyValueList(nos); return (KeyValue[]) l.toArray(new KeyValue[l.size()]); } private static List<KeyValue> genKeyValueList(int nos) { List<KeyValue> l = new ArrayList<KeyValue>(nos); for (int i = 0; i < nos; i++) { l.add(new KeyValue((long)i, Integer.valueOf(i))); } return l; } } // End ObjectPoolTest.java
package com.hhl.tubatu; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class ClipViewPager extends ViewPager { public ClipViewPager(Context context) { super(context); } public ClipViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_UP) { View view = viewOfClickOnScreen(ev); if (view != null) { int index = (Integer) view.getTag(); if (getCurrentItem() != index) { setCurrentItem(index); } } } return super.dispatchTouchEvent(ev); } /** * @param ev * @return */ private View viewOfClickOnScreen(MotionEvent ev) { int childCount = getChildCount(); int currentIndex = getCurrentItem(); int[] location = new int[2]; for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int position = (Integer) v.getTag(); v.getLocationOnScreen(location); int minX = location[0]; int minY = location[1]; int maxX = location[0] + v.getWidth(); int maxY = location[1] + v.getHeight(); if(position < currentIndex){ maxX -= v.getWidth() * (1 - ScalePageTransformer.MIN_SCALE) * 0.5 + v.getWidth() * (Math.abs(1 - ScalePageTransformer.MAX_SCALE)) * 0.5; minX -= v.getWidth() * (1 - ScalePageTransformer.MIN_SCALE) * 0.5 + v.getWidth() * (Math.abs(1 - ScalePageTransformer.MAX_SCALE)) * 0.5; }else if(position == currentIndex){ minX += v.getWidth() * (Math.abs(1 - ScalePageTransformer.MAX_SCALE)); }else if(position > currentIndex){ maxX -= v.getWidth() * (Math.abs(1 - ScalePageTransformer.MAX_SCALE)) * 0.5; minX -= v.getWidth() * (Math.abs(1 - ScalePageTransformer.MAX_SCALE)) * 0.5; } float x = ev.getRawX(); float y = ev.getRawY(); if ((x > minX && x < maxX) && (y > minY && y < maxY)) { return v; } } return null; } }
package com.project.distractless; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewAnimationUtils; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.TextView; public class Pin extends AppCompatActivity { //String for passwordFile public static boolean fromList = false; public static final String KEY = "KeyFile"; String keyInstance; TextView keyView; TextView keyPrompt; String keyEntry = ""; SharedPreferences keyStore; Boolean noKey; @Override protected void onResume() { super.onResume(); if (fromList){ keyPrompt.setText("Congratulations! Enter Your Key to Unlock Your Phone!"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* Instantiations: keyPrompt will change it's output depending on if there is a valid key stored in memory, or depending on if the user key entered matched the stored key or not. keyView is used for feedback to display the number of digits (in password form) user enters. keyStore reads the saved key value. keyInstance will parse the string from keyStore, and if there is no value present a default value of A will be passed to the variable. */ keyPrompt = (TextView) findViewById(R.id.keyPrompt); keyView = (TextView) findViewById(R.id.keyView); keyStore = getSharedPreferences(KEY, 0); keyInstance = keyStore.getString("keyValue", "a"); //The following will adjust the keyPrompt output depending on if keyInstance pulls the //default value from keyStore or not. if (!fromList && keyInstance.equals("a")){ keyPrompt.setText("Select A 6 Digit Key"); noKey = true; } else if (fromList){ keyPrompt.setText("Congratulations! Enter Key to Unlock Your Phone!"); } else { keyPrompt.setText("Enter Your Key"); noKey = false; } } /* Void numPad is used with a series of Case Statements for an OnClick return, which will allow us to easily code the return values for all of the numbers in the numberpad instead of having to code an on-click listener for each of the 10 buttons. */ public void numPad (View view){ switch(view.getId()){ case R.id.numPad1: numData("1"); break; case R.id.numPad2: numData("2"); break; case R.id.numPad3: numData("3"); break; case R.id.numPad4: numData("4"); break; case R.id.numPad5: numData("5"); break; case R.id.numPad6: numData("6"); break; case R.id.numPad7: numData("7"); break; case R.id.numPad8: numData("8"); break; case R.id.numPad9: numData("9"); break; case R.id.numPad0: numData("0"); break; } } /* Void numData checks the value of the user-entered string after every button press, up to a maximum of 6 presses, and checks it against several conditions. noKey is a boolean assignment that looks for a default value assigned to the key in memory, if the default value is present then the value is replaced by the newly entered key. */ public void numData (String num){ keyEntry = keyEntry + num; keyView.setText(keyEntry); if (keyEntry.length() == 6 && noKey){ keyPrompt.setText("Saved!"); SharedPreferences.Editor keyEdit = keyStore.edit(); keyEdit.putString("keyValue", keyEntry); keyEdit.commit(); keyEntry = ""; exitReveal(); } else if (!fromList && keyEntry.equals(keyInstance)) { keyPrompt.setText("Match!"); exitReveal(); } else if (fromList && keyEntry.equals(keyInstance)){ keyPrompt.setText("Bye!"); finish(); } else if (keyEntry.length() == 6 && !keyEntry.equals(keyInstance)){ keyPrompt.setText("Invalid Password"); keyEntry = ""; keyView.setText(keyEntry); } } /* exitRevel creates a circular reveal animation for transition from activity to activity. it reads the screen size, and determines the center of the screen, for it's start and end parameters. */ void exitReveal() { final View mTransition = findViewById(R.id.pinScreen); //Get Center of screen for clip int cx = mTransition.getMeasuredWidth()/2; int cy = mTransition.getMeasuredHeight()/2; //get final radius of clipping circle int finalRadius = Math.max(mTransition.getWidth(), mTransition.getHeight())/2; //Create an Animator for the view Animator anim = ViewAnimationUtils.createCircularReveal(mTransition, cx, cy, finalRadius, 0); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); //mTransition.setVisibility(View.INVISIBLE); Tutorial tut = new Tutorial(); Intent intent = tut.ActivitySwitch(Pin.this, SetAlarm.class, 1); startActivity(intent); } }); anim.setInterpolator(new AccelerateDecelerateInterpolator()); anim.setDuration(550); anim.start(); } }
package com.unipad.http; public class HttpConstant { public static final String LOGIN = "/api/user/login"; public static final String GET_USER_GAME_LIST = "/api/match/getMatchByUser"; public static String Regist = "/api/user/regist"; public static String UPLOAD = "/api/file/upload"; public static String GET_NEWS_LIST = "/api/news/list"; public static String AUTH_PATH = "/api/user/auth"; public static String AUTH_INFO_PATH = "/api/user/data"; public static String GET_RULE = "/api/match/getRule"; public static String APPLY_GAME = "/api/match/apply"; public static String PATH_FILE_URL = "http://192.168.0.104:8090/crazybrain-mng/image/getFile?filePath="; public static String UPDATE_USERINFO = "/api/user/modify"; public static String USER_APPLYED_HTTP= "/api/user/myApply"; public static String USER_IN_GAME_HTTP = "/api/match/checkMatchStart"; public static int JSON_ERREO = -2; public static final int LOGIN_UPDATE_UI = 0x10000; public static final int LOGIN_WRONG_MSG = 0x10001; public static final int CITY_GET_HOME_GAME_LIST = 0x10002; public static final int CHINA_GET_HOME_GAME_LIST = 0x10003; public static final int WORD_GET_HOME_GAME_LIST = 0x10004; public static final int CITY_APPLY_GAME = 0x10005; public static final int CHINA_APPLY_GAME = 0x10006; public static final int WORD_APPLY_GAME = 0x10007; public static final int USER_AUTH=0x10100; public static final int UOLOAD_AUTH_FILE =0x10200; public static final int PERSONALDATA=0x10300; public static final int USER_AUTH_INFO=0x10400; public static final int USER_APPLYED = 0x10500; public static final int USER_IN_GAEM = 0x10600; }
package de.sopa.scene.game; import de.sopa.model.game.GameService; import de.sopa.model.game.Level; import de.sopa.observer.GameSceneObserver; import de.sopa.scene.BaseScene; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.scene.background.Background; import org.andengine.entity.text.Text; import org.andengine.input.touch.detector.ContinuousHoldDetector; import org.andengine.util.color.Color; /** * @author David Schilling - davejs92@gmail.com * @author Raphael Schilling */ public abstract class GameScene extends BaseScene implements GameSceneObserver { protected GameService gameService; private ContinuousHoldDetector continuousHoldDetector; private float spacePerTile; private Text scoreText; private GameFieldView gameFieldView; protected final Level level; protected Level levelBackup; public GameScene(Level level) { super(); this.level = level; initializeLogic(); calculateSpacePerTile(gameService.getLevel().getField().length - 2); levelBackup = new Level(gameService.getLevel()); addBackground(); addTiles(); addButtons(); addScoreText(); addCustomLabels(); registerTouchHandler(); resourcesManager.musicService.stopMusic(); } protected abstract void addCustomLabels(); @Override public void updateGameScene() { if (gameService.solvedPuzzle()) { setOnSceneTouchListener(null); gameService.detatch(this); baseScene.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { baseScene.unregisterUpdateHandler(pTimerHandler); onSolvedGame(); } })); } scoreText.setText(String.valueOf(gameService.getLevel().getMovesCount())); updateTiles(gameService.solvedPuzzle()); } private void addTiles() { float tilesSceneStartY = getTileSceneStartY(); gameFieldView = new GameFieldView(0 - spacePerTile, tilesSceneStartY, spacePerTile, gameService, resourcesManager.regionTileMap, vbom, resourcesManager.tilesBorderRegion); gameFieldView.addTiles(false); attachChild(gameFieldView); } private void updateTiles(final boolean finished) { baseScene.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { detachChild(gameFieldView); gameFieldView.addTiles(finished); attachChild(gameFieldView); } })); } private void calculateSpacePerTile(int width) { spacePerTile = camera.getWidth() / width; } private float getTileSceneStartY() { return (camera.getHeight() - (spacePerTile * gameService.getLevel().getField().length)) / 2; } private void addScoreText() { scoreText = new Text(camera.getWidth() * 0.67f, camera.getHeight() * 0.03f, resourcesManager.scoreFont, String.valueOf(gameService.getLevel().getMovesCount()), 4, vbom); attachChild(scoreText); Text score = new Text(camera.getWidth() * 0.67f, camera.getHeight() * 0.01f, resourcesManager.levelFont, "Current Moves", vbom); score.setScaleCenter(0, 0); score.setScale(0.3f); attachChild(score); Text minimumMovesScoreText = new Text(0, camera.getHeight() * 0.01f, resourcesManager.minMovesFont, "Min. Moves", vbom); minimumMovesScoreText.setScaleCenter(0, 0); minimumMovesScoreText.setScale(0.3f); attachChild(minimumMovesScoreText); Text minimumMovesScore = new Text(0, camera.getHeight() * 0.03f, resourcesManager.minMovesFont, String.valueOf(gameService.getLevel().getMinimumMovesToSolve()), vbom); attachChild(minimumMovesScore); } private void registerTouchHandler() { GameSceneSingleMoveDetector gameSceneSingleMoveDetector = new GameSceneSingleMoveDetector(0, getTileSceneStartY() + spacePerTile, spacePerTile, gameFieldView, gameService); continuousHoldDetector = new ContinuousHoldDetector(0, 100, 0.01f, gameSceneSingleMoveDetector); setOnSceneTouchListener(continuousHoldDetector); } protected abstract void addButtons(); private void addBackground() { setBackground(new Background(Color.BLACK)); } protected abstract void initializeLogic(); @Override public abstract void onBackKeyPressed(); @Override public void disposeScene() { final GameScene gameScene = this; engine.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { engine.unregisterUpdateHandler(pTimerHandler); gameScene.detachChildren(); } })); } /** * is called when the game is solved. */ public abstract void onSolvedGame(); /** * is called when the game is lost. */ public abstract void onLostGame(); }
package gc.david.dfm.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.common.collect.Lists; import com.inmobi.commons.InMobi; import com.inmobi.monetization.IMBanner; import com.inmobi.monetization.IMBannerListener; import com.inmobi.monetization.IMErrorCode; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphViewSeries; import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle; import com.jjoe64.graphview.LineGraphView; import com.splunk.mint.Mint; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.InjectView; import gc.david.dfm.DFMApplication; import gc.david.dfm.R; import gc.david.dfm.adapter.DistanceAdapter; import gc.david.dfm.adapter.MarkerInfoWindowAdapter; import gc.david.dfm.adapter.NavigationDrawerItemAdapter; import gc.david.dfm.map.Haversine; import gc.david.dfm.map.LocationUtils; import gc.david.dfm.model.DaoSession; import gc.david.dfm.model.Distance; import gc.david.dfm.model.Position; import static butterknife.ButterKnife.inject; import static gc.david.dfm.Utils.isOnline; import static gc.david.dfm.Utils.showAlertDialog; import static gc.david.dfm.Utils.toastIt; /** * Implements the app main Activity. * * @author David */ public class MainActivity extends ActionBarActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final int ELEVATION_SAMPLES = 100; private final int FIRST_DRAWER_ITEM_INDEX = 1; @InjectView(R.id.elevationchart) protected RelativeLayout rlElevationChart; @InjectView(R.id.closeChart) protected ImageView ivCloseElevationChart; private GoogleMap googleMap = null; // A request to connect to Location Services private LocationRequest locationRequest = null; // Stores the current instantiation of the location client in this object private GoogleApiClient googleApiClient = null; private Location currentLocation = null; // Moves to current position if app has just started private boolean appHasJustStarted = true; private String distanceMeasuredAsText = ""; private MenuItem searchMenuItem = null; // Show position if we come from other app (p.e. Whatsapp) private boolean mustShowPositionWhenComingFromOutside = false; private LatLng sendDestinationPosition = null; private IMBanner banner = null; private boolean bannerShown = false; private boolean elevationChartShown = false; @SuppressWarnings("rawtypes") private AsyncTask showingElevationTask = null; private GraphView graphView = null; private float DEVICE_DENSITY; private ActionBarDrawerToggle actionBarDrawerToggle; private DrawerLayout drawerLayout; private ListView drawerList; private DistanceMode distanceMode; private List<LatLng> coordinates; private boolean calculatingDistance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mint.initAndStartSession(MainActivity.this, "6f2149e6"); // Enable logging Mint.enableLogging(true); setContentView(R.layout.activity_main); inject(this); DEVICE_DENSITY = getResources().getDisplayMetrics().density; googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); final SupportMapFragment fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)); googleMap = fragment.getMap(); if (googleMap != null) { googleMap.setMyLocationEnabled(true); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // InMobi Ads InMobi.initialize(this, "9b61f509a1454023b5295d8aea4482c2"); banner = (IMBanner) findViewById(R.id.banner); if (banner != null) { banner.setRefreshInterval(30); banner.setIMBannerListener(new IMBannerListener() { @Override public void onShowBannerScreen(IMBanner arg0) { } @Override public void onLeaveApplication(IMBanner arg0) { } @Override public void onDismissBannerScreen(IMBanner arg0) { } @Override public void onBannerRequestSucceeded(IMBanner arg0) { bannerShown = true; fixMapPadding(); } @Override public void onBannerRequestFailed(IMBanner arg0, IMErrorCode arg1) { } @Override public void onBannerInteraction(IMBanner arg0, Map<String, String> arg1) { } }); banner.loadBanner(); } if (!isOnline(getApplicationContext())) { showWifiAlertDialog(); } googleMap.setOnMapLongClickListener(new OnMapLongClickListener() { @Override public void onMapLongClick(LatLng point) { calculatingDistance = true; if (distanceMode == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (coordinates == null || coordinates.isEmpty()) { toastIt(getString(R.string.toast_first_point_needed), getApplicationContext()); } else { coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } } // calcular la distancia else if (currentLocation != null) { if ((distanceMode == DistanceMode.DISTANCE_FROM_CURRENT_POINT) && (coordinates.isEmpty())) { coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } calculatingDistance = false; } }); googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { if (distanceMode == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } else { // calcular la distancia if (currentLocation != null) { if (coordinates != null) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } else { throw new IllegalStateException("Empty coordinates list"); } } } } }); // TODO Release 1.5 // googleMap.setOnMarkerDragListener(new OnMarkerDragListener() { //// private String selectedMarkerId; // @Override // public void onMarkerDragStart(Marker marker) { //// selectedMarkerId = null; //// final String markerId = marker.getId(); //// if (coordinates.contains(markerId)) { //// for (int i = 0; i < coordinates.size(); i++) { //// final LatLng position = coordinates.get(i); //// if (markerId.latitude == position.latitude && //// markerId.longitude == position.longitude) { //// selectedMarkerId = i; //// break; // @Override // public void onMarkerDragEnd(Marker marker) { //// if (selectedMarkerId != -1) { //// coordinates.set(selectedMarkerId, marker.getPosition()); //// // NO movemos el zoom porque estamos simplemente afinando la //// drawAndShowMultipleDistances(coordinates, "", false, false); // @Override // public void onMarkerDrag(Marker marker) { // // nothing googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { final Intent showInfoActivityIntent = new Intent(MainActivity.this, ShowInfoActivity.class); showInfoActivityIntent.putExtra(ShowInfoActivity.POSITIONS_LIST_EXTRA_KEY_NAME, Lists.newArrayList(coordinates)); showInfoActivityIntent.putExtra(ShowInfoActivity.DISTANCE_EXTRA_KEY_NAME, distanceMeasuredAsText); startActivity(showInfoActivityIntent); } }); googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter(this)); // Iniciando la app if (currentLocation == null) { toastIt(getString(R.string.toast_loading_position), getApplicationContext()); } handleIntents(getIntent()); final List<String> distanceModes = Lists.newArrayList(getString(R.string.navigation_drawer_starting_point_current_position_item), getString(R.string.navigation_drawer_starting_point_any_position_item)); final List<Integer> distanceIcons = Lists.newArrayList(R.drawable.ic_action_device_gps_fixed, R.drawable.ic_action_communication_location_on); drawerList = (ListView) findViewById(R.id.left_drawer); // TODO cambiar esto por un header como dios manda final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View convertView = inflater.inflate(R.layout.simple_textview_list_item, drawerList, false); final TextView tvListElement = (TextView) convertView.findViewById(R.id.simple_textview); tvListElement.setText(getString(R.string.navigation_drawer_starting_point_header)); tvListElement.setClickable(false); tvListElement.setTextColor(getResources().getColor(R.color.white)); drawerList.addHeaderView(convertView); drawerList.setAdapter(new NavigationDrawerItemAdapter(this, distanceModes, distanceIcons)); drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.progressdialog_search_position_message, R.string.progressdialog_search_position_message) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); supportInvalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); supportInvalidateOptionsMenu(); } }; drawerLayout.setDrawerListener(actionBarDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); if (savedInstanceState == null) { // TODO change this because the header!!!! selectItem(FIRST_DRAWER_ITEM_INDEX); } } } private DaoSession getApplicationDaoSession() { return ((DFMApplication) getApplicationContext()).getDaoSession(); } /** * Swaps starting point in the main content view */ private void selectItem(int position) { if (position != 0) { distanceMode = (position == FIRST_DRAWER_ITEM_INDEX) ? // TODO change this because the header!!!! DistanceMode.DISTANCE_FROM_CURRENT_POINT : DistanceMode.DISTANCE_FROM_ANY_POINT; Mint.addExtraData("distanceMode", String.valueOf(distanceMode)); // Highlight the selected item and close the drawer drawerList.setItemChecked(position, true); drawerLayout.closeDrawer(drawerList); calculatingDistance = false; coordinates = Lists.newArrayList(); googleMap.clear(); if (showingElevationTask != null) { showingElevationTask.cancel(true); } rlElevationChart.setVisibility(View.INVISIBLE); elevationChartShown = false; fixMapPadding(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. actionBarDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); actionBarDrawerToggle.onConfigurationChanged(newConfig); } @Override protected void onNewIntent(Intent intent) { setIntent(intent); handleIntents(intent); } /** * Handles all Intent types. * * @param intent The input intent. */ private void handleIntents(final Intent intent) { if (intent != null) { if (intent.getAction().equals(Intent.ACTION_SEARCH)) { handleSearchIntent(intent); } else if (intent.getAction().equals(Intent.ACTION_VIEW)) { try { handleViewPositionIntent(intent); } catch (Exception e) { e.printStackTrace(); } } } } /** * Handles a search intent. * * @param intent Input intent. */ private void handleSearchIntent(final Intent intent) { final String query = intent.getStringExtra(SearchManager.QUERY); if (currentLocation != null) { new SearchPositionByName().execute(query); } MenuItemCompat.collapseActionView(searchMenuItem); } /** * Handles a send intent with position data. * * @param intent Input intent with position data. */ private void handleViewPositionIntent(final Intent intent) throws Exception { final Uri uri = intent.getData(); Mint.addExtraData("queryParameter", uri.toString()); final String uriScheme = uri.getScheme(); if (uriScheme.equals("geo")) { final String schemeSpecificPart = uri.getSchemeSpecificPart(); final Matcher matcher = getMatcherForUri(schemeSpecificPart); if (matcher.find()) { if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) { if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label) setDestinationPosition(matcher); } else { // Manage geo:0,0?q=my+street+address String destination = Uri.decode(uri.getQuery()).replace('+', ' '); destination = destination.replace("q=", ""); // TODO check this ugly workaround new SearchPositionByName().execute(destination); mustShowPositionWhenComingFromOutside = true; } } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom setDestinationPosition(matcher); } } else { throw new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); } } else if ((uriScheme.equals("http") || uriScheme.equals("https")) && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude final String queryParameter = uri.getQueryParameter("q"); if (queryParameter != null) { final Matcher matcher = getMatcherForUri(queryParameter); if (matcher.find()) { setDestinationPosition(matcher); } else { throw new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); } } else { throw new NoSuchFieldException("Query sin parámetro q."); } } else { throw new Exception("Imposible tratar la query " + uri.toString()); } } private void setDestinationPosition(final Matcher matcher) { sendDestinationPosition = new LatLng(Double.valueOf(matcher.group(1)), Double.valueOf(matcher.group(2))); mustShowPositionWhenComingFromOutside = true; } private Matcher getMatcherForUri(final String schemeSpecificPart) { final String regex = "(\\-?\\d+\\.*\\d*),(\\-?\\d+\\.*\\d*)"; final Pattern pattern = Pattern.compile(regex); return pattern.matcher(schemeSpecificPart); } /** * Shows the wireless centralized settings in API<11, otherwise shows general settings */ private void showWifiAlertDialog() { showAlertDialog((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB ? android.provider.Settings.ACTION_WIRELESS_SETTINGS : android.provider.Settings.ACTION_SETTINGS), getString(R.string.dialog_connection_problems_title), getString(R.string.dialog_connection_problems_message), getString(R.string.dialog_connection_problems_positive_button), getString(R.string.dialog_connection_problems_negative_button), MainActivity.this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the options menu from XML final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); searchMenuItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); // Configure the search info and add any event listeners final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); // Indicamos que la activity actual sea la buscadora searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setSubmitButtonEnabled(false); searchView.setQueryRefinementEnabled(true); searchView.setIconifiedByDefault(true); final MenuItem loadItem = menu.findItem(R.id.action_load); // TODO hacerlo en segundo plano final List<Distance> allDistances = getApplicationDaoSession().loadAll(Distance.class); if (allDistances.size() == 0) { loadItem.setVisible(false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (actionBarDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.action_search: return true; case R.id.action_load: loadDistancesFromDB(); return true; case R.id.menu_rateapp: showRateDialog(); return true; case R.id.menu_legalnotices: showGooglePlayServiceLicenseDialog(); return true; case R.id.menu_settings: openSettingsActivity(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(Gravity.START)) { drawerLayout.closeDrawer(Gravity.START); } else { super.onBackPressed(); } } /** * Loads all entries stored in the database and show them to the user in a * dialog. */ private void loadDistancesFromDB() { // TODO hacer esto en segundo plano final List<Distance> allDistances = getApplicationDaoSession().loadAll(Distance.class); if (allDistances != null && allDistances.size() > 0) { final DistanceAdapter distanceAdapter = new DistanceAdapter(this, allDistances); final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.dialog_load_distances_title)) .setAdapter(distanceAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final Distance distance = distanceAdapter.getDistanceList().get(which); final List<Position> positionList = getApplicationDaoSession().getPositionDao() ._queryDistance_PositionList(distance.getId()); coordinates.clear(); coordinates.addAll(convertPositionListToLatLngList(positionList)); drawAndShowMultipleDistances(coordinates, distance.getName() + "\n", true, true); } }).create().show(); } } private List<LatLng> convertPositionListToLatLngList(final List<Position> positionList) { final List<LatLng> result = Lists.newArrayList(); for (final Position position : positionList) { result.add(new LatLng(position.getLatitude(), position.getLongitude())); } return result; } /** * Shows settings activity. */ private void openSettingsActivity() { startActivity(new Intent(MainActivity.this, SettingsActivity.class)); } /** * Shows rate dialog. */ private void showRateDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_rate_app_title) .setMessage(R.string.dialog_rate_app_message) .setPositiveButton(getString(R.string.dialog_rate_app_positive_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openPlayStoreAppPage(); } }) .setNegativeButton(getString(R.string.dialog_rate_app_negative_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openFeedbackActivity(); } }).create().show(); } /** * Opens Google Play Store, in Distance From Me page */ private void openPlayStoreAppPage() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=gc.david.dfm"))); } /** * Opens the feedback activity. */ private void openFeedbackActivity() { final Intent openFeedbackActivityIntent = new Intent(MainActivity.this, FeedbackActivity.class); startActivity(openFeedbackActivityIntent); } private void showGooglePlayServiceLicenseDialog() { final String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext()); final AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this); LicenseDialog.setTitle(R.string.menu_legal_notices_title); LicenseDialog.setMessage(LicenseInfo); LicenseDialog.show(); } /** * Called when the Activity is no longer visible at all. Stop updates and * disconnect. */ @Override public void onStop() { if (googleApiClient.isConnected()) { stopPeriodicUpdates(); } super.onStop(); } /** * Called when the Activity is restarted, even before it becomes visible. */ @Override public void onStart() { super.onStart(); /* * Connect the client. Don't re-start any requests here; instead, wait * for onResume() */ googleApiClient.connect(); } /** * Called when the system detects that this Activity is now visible. */ @SuppressLint("NewApi") @Override public void onResume() { super.onResume(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { invalidateOptionsMenu(); } checkPlayServices(); } @Override public void onDestroy() { if (showingElevationTask != null) { showingElevationTask.cancel(true); } super.onDestroy(); } /** * Handle results returned to this Activity by other Activities started with * startActivityForResult(). In particular, the method onConnectionFailed() * in LocationUpdateRemover and LocationUpdateRequester may call * startResolutionForResult() to start an Activity that handles Google Play * services problems. The result of this call returns here, to * onActivityResult. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { // Choose what to do based on the request code switch (requestCode) { // If the request code matches the code sent in onConnectionFailed case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST: switch (resultCode) { // If Google Play services resolved the problem case Activity.RESULT_OK: // Log the result // Log.d(LocationUtils.APPTAG, getString(R.string.resolved)); // Display the result // mConnectionState.setText(R.string.connected); // mConnectionStatus.setText(R.string.resolved); break; // If any other result was returned by Google Play services default: // Log the result // Log.d(LocationUtils.APPTAG, // getString(R.string.no_resolution)); // Display the result // mConnectionState.setText(R.string.disconnected); // mConnectionStatus.setText(R.string.no_resolution); break; } // If any other request code was received default: // Report that this Activity received an unknown requestCode // Log.d(LocationUtils.APPTAG, // getString(R.string.unknown_activity_request_code, requestCode)); break; } } /** * Checks if Google Play Services is available on the device. * * @return Returns <code>true</code> if available; <code>false</code> * otherwise. */ private boolean checkPlayServices() { final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); // de error y devolvemos falso if (resultCode == ConnectionResult.SUCCESS) { return true; } else { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { final int RQS_GooglePlayServices = 1; GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices).show(); } else { // Log.i("checkPlayServices", "Dispositivo no soportado"); finish(); } return false; } } /** * Called by Location Services when the request to connect the client * finishes successfully. At this point, you can request the current * location or start periodic updates */ @Override public void onConnected(Bundle bundle) { startPeriodicUpdates(); } @Override public void onConnectionSuspended(int i) { Log.i("onConnectionSuspended", "GoogleApiClient connection has been suspended"); } /** * Called by Location Services if the attempt to Location Services fails. */ @Override public void onConnectionFailed(ConnectionResult connectionResult) { /* * Google Play services can resolve some errors it detects. If the error * has a resolution, try sending an Intent to start a Google Play * services activity that can resolve error. */ if (connectionResult.hasResolution()) { try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); /* * Thrown if Google Play services cancelled the original * PendingIntent */ } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); } } else { // If no resolution is available, display a dialog to the user with // the error. showErrorDialog(connectionResult.getErrorCode()); } } /** * Report location updates to the UI. */ @Override public void onLocationChanged(Location location) { if (currentLocation != null) { currentLocation.set(location); } else { currentLocation = new Location(location); } if (appHasJustStarted) { if (mustShowPositionWhenComingFromOutside) { if (currentLocation != null) { new SearchPositionByCoordinates().execute(sendDestinationPosition); } mustShowPositionWhenComingFromOutside = false; } else { final LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude()); // 17 is a good zoom level for this action googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17)); } appHasJustStarted = false; } } /** * In response to a request to start updates, send a request to Location * Services. */ private void startPeriodicUpdates() { locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS); // Set the interval ceiling to one minute locationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS); LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } /** * In response to a request to stop updates, send a request to Location * Services. */ private void stopPeriodicUpdates() { // After disconnect() is called, the client is considered "dead". googleApiClient.disconnect(); } /** * Shows a dialog returned by Google Play services for the connection error * code * * @param errorCode An error code returned from onConnectionFailed */ private void showErrorDialog(final int errorCode) { // Get the error dialog from Google Play services final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { // Create a new DialogFragment in which to show the error dialog final ErrorDialogFragment errorFragment = new ErrorDialogFragment(); // Set the dialog in the DialogFragment errorFragment.setDialog(errorDialog); // Show the error dialog in the DialogFragment errorFragment.show(getSupportFragmentManager(), "Geofence detection"); } } private void drawAndShowMultipleDistances(final List<LatLng> coordinates, final String message, final boolean isLoadingFromDB, final boolean mustApplyZoomIfNeeded) { // Borramos los antiguos marcadores y lineas googleMap.clear(); // Calculamos la distancia distanceMeasuredAsText = calculateDistance(coordinates); addMarkers(coordinates, distanceMeasuredAsText, message, isLoadingFromDB); addLines(coordinates, isLoadingFromDB); moveCameraZoom(coordinates.get(0), coordinates.get(coordinates.size() - 1), mustApplyZoomIfNeeded); if (getSharedPreferences(getBaseContext()).getBoolean("elevation_chart", false) && isOnline(getApplicationContext())) { getElevation(coordinates); } } /** * Adds a marker to the map in a specified position and shows its info * window. * * @param coordinates Positions list. * @param distance Distance to destination. * @param message Destination address (if needed). * @param isLoadingFromDB Indicates whether we are loading data from database. */ private void addMarkers(final List<LatLng> coordinates, final String distance, final String message, final boolean isLoadingFromDB) { for (int i = 0; i < coordinates.size(); i++) { if ((i == 0 && (isLoadingFromDB || distanceMode == DistanceMode.DISTANCE_FROM_ANY_POINT)) || (i == coordinates.size() - 1)) { final LatLng coordinate = coordinates.get(i); final Marker marker = addMarker(coordinate); // TODO Release 1.5 // marker.setDraggable(true); if (i == coordinates.size() - 1) { marker.setTitle(message + distance); marker.showInfoWindow(); } } } } private Marker addMarker(final LatLng coordinate) { return googleMap.addMarker(new MarkerOptions().position(coordinate)); } private void addLines(final List<LatLng> coordinates, final boolean isLoadingFromDB) { for (int i = 0; i < coordinates.size() - 1; i++) { addLine(coordinates.get(i), coordinates.get(i + 1), isLoadingFromDB); } } /** * Adds a line between start and end positions. * * @param start Start position. * @param end Destination position. */ private void addLine(final LatLng start, final LatLng end, final boolean isLoadingFromDB) { final PolylineOptions lineOptions = new PolylineOptions().add(start).add(end); lineOptions.width(3 * getResources().getDisplayMetrics().density); lineOptions.color(isLoadingFromDB ? Color.YELLOW : Color.GREEN); googleMap.addPolyline(lineOptions); } /** * Returns the distance between start and end positions normalized by device * locale. * * @param coordinates position list. * @return The normalized distance. */ private String calculateDistance(final List<LatLng> coordinates) { double distanceInMetres = 0.0; for (int i = 0; i < coordinates.size() - 1; i++) { distanceInMetres += Haversine.getDistance(coordinates.get(i).latitude, coordinates.get(i).longitude, coordinates.get(i + 1).latitude, coordinates.get(i + 1).longitude); } return Haversine.normalizeDistance(distanceInMetres, getResources().getConfiguration().locale); } /** * Moves camera position and applies zoom if needed. * * @param p1 Start position. * @param p2 Destination position. */ private void moveCameraZoom(final LatLng p1, final LatLng p2, final boolean mustApplyZoomIfNeeded) { double centerLat = 0.0; double centerLon = 0.0; final String centre = getSharedPreferences(getBaseContext()).getString("animation", "CEN"); if (centre.equals("CEN")) { centerLat = (p1.latitude + p2.latitude) / 2; centerLon = (p1.longitude + p2.longitude) / 2; } else if (centre.equals("DES")) { centerLat = p2.latitude; centerLon = p2.longitude; } else if (centre.equals("NO")) { return; } if (mustApplyZoomIfNeeded) { googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLat, centerLon), calculateZoom(p1, p2))); } else { googleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(p2.latitude, p2.longitude))); } } private SharedPreferences getSharedPreferences(final Context context) { return PreferenceManager.getDefaultSharedPreferences(context); } /** * Calculates zoom level to make possible current and destination positions * appear in the device. * * @param origin Current position. * @param destination Destination position. * @return Zoom level. */ private float calculateZoom(final LatLng origin, final LatLng destination) { double distanceInMetres = Haversine.getDistance(origin.latitude, origin.longitude, destination.latitude, destination.longitude); double kms = distanceInMetres / 1000; if (kms > 2700) { return 3; } else if (kms > 1300) { return 4; } else if (kms > 650) { return 5; } else if (kms > 325) { return 6; } else if (kms > 160) { return 7; } else if (kms > 80) { return 8; } else if (kms > 40) { return 9; } else if (kms > 20) { return 10; } else if (kms > 10) { return 11; } else if (kms > 5) { return 12; } else if (kms > 2.5) { return 13; } else if (kms > 1.25) { return 14; } else if (kms > 0.6) { return 15; } else if (kms > 0.3) { return 16; } else if (kms > 0.15) { return 17; } return 18; } /** * Calculates elevation points in background and shows elevation chart. * * @param coordinates Positions list. */ private void getElevation(final List<LatLng> coordinates) { String positionListUrlParameter = ""; for (int i = 0; i < coordinates.size(); i++) { final LatLng coordinate = coordinates.get(i); positionListUrlParameter += String.valueOf(coordinate.latitude) + "," + String.valueOf(coordinate.longitude); if (i != coordinates.size() - 1) { positionListUrlParameter += "|"; } } if (positionListUrlParameter.isEmpty()) { throw new IllegalStateException("Coordinates list empty"); } if (showingElevationTask != null) { showingElevationTask.cancel(true); } showingElevationTask = new GetAltitude().execute(positionListUrlParameter); } /** * Sets map attending to the action which is performed. */ private void fixMapPadding() { if (bannerShown) { if (elevationChartShown) { googleMap.setPadding(0, rlElevationChart.getHeight(), 0, banner.getLayoutParams().height); } else { googleMap.setPadding(0, 0, 0, banner.getLayoutParams().height); } } else { if (elevationChartShown) { googleMap.setPadding(0, rlElevationChart.getHeight(), 0, 0); } else { googleMap.setPadding(0, 0, 0, 0); } } } private static enum DistanceMode { DISTANCE_FROM_CURRENT_POINT, DISTANCE_FROM_ANY_POINT } /** * A subclass of AsyncTask that calls getFromLocationName() in the background. */ private class SearchPositionByName extends AsyncTask<Object, Void, Integer> { protected List<Address> addressList; protected StringBuilder fullAddress; protected LatLng selectedPosition; protected ProgressDialog progressDialog; @Override protected void onPreExecute() { addressList = null; fullAddress = new StringBuilder(); selectedPosition = null; if (!isOnline(getApplicationContext())) { showWifiAlertDialog(); MenuItemCompat.collapseActionView(searchMenuItem); cancel(false); } else { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle(R.string.progressdialog_search_position_title); progressDialog.setMessage(getString(R.string.progressdialog_search_position_message)); progressDialog.setCancelable(false); progressDialog.setIndeterminate(true); progressDialog.show(); } } @Override protected Integer doInBackground(Object... params) { /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { addressList = geoCoder.getFromLocationName((String) params[0], 5); } catch (IOException e) { e.printStackTrace(); return -1; // Network is unavailable or any other I/O problem occurs } if (addressList == null) { return -3; // No backend service available } else if (addressList.isEmpty()) { return -2; // No matches were found } else { return 0; } } @Override protected void onPostExecute(Integer result) { switch (result) { case 0: if (addressList != null && addressList.size() > 0) { // Si hay varios, elegimos uno. Si solo hay uno, mostramos ese if (addressList.size() == 1) { processSelectedAddress(0); handleSelectedAddress(); } else { final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(getString(R.string.dialog_select_address_title)); builder.setItems(groupAddresses(addressList).toArray(new String[addressList.size()]), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { processSelectedAddress(item); handleSelectedAddress(); } }); builder.create().show(); } } break; case -1: toastIt(getString(R.string.toast_no_find_address), getApplicationContext()); break; case -2: toastIt(getString(R.string.toast_no_results), getApplicationContext()); break; case -3: toastIt(getString(R.string.toast_no_find_address), getApplicationContext()); break; } progressDialog.dismiss(); if (searchMenuItem != null) { MenuItemCompat.collapseActionView(searchMenuItem); } } private void handleSelectedAddress() { if (distanceMode == DistanceMode.DISTANCE_FROM_ANY_POINT) { coordinates.add(selectedPosition); if (coordinates.isEmpty()) { // add marker final Marker marker = addMarker(selectedPosition); marker.setTitle(fullAddress.toString()); marker.showInfoWindow(); // moveCamera moveCameraZoom(selectedPosition, selectedPosition, false); distanceMeasuredAsText = calculateDistance(Lists.newArrayList(selectedPosition, selectedPosition)); // That means we are looking for a first position, so we want to calculate a distance starting // from here calculatingDistance = true; } else { drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } } else { if (!appHasJustStarted) { if (coordinates == null || coordinates.isEmpty()) { coordinates = Lists.newArrayList(); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(selectedPosition); drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } else { // Coming from View Action Intent sendDestinationPosition = selectedPosition; } } } /** * Processes the address selected by the user and sets the new destination * position. * * @param item The item index in the AlertDialog. */ protected void processSelectedAddress(final int item) { // Fill address info to show in the marker info window final Address address = addressList.get(item); for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { fullAddress.append(address.getAddressLine(i)).append("\n"); } selectedPosition = new LatLng(address.getLatitude(), address.getLongitude()); } /** * Extract a list of address from a list of Address objects. * * @param addressList An Address's list. * @return A string list with only addresses in text. */ protected List<String> groupAddresses(final List<Address> addressList) { final List<String> result = Lists.newArrayList(); StringBuilder stringBuilder; for (final Address l : addressList) { stringBuilder = new StringBuilder(); for (int j = 0; j < l.getMaxAddressLineIndex() + 1; j++) { stringBuilder.append(l.getAddressLine(j)).append("\n"); } result.add(stringBuilder.toString()); } return result; } } /** * A subclass of SearchPositionByName to get position by coordinates. */ private class SearchPositionByCoordinates extends SearchPositionByName { @Override protected Integer doInBackground(Object... params) { /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault()); final LatLng latLng = (LatLng) params[0]; try { addressList = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (final IOException e) { e.printStackTrace(); return -1; } catch (final IllegalArgumentException e) { ; throw new IllegalArgumentException(String.format("Error en latitud=%f o longitud=%f.\n%s", latLng.latitude, latLng.longitude, e.toString())); } if (addressList == null) { return -3; // empty list if there is no backend service available } else if (addressList.size() > 0) { return 0; } else { return -2; } } @Override protected void onPostExecute(Integer result) { switch (result) { case 0: processSelectedAddress(0); drawAndShowMultipleDistances(Lists.newArrayList(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), selectedPosition), fullAddress.toString(), false, true); break; case -1: toastIt(getString(R.string.toast_no_find_address), getApplicationContext()); break; case -2: toastIt(getString(R.string.toast_no_results), getApplicationContext()); break; case -3: toastIt(getString(R.string.toast_no_find_address), getApplicationContext()); break; } progressDialog.dismiss(); } } /** * A subclass of AsyncTask that gets elevation points from coordinates in * background and shows an elevation chart. * * @author David */ private class GetAltitude extends AsyncTask<String, Void, Double> { private HttpClient httpClient = null; private HttpGet httpGet = null; private HttpResponse httpResponse; private String responseAsString; private InputStream inputStream = null; private JSONObject responseJSON; @Override protected void onPreExecute() { httpClient = new DefaultHttpClient(); responseAsString = null; // Delete elevation chart if exists if (graphView != null) { rlElevationChart.removeView(graphView); } rlElevationChart.setVisibility(View.INVISIBLE); graphView = null; elevationChartShown = false; fixMapPadding(); } @Override protected Double doInBackground(String... params) { httpGet = new HttpGet("http://maps.googleapis.com/maps/api/elevation/json?sensor=true" + "&path=" + Uri.encode(params[0]) + "&samples=" + ELEVATION_SAMPLES); httpGet.setHeader("content-type", "application/json"); try { httpResponse = httpClient.execute(httpGet); inputStream = httpResponse.getEntity().getContent(); if (inputStream != null) { responseAsString = convertInputStreamToString(inputStream); responseJSON = new JSONObject(responseAsString); if (responseJSON.get("status").equals("OK")) { buildElevationChart(responseJSON.getJSONArray("results")); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Double result) { showElevationProfileChart(); // When HttpClient instance is no longer needed // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.getConnectionManager().shutdown(); } /** * Converts the InputStream with the retrieved data to String. * * @param inputStream The input stream. * @return The InputStream converted to String. * @throws IOException */ private String convertInputStreamToString(final InputStream inputStream) throws IOException { final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { result.append(line); } inputStream.close(); bufferedReader.close(); return result.toString(); } /** * Builds the information about the elevation profile chart. Use this in * a background task. * * @param array JSON array with the response data. * @throws JSONException */ private void buildElevationChart(final JSONArray array) throws JSONException { // Creates the serie and adds data to it final GraphViewSeries series = new GraphViewSeries(null, new GraphViewSeriesStyle(getResources().getColor(R.color.elevation_chart_line), (int) (3 * DEVICE_DENSITY)), new GraphView.GraphViewData[]{}); for (int w = 0; w < array.length(); w++) { series.appendData(new GraphView.GraphViewData(w, Haversine.normalizeAltitudeByLocale(Double.valueOf(array.getJSONObject(w) .get("elevation") .toString()), Locale.getDefault())), false, array.length()); } // Creates the line and add it to the chart graphView = new LineGraphView(getApplicationContext(), getString(R.string.elevation_chart_title, Haversine.getAltitudeUnitByLocale(Locale.getDefault()))); graphView.addSeries(series); graphView.getGraphViewStyle().setGridColor(Color.TRANSPARENT); graphView.getGraphViewStyle().setNumHorizontalLabels(1); // Con cero no va graphView.getGraphViewStyle().setTextSize(15 * DEVICE_DENSITY); graphView.getGraphViewStyle().setVerticalLabelsWidth((int) (50 * DEVICE_DENSITY)); } /** * Shows the elevation profile chart. */ private void showElevationProfileChart() { if (graphView != null) { rlElevationChart.setVisibility(LinearLayout.VISIBLE); rlElevationChart.setBackgroundColor(getResources().getColor(R.color.elevation_chart_background)); rlElevationChart.addView(graphView); elevationChartShown = true; fixMapPadding(); ivCloseElevationChart.setVisibility(View.VISIBLE); ivCloseElevationChart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rlElevationChart.removeView(graphView); rlElevationChart.setVisibility(View.INVISIBLE); elevationChartShown = false; fixMapPadding(); } }); } } } }
package mystikos.pollen; import android.os.StrictMode; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; public class MainActivity extends AppCompatActivity { private TextView JnumberToday; private TextView JnumberTomorrow; private TextView JnumberDayAfter; private JsonElement jelement; private JsonObject jobject; private JsonElement jelement2; private JsonObject locationobject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); JnumberToday = (TextView) findViewById(R.id.numberToday); JnumberTomorrow = (TextView) findViewById(R.id.numberTomorrow); JnumberDayAfter = (TextView) findViewById(R.id.numberDayAfter); getData(); } protected void getData () { try { URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); InputStream in = url.openStream(); jelement = new JsonParser().parse(new InputStreamReader(in)); jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("allergyForecast"); String pollenToday = jobject.get("Day0").toString(); String pollenTomorrow = jobject.get("Day1").toString(); String pollenDayAfter = jobject.get("Day2").toString(); JnumberToday.setText(pollenToday); JnumberTomorrow.setText(pollenTomorrow); JnumberDayAfter.setText(pollenDayAfter); //setLocationText(); } catch (Exception e) {e.printStackTrace();} } //method to get pollen data and set it into its respective textviews protected void getZip () { } //method to get zip code from settings file protected void setTheme () { } protected void setLocationText () { try { URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); InputStream in = url.openStream(); jelement2 = new JsonParser().parse(new InputStreamReader(in)); locationobject = jelement2.getAsJsonObject(); locationobject = locationobject.getAsJsonObject("ForecastInfo"); String city = locationobject.get("City").toString(); String state = locationobject.get("State").toString(); String location = city + "," + state; setTitle(location); } catch (Exception e) {e.printStackTrace();} } //method to set title to location, currently does not work }
package ucar.nc2.iosp.nids; import junit.framework.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.ma2.Array; import ucar.ma2.ArrayStructure; import ucar.ma2.StructureData; import ucar.nc2.*; import ucar.unidata.util.test.TestDir; import java.io.*; import java.lang.invoke.MethodHandles; public class TestNids extends TestCase { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static String basereflectFile = TestDir.localTestDataDir + "nids/N0R_20041119_2147"; private static String basereflect1File = TestDir.localTestDataDir + "nids/N1R_20050119_1548"; private static String basereflect2File = TestDir.localTestDataDir + "nids/N2R_20050119_1528"; private static String basereflect3File = TestDir.localTestDataDir + "nids/N3R_20050119_1548"; private static String basereflectCFile = TestDir.localTestDataDir + "nids/NCR_20050119_1548"; private static String basereflect248File = TestDir.localTestDataDir + "nids/N0Z_20050119_1538"; private static String radialVelocityFile = TestDir.localTestDataDir + "nids/N0V_20041117_1646"; private static String radialVelocity1File = TestDir.localTestDataDir + "nids/N1V_20050119_1548"; private static String echotopFile = TestDir.localTestDataDir + "nids/NET_20041123_1648"; private static String oneHourPrecipFile = TestDir.localTestDataDir + "nids/N1P_20041122_1837"; private static String StormRelMeanVel0File = TestDir.localTestDataDir + "nids/N0S_20050119_1548"; private static String StormRelMeanVel1File = TestDir.localTestDataDir + "nids/N1S_20041117_1640"; private static String StormRelMeanVel2File = TestDir.localTestDataDir + "nids/N2S_20050120_1806"; private static String StormRelMeanVel3File = TestDir.localTestDataDir + "nids/N3S_20050120_1806"; private static String totalPrecipFile = TestDir.localTestDataDir + "nids/NTP_20050119_1528"; private static String digitPrecipArrayFile = TestDir.localTestDataDir + "nids/DPA_20041123_1709"; private static String vertIntegLiquidFile = TestDir.localTestDataDir + "nids/NVL_20041130_1946"; private static String vadWindProfileFile = TestDir.localTestDataDir + "nids/NVW_20041117_1657"; public void testNidsReadRadial() throws IOException { File cwd = new File("."); System.out.printf("**** CWD = %s%n", cwd.getAbsolutePath()); File f = new File(basereflectFile); System.out.printf("**** %s = %s%n", f.getAbsolutePath(), f.exists()); NetcdfFile ncfile = null; try { System.out.println("**** Open " + basereflectFile); ncfile = NetcdfFile.open(basereflectFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } Variable v = null; v = ncfile.findVariable("BaseReflectivity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + basereflect1File); ncfile = NetcdfFile.open(basereflect1File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("BaseReflectivity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + basereflect2File); ncfile = NetcdfFile.open(basereflect2File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("BaseReflectivity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + basereflect3File); ncfile = NetcdfFile.open(basereflect3File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("BaseReflectivity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + basereflect248File); ncfile = NetcdfFile.open(basereflect248File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("BaseReflectivity248"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + StormRelMeanVel0File); ncfile = NetcdfFile.open(StormRelMeanVel0File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("StormMeanVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + StormRelMeanVel1File); ncfile = NetcdfFile.open(StormRelMeanVel1File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("StormMeanVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + StormRelMeanVel2File); ncfile = NetcdfFile.open(StormRelMeanVel2File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("StormMeanVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + StormRelMeanVel3File); ncfile = NetcdfFile.open(StormRelMeanVel3File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("StormMeanVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + radialVelocityFile); ncfile = NetcdfFile.open(radialVelocityFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("RadialVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + radialVelocity1File); ncfile = NetcdfFile.open(radialVelocity1File); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("RadialVelocity"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); } public void testNidsReadRadialN1P() throws IOException { NetcdfFile ncfile = null; try { System.out.println("**** Open " + oneHourPrecipFile); ncfile = NetcdfFile.open(oneHourPrecipFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } Variable v = ncfile.findVariable("Precip1hr_RAW"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + totalPrecipFile); ncfile = NetcdfFile.open(totalPrecipFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("PrecipAccum_RAW"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); } public void testNidsReadRaster() throws IOException { NetcdfFile ncfile = null; try { System.out.println("**** Open " + echotopFile); ncfile = NetcdfFile.open(echotopFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } Variable v = ncfile.findVariable("EchoTop"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + vertIntegLiquidFile); ncfile = NetcdfFile.open(vertIntegLiquidFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("VertLiquid"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); v = ncfile.findVariable("VertLiquid_RAW"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); try { System.out.println("**** Open " + basereflectCFile); ncfile = NetcdfFile.open(basereflectCFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("BaseReflectivityComp"); testReadData(v); assert (null != v.getDimension(0)); assert (null != v.getDimension(1)); ncfile.close(); } public void testNidsReadNVW() throws IOException { NetcdfFile ncfile = null; Variable v = null; Array a = null; try { System.out.println("**** Open " + vadWindProfileFile); ncfile = NetcdfFile.open(vadWindProfileFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } assert (null != ncfile.findVariable("textStruct_code8")); assert (null != ncfile.findVariable("textStruct_code8").getDimension(0)); v = ncfile.findVariable("unlinkedVectorStruct"); testReadDataAsShort((Structure) v, "iValue"); v = ncfile.findVariable("VADWindSpeed"); testReadData(v); v = ncfile.findVariable("TabMessagePage"); testReadData(v); ncfile.close(); } public void testNidsReadDPA() throws IOException { NetcdfFile ncfile = null; Variable v = null; Array a = null; try { System.out.println("**** Open " + digitPrecipArrayFile); ncfile = NetcdfFile.open(digitPrecipArrayFile); } catch (java.io.IOException e) { System.out.println(" fail = " + e); e.printStackTrace(); assert (false); } v = ncfile.findVariable("PrecipArray_0"); testReadData(v); /* * v = ncfile.findVariable("PrecipArray_1"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_2"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_3"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_4"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_5"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_6"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_7"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_8"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_9"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_10"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_11"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_12"); * testReadData(v); * * v = ncfile.findVariable("PrecipArray_13"); * testReadData(v); */ assert (null != ncfile.findVariable("textStruct_code1").getDimension(0)); ncfile.close(); } private void testReadData(Variable v) { Array a = null; assert (null != v); assert (null != v.getDimension(0)); try { a = v.read(); assert (null != a); } catch (java.io.IOException e) { e.printStackTrace(); assert (false); } assert (v.getSize() == a.getSize()); } private void testReadDataAsShort(Structure v, String memberName) { Array a = null; assert (null != v); assert (null != v.getDimension(0)); try { a = v.read(); assert (null != a); } catch (java.io.IOException e) { e.printStackTrace(); assert (false); } assert (v.getSize() == a.getSize()); assert (a instanceof ArrayStructure); int sum = 0; ArrayStructure as = (ArrayStructure) a; int n = (int) as.getSize(); for (int i = 0; i < n; i++) { StructureData sdata = as.getStructureData(i); sum += sdata.getScalarShort(memberName); } System.out.println("test short sum = " + sum); } }
package ucar.nc2.dataset; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.auth.CredentialsProvider; import opendap.dap.DConnect2; import ucar.unidata.io.http.HTTPRandomAccessFile; import thredds.util.net.EasySSLProtocolSocketFactory; import java.io.IOException; /** * Manage Http Client protocol settings. * <pre> * Example: * org.apache.commons.httpclient.auth.CredentialsProvider provider = new thredds.ui.UrlAuthenticatorDialog(frame); * ucar.nc2.dataset.HttpClientManager.init(provider, "ToolsUI"); * </pre> * * @author caron * @version $Revision$ $Date$ */ public class HttpClientManager { static private boolean debug = false; static private boolean protocolRegistered = false; static private HttpClient _client; static private int timeout = 0; /** * initialize the HttpClient layer. * * @param provider CredentialsProvider. * @param userAgent Content of User-Agent header, may be null */ static public void init(CredentialsProvider provider, String userAgent) { if (!protocolRegistered) { // this allows self-signed certificates. Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 8443)); protocolRegistered = true; } initHttpClient(); if (provider != null) _client.getParams().setParameter(CredentialsProvider.PROVIDER, provider); if (userAgent != null) _client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent + "/NetcdfJava/HttpClient"); else _client.getParams().setParameter(HttpMethodParams.USER_AGENT, "NetcdfJava/HttpClient"); setHttpClient(_client); } /** * Set the HttpClient object - a single instance is used. * Propaget to entire NetcdfJava library. */ static public void setHttpClient(HttpClient client) { _client = client; DConnect2.setHttpClient(_client); HTTPRandomAccessFile.setHttpClient(_client); } /** * Get the HttpClient object - a single instance is used. */ static public HttpClient getHttpClient() { return _client; } private static synchronized void initHttpClient() { if (_client != null) return; MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); _client = new HttpClient(connectionManager); HttpClientParams params = _client.getParams(); params.setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout)); params.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); params.setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.RFC_2109); // look need default CredentialsProvider ?? // _client.getParams().setParameter(CredentialsProvider.PROVIDER, provider); } public static void clearState() { _client.getState().clearCookies(); _client.getState().clearCredentials(); } /** * COnvenience better to use getResponseAsStream */ public static String getContent(String urlString) throws IOException { GetMethod m = new GetMethod(urlString); m.setFollowRedirects(true); try { _client.executeMethod(m); return m.getResponseBodyAsString(); } finally { m.releaseConnection(); } } public static int putContent(String urlString, String content) throws IOException { PutMethod m = new PutMethod(urlString); m.setDoAuthentication( true ); try { m.setRequestEntity(new StringRequestEntity(content)); _client.executeMethod(m); int resultCode = m.getStatusCode(); // followRedirect wont work for PUT if (resultCode == 302) { String redirectLocation; Header locationHeader = m.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); if (debug) System.out.println("***Follow Redirection = "+redirectLocation); resultCode = putContent(redirectLocation, content); } } return resultCode; } finally { m.releaseConnection(); } } }
package net.alphadev.usbstorage; import android.content.Context; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbManager; import java.io.IOException; import java.nio.ByteBuffer; import java.security.InvalidParameterException; import de.waldheinz.fs.BlockDevice; import de.waldheinz.fs.ReadOnlyException; public class UsbBlockDevice implements BlockDevice { public final static int DEFAULT_SECTOR_SIZE = 512; private UsbEndpoint mReadEndpoint; private UsbEndpoint mWriteEndpoint; private UsbInterface mDataInterface; private UsbDeviceConnection mConnection; private final Object mReadBufferLock = new Object(); private final Object mWriteBufferLock = new Object(); private boolean readOnly; private boolean closed; public UsbBlockDevice(Context ctx, UsbDevice device, final boolean readOnly) { final UsbManager manager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE); } private void open(UsbDevice device, UsbManager manager) { for(int i = 0; i <= device.getInterfaceCount(); i++) { UsbInterface interfaceProbe = device.getInterface(i); if(interfaceProbe.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE) { mDataInterface = device.getInterface(i); } } this.readOnly = false; for(int i = 0; i <= mDataInterface.getEndpointCount(); i++) { UsbEndpoint endpointProbe = mDataInterface.getEndpoint(i); if(endpointProbe.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if(endpointProbe.getDirection() == UsbConstants.USB_DIR_IN) { mReadEndpoint = endpointProbe; } else { if(!readOnly) { mWriteEndpoint = endpointProbe; this.readOnly = false; } } } } mConnection = manager.openDevice(device); closed = false; } @Override public long getSize() throws IOException { checkClosed(); // create a usb request and ask for the drives size. return 0; } @Override public void read(long offset, ByteBuffer byteBuffer) throws IOException { checkClosed(); final int numBytesRead; synchronized (mReadBufferLock) { if(!byteBuffer.hasArray()) { throw new InvalidParameterException("Your Buffer isn't Array-backed!"); } int readAmt = (int)Math.min(getSize(), (long)byteBuffer.remaining()); int timeoutMillis = 250; numBytesRead = mConnection.bulkTransfer(mReadEndpoint, byteBuffer.array(), readAmt, timeoutMillis); if (numBytesRead < 0) { // This sucks: we get -1 on timeout, not 0 as preferred. // We *should* use UsbRequest, except it has a bug/api oversight // where there is no way to determine the number of bytes read if (timeoutMillis == Integer.MAX_VALUE) { // Hack: Special case "~infinite timeout" as an error. throw new IllegalStateException("Unknown usb timing error occured!"); } throw new IllegalStateException("Unknown error occured!"); } //System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead); } } @Override public void write(long offset, ByteBuffer byteBuffer) throws ReadOnlyException, IOException, IllegalArgumentException { } @Override public void flush() throws IOException { // since we write everything directly to the device there's no need to flush. } @Override public int getSectorSize() throws IOException { return DEFAULT_SECTOR_SIZE; } @Override public void close() throws IOException { if (mConnection == null) { throw new IOException("Already closed"); } mConnection.close(); mConnection = null; closed = true; } @Override public boolean isClosed() { return closed; } @Override public boolean isReadOnly() { return readOnly; } private void checkClosed() { if (closed) throw new IllegalStateException("device already closed"); } }
package universalcoins.net; import cpw.mods.fml.common.FMLLog; import universalcoins.UCTileEntity; import universalcoins.UCTradeStationGUI; import universalcoins.UniversalCoins; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class PacketTradingStation extends AbstractPacket { private int x, y, z, button; private boolean bypass; public PacketTradingStation() { } public PacketTradingStation(int x, int y, int z, int button, boolean bypass) { this.x = x; this.y = y; this.z = z; this.button = button; this.bypass = bypass; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) { buffer.writeInt(x); buffer.writeInt(y); buffer.writeInt(z); buffer.writeInt(button); buffer.writeBoolean(bypass); } @Override public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) { x = buffer.readInt(); y = buffer.readInt(); z = buffer.readInt(); button = buffer.readInt(); bypass = buffer.readBoolean(); } @Override public void handleClientSide(EntityPlayer player) { } @Override public void handleServerSide(EntityPlayer player) { World world = player.worldObj; TileEntity ucTileEntity = world.getTileEntity(x, y, z); if (ucTileEntity instanceof UCTileEntity) { if (button == UCTradeStationGUI.idBypassButton){ ((UCTileEntity) ucTileEntity).setBypass(bypass); } if (button == UCTradeStationGUI.idBuyButton) { ((UCTileEntity) ucTileEntity).onBuyPressed(); } else if (button == UCTradeStationGUI.idSellButton) { ((UCTileEntity) ucTileEntity).onSellPressed(); } else if (button == UCTradeStationGUI.idSellMaxButton){ ((UCTileEntity) ucTileEntity).onSellMaxPressed(); } else if (button == UCTradeStationGUI.idBuyMaxButton){ ((UCTileEntity) ucTileEntity).onBuyMaxPressed(); } else if (button <= UCTradeStationGUI.idHeapButton){ ((UCTileEntity) ucTileEntity).onRetrieveButtonsPressed(button); } NBTTagCompound data = new NBTTagCompound(); ucTileEntity.writeToNBT(data); } world.markBlockForUpdate(x, y, z); } }
package org.commcare.views.widgets; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import org.commcare.CommCareApplication; import org.commcare.activities.components.FormEntryInstanceState; import org.commcare.dalvik.R; import org.commcare.logic.PendingCalloutInterface; import org.commcare.util.LogTypes; import org.commcare.utils.FileExtensionNotFoundException; import org.commcare.utils.FileUtil; import org.commcare.utils.FormUploadUtil; import org.commcare.utils.StringUtils; import org.commcare.utils.UriToFilePath; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.data.InvalidData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryPrompt; import java.io.File; import java.io.IOException; import java.io.InputStream; import androidx.annotation.NonNull; /** * Generic logic for capturing or choosing audio/video/image media * * @author Phillip Mates (pmates@dimagi.com) */ public abstract class MediaWidget extends QuestionWidget { private static final String TAG = MediaWidget.class.getSimpleName(); protected static final String CUSTOM_TAG = "custom"; protected Button mCaptureButton; protected Button mPlayButton; protected Button mChooseButton; protected String mBinaryName; protected final PendingCalloutInterface pendingCalloutInterface; protected final String mInstanceFolder; private int oversizedMediaSize; protected String recordedFileName; protected String customFileTag; private String destMediaPath; public MediaWidget(Context context, FormEntryPrompt prompt, PendingCalloutInterface pendingCalloutInterface) { super(context, prompt); this.pendingCalloutInterface = pendingCalloutInterface; mInstanceFolder = FormEntryInstanceState.mFormRecordPath.substring(0, FormEntryInstanceState.mFormRecordPath.lastIndexOf("/") + 1); setOrientation(LinearLayout.VERTICAL); initializeButtons(); setupLayout(); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (visibility == View.VISIBLE) { loadAnswerFromDataModel(); } } private void loadAnswerFromDataModel() { mBinaryName = mPrompt.getAnswerText(); if (mBinaryName != null) { reloadFile(); } else { checkForOversizedMedia(mPrompt.getAnswerValue()); togglePlayButton(false); } } protected void reloadFile() { togglePlayButton(true); File f = new File(mInstanceFolder + mBinaryName); checkFileSize(f); } protected void togglePlayButton(boolean enabled) { mPlayButton.setEnabled(enabled); } protected abstract void initializeButtons(); protected void setupLayout() { addView(mCaptureButton); addView(mChooseButton); addView(mPlayButton); } @Override public IAnswerData getAnswer() { if (oversizedMediaSize > 0) { // media was too big to upload, set answer as invalid data to // allow showing the user a proper warning message. return new InvalidData("", new IntegerData(oversizedMediaSize)); } else if (mBinaryName != null) { return new StringData(mBinaryName); } return null; } /** * @return whether the media file passes the size check */ private boolean ifMediaSizeChecks(String binaryPath) { File source = new File(binaryPath); boolean isTooLargeToUpload = checkFileSize(source); if (isTooLargeToUpload) { oversizedMediaSize = (int)source.length() / (1024 * 1024); return false; } else { oversizedMediaSize = -1; return true; } } /** * @return whether the media file has a valid extension */ private boolean ifMediaExtensionChecks(String binaryPath) { String extension = FileUtil.getExtension(recordedFileName); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { Toast.makeText(getContext(), Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); Log.e(TAG, String.format( "Could not save file with URI %s because of bad extension %s.", binaryPath, extension )); return false; } return true; } @Override public void clearAnswer() { deleteMedia(); togglePlayButton(false); } private void deleteMedia() { File f = new File(mInstanceFolder + mBinaryName); if (!f.delete()) { Log.e(TAG, "Failed to delete " + f); } mBinaryName = null; } @Override public void setOnLongClickListener(OnLongClickListener l) { mCaptureButton.setOnLongClickListener(l); mChooseButton.setOnLongClickListener(l); mPlayButton.setOnLongClickListener(l); } @Override public void unsetListeners() { super.unsetListeners(); mCaptureButton.setOnLongClickListener(null); mChooseButton.setOnLongClickListener(null); mPlayButton.setOnLongClickListener(null); } @Override public void cancelLongPress() { super.cancelLongPress(); mCaptureButton.cancelLongPress(); mChooseButton.cancelLongPress(); mPlayButton.cancelLongPress(); } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public void setBinaryData(Object binaryURI) { // delete any existing media if (mBinaryName != null) { deleteMedia(); } String binaryPath; try { binaryPath = createFilePath(binaryURI); } catch (FileExtensionNotFoundException e) { showToast("form.attachment.invalid.extension"); Logger.exception("Error while saving media ", e); return; } catch (IOException e) { e.printStackTrace(); showToast("form.attachment.copy.fail"); Logger.exception("Error while saving media ", e); return; } if (!ifMediaSizeChecks(binaryPath) && !ifMediaExtensionChecks(binaryPath)) { return; } File newMedia; recordedFileName = FileUtil.getFileName(binaryPath); copyRecordedFileToDestination(binaryPath); newMedia = new File(destMediaPath); if (newMedia.exists()) { showToast("form.attachment.success"); } mBinaryName = newMedia.getName(); } private void copyRecordedFileToDestination(String binaryPath) { String extension = FileUtil.getExtension(recordedFileName); destMediaPath = mInstanceFolder + System.currentTimeMillis() + customFileTag + "." + extension; // Copy to destMediaPath File source = new File(binaryPath); try { FileUtil.copyFile(source, new File(destMediaPath)); } catch (IOException e) { showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); e.printStackTrace(); } } /** * If file is chosen by user, the file selection intent will return an URI * If file is auto-selected after recording_fragment, then the recordingfragment will provide a string file path * Set value of customFileTag if the file is a recent recording from the RecordingFragment */ private String createFilePath(Object binaryuri) throws IOException { String path; if (binaryuri instanceof Uri) { // Make a copy to a temporary location InputStream inputStream = getContext().getContentResolver().openInputStream((Uri)binaryuri); String fileName = FileUtil.getFileName(getContext(), (Uri)binaryuri); path = CommCareApplication.instance().getAndroidFsTemp() + System.currentTimeMillis() + "." + FileUtil.getExtension(fileName); FileUtil.copyFile(inputStream, new File(path)); customFileTag = ""; } else { path = (String)binaryuri; customFileTag = CUSTOM_TAG; } return path; } protected void playMedia(String mediaType) { Intent i = new Intent("android.intent.action.VIEW"); File mediaFile = new File(mInstanceFolder + mBinaryName); Uri mediaUri = FileUtil.getUriForExternalFile(getContext(), mediaFile); i.setDataAndType(mediaUri, mediaType); UriToFilePath.grantPermissionForUri(getContext(), i, mediaUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); try { getContext().startActivity(i); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), StringUtils.getStringSpannableRobust(getContext(), R.string.activity_not_found, "play " + mediaType.substring(0, mediaType.indexOf("/"))), Toast.LENGTH_SHORT).show(); } } }
package de.jonasrottmann.realmbrowser.utils; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.text.SpannableString; import android.text.style.StyleSpan; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.Date; import io.realm.DynamicRealmObject; import io.realm.RealmList; public class MagicUtils { public static boolean isParametrizedField(@NonNull Field field) { return field.getGenericType() instanceof ParameterizedType; } @NonNull public static String createParametrizedName(@NonNull Field field) { ParameterizedType pType = (ParameterizedType) field.getGenericType(); String rawType = pType.getRawType().toString(); int rawTypeIndex = rawType.lastIndexOf("."); if (rawTypeIndex > 0) { rawType = rawType.substring(rawTypeIndex + 1); } String argument = pType.getActualTypeArguments()[0].toString(); int argumentIndex = argument.lastIndexOf("."); if (argumentIndex > 0) { argument = argument.substring(argumentIndex + 1); } return rawType + "<" + argument + ">"; } @NonNull public static CharSequence getFieldValueString(DynamicRealmObject realmObject, Field field) { String value; if (field.getType().getName().equals(Byte.class.getName()) || field.getType().getName().equals("byte")) { // Byte value = String.valueOf(realmObject.getByte(field.getName())); } else if (field.getType().getName().equals(Boolean.class.getName()) || field.getType().getName().equals("boolean")) { // Boolean value = String.valueOf(realmObject.getBoolean(field.getName())); } else if (field.getType().getName().equals(Short.class.getName()) || field.getType().getName().equals("short")) { // Short value = String.valueOf(realmObject.getShort(field.getName())); } else if (field.getType().getName().equals(Integer.class.getName()) || field.getType().getName().equals("int")) { // Integer value = String.valueOf(realmObject.getInt(field.getName())); } else if (field.getType().getName().equals(Long.class.getName()) || field.getType().getName().equals("long")) { // Long value = String.valueOf(realmObject.getLong(field.getName())); } else if (field.getType().getName().equals(Float.class.getName()) || field.getType().getName().equals("float")) { // Float value = String.valueOf(realmObject.getFloat(field.getName())); } else if (field.getType().getName().equals(Double.class.getName()) || field.getType().getName().equals("double")) { // Double value = String.valueOf(realmObject.getDouble(field.getName())); } else if (field.getType().getName().equals(String.class.getName())) { // String value = realmObject.getString(field.getName()); } else if (field.getType().getName().equals(Date.class.getName())) { // Date Date date = realmObject.getDate(field.getName()); if (date != null) value = date.toString(); else value = null; } else { if (field.getType().getName().equals(RealmList.class.getName())) { // RealmList value = (MagicUtils.createParametrizedName(field)); } else { // ? extends RealmObject value = (realmObject.getObject(field.getName()).toString()); } } if (value == null) { // Display null in italics to be able to distinguish between null and a string that actually says "null" value = "null"; SpannableString nullString = new SpannableString(value); nullString.setSpan(new StyleSpan(Typeface.ITALIC), 0, value.length(), 0); return nullString; } else { return value; } } }
package no.deichman.services.search; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import no.deichman.services.entity.EntityService; import no.deichman.services.entity.EntityType; import no.deichman.services.uridefaults.XURI; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.ResIterator; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ServerErrorException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import static com.google.common.collect.ImmutableMap.of; import static com.google.common.collect.Lists.newArrayList; import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.URLEncoder.encode; import static java.util.stream.Collectors.toList; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static no.deichman.services.uridefaults.BaseURI.ontology; import static org.apache.http.impl.client.HttpClients.createDefault; import static org.apache.jena.rdf.model.ResourceFactory.createProperty; /** * Responsibility: perform indexing and searching. */ public class SearchServiceImpl implements SearchService { public static final Property AGENT = createProperty(ontology("agent")); private static final Logger LOG = LoggerFactory.getLogger(SearchServiceImpl.class); private static final String UTF_8 = "UTF-8"; public static final int SIXTY_ONE = 61; public static final String[] LOCAL_INDEX_SEARCH_FIELDS = {ontology("name"), ontology("prefLabel")}; private final EntityService entityService; private final String elasticSearchBaseUrl; private ModelToIndexMapper workModelToIndexMapper = new ModelToIndexMapper("work"); private ModelToIndexMapper eventModelToIndexMapper = new ModelToIndexMapper("event"); private ModelToIndexMapper serialModelToIndexMapper = new ModelToIndexMapper("serial"); private ModelToIndexMapper personModelToIndexMapper = new ModelToIndexMapper("person"); private ModelToIndexMapper corporationModelToIndexMapper = new ModelToIndexMapper("corporation"); private ModelToIndexMapper publicationModelToIndexMapper = new ModelToIndexMapper("publication"); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); public SearchServiceImpl(String elasticSearchBaseUrl, EntityService entityService) { this.elasticSearchBaseUrl = elasticSearchBaseUrl; this.entityService = entityService; getIndexUriBuilder(); } @Override public final void index(XURI xuri) throws Exception { switch (xuri.getTypeAsEntityType()) { case WORK: doIndexWork(xuri, false, false); break; case PERSON: case CORPORATION: doIndexWorkCreator(xuri, false); break; case PUBLICATION: doIndexPublication(xuri); break; case EVENT: doIndexEvent(xuri); break; case SERIAL: doIndexSerial(xuri); break; default: doIndex(xuri); } } public final void indexOnly(XURI xuri) throws Exception { switch (xuri.getTypeAsEntityType()) { case WORK: doIndexWork(xuri, true, true); break; case PERSON: case CORPORATION: doIndexWorkCreator(xuri, true); break; case PUBLICATION: doIndexPublication(xuri); break; case EVENT: doIndexEvent(xuri); break; case SERIAL: doIndexSerial(xuri); break; default: doIndex(xuri); } } private void doIndexEvent(XURI xuri) { Model eventModelWithLinkedResources = entityService.retrieveEventWithLinkedResources(xuri); indexDocument(xuri, eventModelToIndexMapper.createIndexDocument(eventModelWithLinkedResources, xuri)); } private void doIndexSerial(XURI xuri) { Model serialModelWithLinkedResources = entityService.retrieveSerialWithLinkedResources(xuri); indexDocument(xuri, serialModelToIndexMapper.createIndexDocument(serialModelWithLinkedResources, xuri)); } @Override public final Response searchPersonWithJson(String json) { return searchWithJson(json, getPersonSearchUriBuilder()); } @Override public final Response searchWorkWithJson(String json, MultivaluedMap<String, String> queryParams) { return searchWithJson(json, getWorkSearchUriBuilder(queryParams)); } @Override public final Response searchPublicationWithJson(String json) { return searchWithJson(json, getPublicationSearchUriBuilder()); } @Override public final Response searchInstrument(String query) { return doSearch(query, getInstrumentSearchUriBuilder()); } @Override public final Response searchCompositionType(String query) { return doSearch(query, getCompositionTypeSearchUriBuilder()); } @Override public final Response searchEvent(String query) { return doSearch(query, getEventSearchUriBuilder()); } @Override public final Response clearIndex() { try (CloseableHttpClient httpclient = createDefault()) { URI uri = getIndexUriBuilder().setPath("/search").build(); try (CloseableHttpResponse getExistingIndex = httpclient.execute(new HttpGet(uri))) { if (getExistingIndex.getStatusLine().getStatusCode() == HTTP_OK) { try (CloseableHttpResponse delete = httpclient.execute(new HttpDelete(uri))) { int statusCode = delete.getStatusLine().getStatusCode(); LOG.info("Delete index request returned status " + statusCode); if (statusCode != HTTP_OK) { throw new ServerErrorException("Failed to delete elasticsearch index", HTTP_INTERNAL_ERROR); } } } } HttpPut createIndexRequest = new HttpPut(uri); createIndexRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/search_index.json"), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse create = httpclient.execute(createIndexRequest)) { int statusCode = create.getStatusLine().getStatusCode(); LOG.info("Create index request returned status " + statusCode); if (statusCode != HTTP_OK) { throw new ServerErrorException("Failed to create elasticsearch index", HTTP_INTERNAL_ERROR); } } putIndexMapping(httpclient, "work"); putIndexMapping(httpclient, "person"); putIndexMapping(httpclient, "serial"); putIndexMapping(httpclient, "corporation"); putIndexMapping(httpclient, "place"); putIndexMapping(httpclient, "subject"); putIndexMapping(httpclient, "genre"); putIndexMapping(httpclient, "publication"); putIndexMapping(httpclient, "instrument"); putIndexMapping(httpclient, "compositionType"); putIndexMapping(httpclient, "event"); putIndexMapping(httpclient, "workSeries"); return Response.status(Response.Status.OK).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR); } } private void putIndexMapping(CloseableHttpClient httpclient, String type) throws URISyntaxException, IOException { URI workIndexUri = getIndexUriBuilder().setPath("/search/_mapping/" + type).build(); HttpPut putWorkMappingRequest = new HttpPut(workIndexUri); putWorkMappingRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/" + type + "_mapping.json"), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse create = httpclient.execute(putWorkMappingRequest)) { int statusCode = create.getStatusLine().getStatusCode(); LOG.info("Create mapping request for " + type + " returned status " + statusCode); if (statusCode != HTTP_OK) { throw new ServerErrorException("Failed to create elasticsearch mapping for " + type, HTTP_INTERNAL_ERROR); } } } private Response searchWithJson(String body, URIBuilder searchUriBuilder) { try { HttpPost httpPost = new HttpPost(searchUriBuilder.build()); httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8)); httpPost.setHeader("Content-type", "application/json"); return executeHttpRequest(httpPost); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR); } } private Response executeHttpRequest(HttpRequestBase httpRequestBase) throws IOException { try (CloseableHttpClient httpclient = createDefault(); CloseableHttpResponse response = httpclient.execute(httpRequestBase)) { HttpEntity responseEntity = response.getEntity(); String jsonContent = IOUtils.toString(responseEntity.getContent()); Response.ResponseBuilder responseBuilder = Response.ok(jsonContent); Header[] headers = response.getAllHeaders(); for (Header header : headers) { responseBuilder = responseBuilder.header(header.getName(), header.getValue()); } return responseBuilder.build(); } catch (Exception e) { throw e; } } @Override public final Response searchWork(String query) { return doSearch(query, getWorkSearchUriBuilder(null)); } @Override public final Response searchPerson(String query) { return doSearch(query, getPersonSearchUriBuilder()); } @Override public final Response searchPlace(String query) { return doSearch(query, getPlaceUriBuilder()); } @Override public final Response searchCorporation(String query) { return doSearch(query, getCorporationSearchUriBuilder()); } @Override public final Response searchSerial(String query) { return doSearch(query, getSerialSearchUriBuilder()); } @Override public final Response searchSubject(String query) { return doSearch(query, getSubjectSearchUriBuilder()); } @Override public final Response searchGenre(String query) { return doSearch(query, getGenreSearchUriBuilder()); } @Override public final Response searchPublication(String query) { return doSearch(query, getPublicationSearchUriBuilder()); } @Override public final void delete(XURI xuri) { try (CloseableHttpClient httpclient = createDefault()) { HttpDelete httpDelete = new HttpDelete(getIndexUriBuilder() .setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8))) .build()); try (CloseableHttpResponse putResponse = httpclient.execute(httpDelete)) { LOG.debug(putResponse.getStatusLine().toString()); } } catch (Exception e) { LOG.error(format("Failed to delete %s in elasticsearch", xuri.getUri()), e); throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR); } } @Override public final Response sortedList(String type, String prefix, int minSize, String field) { EntityType entityType = EntityType.get(type); URIBuilder searchUriBuilder = getIndexUriBuilder().setPath("/search/" + type + "/_search").setParameter("size", Integer.toString(minSize)); switch (entityType) { case PERSON: case CORPORATION: case PLACE: case SUBJECT: case EVENT: case WORK_SERIES: case SERIAL: case GENRE: case MUSICAL_INSTRUMENT: case MUSICAL_COMPOSITION_TYPE: return searchWithJson(createPreIndexedSearchQuery(prefix, minSize, entityType), searchUriBuilder); default: return searchWithJson(createSortedListQuery(prefix, minSize, field), searchUriBuilder); } } private String createSortedListQuery(String prefix, int minSize, String field) { String sortedListQuery; List<Map> should = new ArrayList<>(); for (int i = 0; i < prefix.length(); i++) { should.add( of("constant_score", of("boost", 2 << Math.max(prefix.length() - i, SIXTY_ONE), "query", of("match_phrase_prefix", of(field, prefix.substring(0, prefix.length() - i)))))); } sortedListQuery = GSON.toJson(of( "size", minSize, "query", of( "bool", of( "should", should) ) )); return sortedListQuery; } private String createPreIndexedSearchQuery(String prefix, int minSize, EntityType entityType) { Collection<NameEntry> nameEntries = entityService.neighbourhoodOfName(entityType, prefix, minSize); List<Map> should = new ArrayList<>(); should.addAll(nameEntries .stream() .filter(NameEntry::isBestMatch) .map(e -> of( "ids", of("values", newArrayList(urlEncode(e.getUri()))))) .collect(toList())); should.add(of( "ids", of("values", nameEntries .stream() .map(NameEntry::getUri) .map(SearchServiceImpl::urlEncode) .collect(toList()) ) )); return GSON.toJson( of( "size", minSize, "query", of( "bool", of("should", should) ) ) ); } private static String urlEncode(String uri) { return uri.replace(":", "%3A").replace("/", "%2F"); } @Override public final Response searchWorkWhereUriIsSubject(String subjectUri, int maxSize) { String body = GSON.toJson(of( "size", maxSize, "query", of( "nested", of( "path", "subjects", "query", of("term", of( "subjects.uri", subjectUri) ) ) ) )); return searchWithJson(body, getIndexUriBuilder().setPath("/search/work/_search")); } @Override public final Response searchWorkSeries(String query) { return doSearch(query, getWorkSeriesSearchUriBuilder()); } private URIBuilder getWorkSeriesSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/workSeries/_search"); } private void doIndexPublication(XURI pubUri) throws Exception { Model pubModel = entityService.retrieveById(pubUri); Property publicationOfProperty = ResourceFactory.createProperty(ontology("publicationOf")); if (pubModel.getProperty(null, publicationOfProperty) != null) { String workUri = pubModel.getProperty(ResourceFactory.createResource(pubUri.toString()), publicationOfProperty).getObject().toString(); XURI workXURI = new XURI(workUri); pubModel = entityService.retrieveWorkWithLinkedResources(workXURI); } indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(pubModel, pubUri)); } private void doIndexWork(XURI xuri, boolean indexedPerson, boolean indexedPublication) throws Exception { Model workModelWithLinkedResources = entityService.retrieveWorkWithLinkedResources(xuri); indexDocument(xuri, workModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, xuri)); if (!indexedPerson) { for (Statement stmt : workModelWithLinkedResources.listStatements().toList()) { if (stmt.getPredicate().equals(AGENT)) { XURI creatorXuri = new XURI(stmt.getObject().asNode().getURI()); doIndexWorkCreatorOnly(creatorXuri); } } } if (indexedPublication) { return; } // Index all publications belonging to work // TODO instead of iterating over all subjects, find only subjects of triples with publicationOf as predicate ResIterator subjectIterator = workModelWithLinkedResources.listSubjects(); while (subjectIterator.hasNext()) { Resource subj = subjectIterator.next(); if (subj.isAnon()) { continue; } if (subj.toString().contains("publication")) { XURI pubUri = new XURI(subj.toString()); indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, pubUri)); } } } private void doIndexWorkCreator(XURI creatorUri, boolean indexedWork) throws Exception { Model works = entityService.retrieveWorksByCreator(creatorUri); if (!indexedWork) { ResIterator subjectIterator = works.listSubjects(); while (subjectIterator.hasNext()) { Resource subj = subjectIterator.next(); if (subj.isAnon() || subj.toString().indexOf(' continue; } XURI workUri = new XURI(subj.toString()); if (!workUri.getUri().equals(creatorUri.getUri())) { doIndexWorkOnly(workUri); } } } switch (creatorUri.getTypeAsEntityType()) { case PERSON: indexDocument(creatorUri, personModelToIndexMapper .createIndexDocument(entityService.retrievePersonWithLinkedResources(creatorUri).add(works), creatorUri)); cacheNameIndex(creatorUri, works); break; case CORPORATION: indexDocument(creatorUri, corporationModelToIndexMapper .createIndexDocument(entityService.retrieveCorporationWithLinkedResources(creatorUri).add(works), creatorUri)); cacheNameIndex(creatorUri, works); break; default: throw new RuntimeException(format( "Tried to index work creator of type %1$s. Should be %2$s or %3$s", creatorUri.getTypeAsEntityType(), EntityType.PERSON, EntityType.CORPORATION )); } } private void doIndex(XURI xuri) throws Exception { Model indexModel = entityService.retrieveById(xuri); indexDocument(xuri, new ModelToIndexMapper(xuri.getTypeAsEntityType().getPath()).createIndexDocument(indexModel, xuri)); cacheNameIndex(xuri, indexModel); } private void cacheNameIndex(XURI xuri, Model indexModel) { entityService.statementsInModelAbout(xuri, indexModel, LOCAL_INDEX_SEARCH_FIELDS) .forEachRemaining(statement -> { entityService.addIndexedName( xuri.getTypeAsEntityType(), statement.getObject().asLiteral().toString(), statement.getSubject().getURI()); }); } private void doIndexWorkOnly(XURI xuri) throws Exception { doIndexWork(xuri, true, false); } private void indexDocument(XURI xuri, String document) { try (CloseableHttpClient httpclient = createDefault()) { HttpPut httpPut = new HttpPut(getIndexUriBuilder() .setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8))) // TODO drop urlencoded ID, and define _id in mapping from field uri .build()); httpPut.setEntity(new StringEntity(document, Charset.forName(UTF_8))); httpPut.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.withCharset(UTF_8).toString()); try (CloseableHttpResponse putResponse = httpclient.execute(httpPut)) { LOG.debug(putResponse.getStatusLine().toString()); } } catch (Exception e) { LOG.error(format("Failed to index %s in elasticsearch", xuri.getUri()), e); throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR); } } private Response doSearch(String query, URIBuilder searchUriBuilder) { try { HttpGet httpGet = new HttpGet(searchUriBuilder .setParameter("q", query) .setParameter("size", "100") .build()); return executeHttpRequest(httpGet); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR); } } private void doIndexWorkCreatorOnly(XURI xuri) throws Exception { doIndexWorkCreator(xuri, true); } private URIBuilder getIndexUriBuilder() { try { return new URIBuilder(this.elasticSearchBaseUrl); } catch (URISyntaxException e) { LOG.error("Failed to create uri builder for elasticsearch"); throw new RuntimeException(e); } } private URIBuilder getWorkSearchUriBuilder(MultivaluedMap<String, String> queryParams) { URIBuilder uriBuilder = getIndexUriBuilder().setPath("/search/work/_search"); if (queryParams != null && !queryParams.isEmpty()) { List<NameValuePair> nvpList = new ArrayList<>(queryParams.size()); queryParams.forEach((key, values) -> { values.forEach(value -> { nvpList.add(new BasicNameValuePair(key, value)); }); }); uriBuilder.setParameters(nvpList); } return uriBuilder; } private URIBuilder getPersonSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/person/_search"); } public final URIBuilder getPlaceUriBuilder() { return getIndexUriBuilder().setPath("/search/place/_search"); } public final URIBuilder getCorporationSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/corporation/_search"); } public final URIBuilder getSerialSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/serial/_search"); } public final URIBuilder getSubjectSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/subject/_search"); } public final URIBuilder getGenreSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/genre/_search"); } public final URIBuilder getPublicationSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/publication/_search"); } public final URIBuilder getInstrumentSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/instrument/_search"); } public final URIBuilder getCompositionTypeSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/compositionType/_search"); } private URIBuilder getEventSearchUriBuilder() { return getIndexUriBuilder().setPath("/search/event/_search"); } }
package br.pucrs.ap3.trees; /** * The {@code BinarySearchTree} class is... * * @author marco.mangan@pucrs.br * */ public class BinarySearchTree { private Node root; public BinarySearchTree() { root = null; } /** * * @param value */ public void add(int value) { root = add0(root, value); } /** * * @param value * @return */ public boolean contains(int value) { return contains0(root, value); } /** * * @param node * @param value * @return */ private Node add0(Node node, int value) { if (node == null) { Node n = new Node(); n.key = value; n.left = null; n.right = null; return n; } if (node.key == value) throw new RuntimeException("Valor existente!"); if (node.key < value) node.right = add0(node.right, value); else node.left = add0(node.left, value); return node; } /** * * @param node * @param value * @return */ private boolean contains0(Node node, int value) { if (node == null) return false; if (node.key == value) return true; if (node.key < value) return contains0(node.right, value); return contains0(node.left, value); } /** * * @return */ public int size() { return size0(root); } /** * * @param node * @return */ private int size0(Node node) { if (node == null) return 0; return 1 + size0(node.left) + size0(node.right); } @Override public String toString() { return toString0(root); } /** * * @param node * @return */ private String toString0(Node node) { if (node == null) return " return toString0(node.left) + String.format(" %d ", node.key) + toString0(node.right); } }
package dev; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.xml.namespace.QName; import javax.xml.soap.SOAPMessage; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.message.MessageElement; import org.apache.axis.message.RPCElement; import org.apache.axis.message.SOAPBody; import org.apache.axis.message.SOAPBodyElement; import org.joseki.soap.GraphDeserializerFactory; import org.joseki.soap.ResultSetAxis; import org.joseki.soap.SOAPUtils; import org.joseki.ws1.JosekiQueryServiceLocator; import org.joseki.ws1.QuerySoapBindingStub; import org.joseki.ws1.QueryType; import org.w3.www._2001.sw.DataAccess.rf1.result2.*; import org.w3.www._2001.sw.DataAccess.sparql_protocol_types.Query; import org.w3.www._2001.sw.DataAccess.sparql_protocol_types.QueryFault; import org.w3.www._2001.sw.DataAccess.sparql_protocol_types.QueryResult; public class WSClient { static String now = null ; static { String fmt = "HH:mm:ss" ; SimpleDateFormat dFmt = new SimpleDateFormat(fmt) ; now = dFmt.format(new Date()) ; } public static void main(String[] args) { clientOM() ; } public static void clientOM() { try { // HappyClient hc = new HappyClient(System.out) ; // hc.verifyClientIsHappy(false) ; // Install deserialier for rdf:RDF String endpoint = "http://localhost:2525/axis/services/sparql-query" ; JosekiQueryServiceLocator service = new JosekiQueryServiceLocator(); service.setSparqlQueryEndpointAddress(endpoint) ; TypeMappingRegistry reg = service.getEngine().getTypeMappingRegistry() ; TypeMapping tm = (TypeMapping)reg.getTypeMapping("") ; tm.register(Model.class, new QName(RDF.getURI(), "RDF") , null, new GraphDeserializerFactory()) ; QueryType qt = service.getSparqlQuery() ; Query q = new Query() ; q.setSparqlQuery("SELECT ?z {?x ?y ?z . FILTER regex(?z, 'Harry')}") ; // q.setNamedGraphUri(new URI[]{ // Do it. QueryResult qr = null ; try { qr = qt.query(q) ; } catch (QueryFault ex) { System.err.println("RC = "+ex.getQueryFaultCode()+" "+ex.getQueryFaultMessage()) ; //System.err.println("RC = "+ex.getFaultCode()+" "+ex.getFaultString()) ; return ; } catch (AxisFault axisFault) { System.err.println("Axis fault: "+axisFault.getFaultCode()) ; System.err.println(axisFault.getFaultString()) ; return ; } if ( true ) { MessageContext cxt = ((QuerySoapBindingStub)qt)._getCall().getMessageContext() ; cxt.setProperty("disablePrettyXML", new Boolean(false)) ; // Print incoming. SOAPMessage msg = cxt.getMessage() ; SOAPBody b = (SOAPBody)msg.getSOAPBody() ; String s = SOAPUtils.elementAsString(cxt, b) ; System.out.println(s) ; System.out.println() ; } if ( qr.getRDF() != null ) { Model m = (Model)qr.getRDF() ; m.write(System.out, "N3") ; return ; } if ( qr.getSparql() != null ) { processResultSet(qr.getSparql()) ; return ; } System.err.println("Unknown result element!!") ; } catch (AxisFault ex) { System.err.println(ex.getFaultReason()) ; System.err.println(ex.getMessage()) ; //ex.printStackTrace(System.err) ; } catch (Exception ex) { System.err.println(ex.getMessage()) ; ex.printStackTrace(System.err) ; } } private static void processResultSet(Sparql resultSet) { ResultSet rs = new ResultSetAxis(resultSet) ; ResultSetFormatter.out(System.out, rs) ; } public static void clientRaw() { try { String endpoint = "http://localhost:2525/axis/services/sparql-query" ; Service service = new Service(); Call call = (Call) service.createCall(); MessageContext msgContext = call.getMessageContext() ; call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName(new QName("", "query")) ; QName op = new QName("http: "query", "sparql") ; SOAPBodyElement bodyElt = new SOAPBodyElement(op) ; bodyElt.addNamespaceDeclaration("st", "http: // "sparql-query")) ; MessageElement mElt = new MessageElement(new QName("sparql-query")) ; mElt.addTextNode("SELECT -- RAW -- "+now) ; bodyElt.addChild(mElt) ; String tmp = SOAPUtils.elementAsString(msgContext, bodyElt) ; System.out.println(tmp) ; System.out.println() ; Object ret = (Object) call.invoke(new Object[]{bodyElt}) ; //System.out.println("Return:("+ret.getClass().getSimpleName()+")"+ret) ; Object obj = ((Vector)ret).get(0) ; //System.out.println("Return1:("+obj.getClass().getSimpleName()+")"+obj) ; RPCElement e = (RPCElement)obj ; msgContext.setProperty("disablePrettyXML", new Boolean(false)) ; System.out.println(SOAPUtils.elementAsString(msgContext, e)) ; //e.deserialize() ; // Not sure where the deserialized version goes to } catch (QueryFault ex) { System.err.println("RC = "+ex.getQueryFaultCode()+" "+ex.getQueryFaultMessage()) ; } catch (Exception ex) { System.err.println(ex.getMessage()) ; ex.printStackTrace(System.err) ; } } }
package org.voltdb.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.voltdb.BackendTarget; import org.voltdb.ServerThread; import org.voltdb.benchmark.tpcc.TPCCProjectBuilder; import org.voltdb.benchmark.tpcc.procedures.InsertNewOrder; import org.voltdb.utils.BuildDirectoryUtils; import org.voltdb_testprocs.regressionsuites.multipartitionprocs.MultiSiteSelect; public class TestJDBCDriver { static String testjar; static ServerThread server; static Connection conn; static TPCCProjectBuilder pb; @BeforeClass public static void setUp() throws ClassNotFoundException, SQLException { testjar = BuildDirectoryUtils.getBuildDirectoryPath() + File.separator + "jdbcdrivertest.jar"; // compile a catalog pb = new TPCCProjectBuilder(); pb.addDefaultSchema(); pb.addDefaultPartitioning(); pb.addProcedures(MultiSiteSelect.class, InsertNewOrder.class); pb.compile(testjar, 2, 0); // Set up ServerThread and Connection startServer(); } @AfterClass public static void tearDown() throws Exception { stopServer(); File f = new File(testjar); f.delete(); } private static void startServer() throws ClassNotFoundException, SQLException { server = new ServerThread(testjar, pb.getPathToDeployment(), BackendTarget.NATIVE_EE_JNI); server.start(); server.waitForInitialization(); Class.forName("org.voltdb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:voltdb://localhost:21212"); } private static void stopServer() throws SQLException { if (conn != null) { conn.close(); conn = null; } if (server != null) { try { server.shutdown(); } catch (InterruptedException e) { /*empty*/ } server = null; } } @Test public void testTableTypes() throws SQLException { ResultSet types = conn.getMetaData().getTableTypes(); int count = 0; List<String> typeList = Arrays.asList(JDBC4DatabaseMetaData.tableTypes); while (types.next()) { assertTrue(typeList.contains(types.getString("TABLE_TYPE"))); count++; } assertEquals(count, typeList.size()); } /** * Retrieve table of the given types and check if the count matches the * expected values * * @param types The table type * @param expected Expected total count * @throws SQLException */ private void tableTest(String[] types, int expected) throws SQLException { ResultSet tables = conn.getMetaData().getTables("blah", "blah", "%", types); int count = 0; List<String> typeList = Arrays.asList(JDBC4DatabaseMetaData.tableTypes); if (types != null) { typeList = Arrays.asList(types); } while (tables.next()) { assertFalse(tables.getString("TABLE_NAME").isEmpty()); assertTrue(typeList.contains(tables.getString("TABLE_TYPE"))); count++; } assertEquals(expected, count); } @Test public void testAllTables() throws SQLException { // TPCC has 10 tables tableTest(null, 10); } @Test public void testFilterTableByType() throws SQLException { for (String type : JDBC4DatabaseMetaData.tableTypes) { int expected = 0; // TPCC has 10 tables and no views if (type.equals("TABLE")) { expected = 10; } tableTest(new String[] {type}, expected); } } @Test public void testFilterTableByName() { try { conn.getMetaData().getTables("blah", "blah", "ORDERS", null); } catch (SQLException e) { return; } fail("Should fail, we don't support filtering by table name"); } /** * Retrieve columns of a given table and check if the count is expected. * * @param table Table name * @param column Column name or null to get all * @param expected Expected number of columns * @throws SQLException */ private void tableColumnTest(String table, String column, int expected) throws SQLException { ResultSet columns = conn.getMetaData().getColumns("blah", "blah", table, column); int count = 0; while (columns.next()) { assertEquals(table, columns.getString("TABLE_NAME")); assertFalse(columns.getString("COLUMN_NAME").isEmpty()); count++; } assertEquals(expected, count); } @Test public void testAllColumns() throws SQLException { tableColumnTest("WAREHOUSE", null, 9); tableColumnTest("WAREHOUSE", "%", 9); } @Test public void testFilterColumnByName() throws SQLException { tableColumnTest("WAREHOUSE", "W_ID", 1); } /** * Retrieve index info of a table and check the count. * * @param table * Table name * @param unique * Unique or not * @param expected * Expected count * @throws SQLException */ private void indexInfoTest(String table, boolean unique, int expected) throws SQLException { ResultSet indexes = conn.getMetaData().getIndexInfo("blah", "blah", table, unique, false); int count = 0; while (indexes.next()) { assertEquals(table, indexes.getString("TABLE_NAME")); if (unique) { assertEquals(false, indexes.getBoolean("NON_UNIQUE")); } count++; } assertEquals(expected, count); } @Test public void testAllIndexes() throws SQLException { indexInfoTest("ORDERS", false, 10); } @Test public void testFilterIndexByUnique() throws SQLException { indexInfoTest("ORDERS", true, 7); } @Test public void testAllPrimaryKeys() throws SQLException { ResultSet keys = conn.getMetaData().getPrimaryKeys("blah", "blah", "ORDERS"); int count = 0; while (keys.next()) { assertEquals("ORDERS", keys.getString("TABLE_NAME")); count++; } assertEquals(3, count); } @Test public void testAllProcedures() throws SQLException { ResultSet procedures = conn.getMetaData().getProcedures("blah", "blah", "%"); int count = 0; List<String> names = Arrays.asList(new String[] {"MultiSiteSelect", "InsertNewOrder"}); while (procedures.next()) { String procedure = procedures.getString("PROCEDURE_NAME"); if (procedure.contains(".")) { // auto-generated CRUD } else { assertTrue(names.contains(procedure)); } count++; } // 7 tables * 4 CRUD/table + 2 procedures + // 3 for replicated insert or insert where partition key !in primary assertEquals(7 * 4 + 2 + 3, count); } @Test public void testFilterProcedureByName() { try { conn.getMetaData().getProcedures("blah", "blah", "InsertNewOrder"); } catch (SQLException e) { return; } fail("Should fail, we don't support procedure filtering by name"); } /** * Retrieve columns of a given procedure and check if the count is expected. * * @param procedure Procedure name * @param column Column name or null to get all * @param expected Expected number of columns * @throws SQLException */ private void procedureColumnTest(String procedure, String column, int expected) throws SQLException { ResultSet columns = conn.getMetaData().getProcedureColumns("blah", "blah", procedure, column); int count = 0; while (columns.next()) { assertEquals(procedure, columns.getString("PROCEDURE_NAME")); assertFalse(columns.getString("COLUMN_NAME").isEmpty()); count++; } assertEquals(expected, count); } @Test public void testAllProcedureColumns() throws SQLException { procedureColumnTest("InsertNewOrder", null, 3); procedureColumnTest("InsertNewOrder", "%", 3); } @Test public void testFilterProcedureColumnsByName() throws SQLException { ResultSet procedures = conn.getMetaData().getProcedures("blah", "blah", "%"); int count = 0; while (procedures.next()) { String proc = procedures.getString("PROCEDURE_NAME"); // Skip CRUD if (proc.contains(".")) { continue; } ResultSet columns = conn.getMetaData().getProcedureColumns("b", "b", proc, null); while (columns.next()) { String column = columns.getString("COLUMN_NAME"); procedureColumnTest(proc, column, 1); count++; } } assertEquals(3, count); } @Test public void testResultSetMetaData() throws SQLException { ResultSetMetaData meta = conn.getMetaData().getTableTypes().getMetaData(); // JDBC index starts at 1!!!!!!!!!!!!!!!!!!!!!!! assertEquals(String.class.getName(), meta.getColumnClassName(1)); assertTrue(meta.getColumnDisplaySize(1) > 0); assertEquals(Types.VARCHAR, meta.getColumnType(1)); assertEquals("VARCHAR", meta.getColumnTypeName(1)); assertTrue(meta.getPrecision(1) > 0); assertEquals(0, meta.getScale(1)); assertTrue(meta.isCaseSensitive(1)); assertFalse(meta.isSigned(1)); } @Test public void testBadProcedureName() throws SQLException { CallableStatement cs = conn.prepareCall("{call Oopsy(?)}"); cs.setLong(1, 99); try { cs.execute(); } catch (SQLException e) { // Since it's a GENERAL_ERROR we need to look for a string by pattern. assertEquals(e.getSQLState(), SQLError.GENERAL_ERROR); assertTrue(Pattern.matches(".*Procedure .* not found.*", e.getMessage())); } } @Test public void testDoubleInsert() throws SQLException { // long i_id, long i_im_id, String i_name, double i_price, String i_data CallableStatement cs = conn.prepareCall("{call InsertNewOrder(?, ?, ?)}"); cs.setInt(1, 55); cs.setInt(2, 66); cs.setInt(3, 77); cs.execute(); try { cs.execute(); } catch (SQLException e) { // Since it's a GENERAL_ERROR we need to look for a string by pattern. assertEquals(e.getSQLState(), SQLError.GENERAL_ERROR); assertTrue(e.getMessage().contains("violation of constraint")); } } public void testVersionMetadata() throws SQLException { int major = conn.getMetaData().getDatabaseMajorVersion(); int minor = conn.getMetaData().getDatabaseMinorVersion(); assertTrue(major >= 2); assertTrue(minor >= 0); } @Test public void testLostConnection() throws SQLException, ClassNotFoundException { // Break the current connection and try to execute a procedure call. CallableStatement cs = conn.prepareCall("{call Oopsy(?)}"); stopServer(); cs.setLong(1, 99); try { cs.execute(); } catch (SQLException e) { assertEquals(e.getSQLState(), SQLError.CONNECTION_FAILURE); } // Restore a working connection for any remaining tests startServer(); } }
package org.voltdb.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import junit.framework.TestCase; import org.voltdb.ServerThread; import org.voltdb.VoltDB; import org.voltdb.VoltDB.Configuration; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.compiler.VoltProjectBuilder; public class TestCSVLoader extends TestCase { private String pathToCatalog; private String pathToDeployment; private ServerThread localServer; private VoltDB.Configuration config; private VoltProjectBuilder builder; private Client client; private final String userHome = System.getProperty("user.home"); String path_csv = userHome + "/" + "test.csv"; @Override protected void setUp() throws Exception { super.setUp(); } public void testCommon() throws Exception { String mySchema = "create table BLAH (" + "clm_integer integer default 0 not null, " + // column that is partitioned on "clm_tinyint tinyint default 0, " + "clm_smallint smallint default 0, " + "clm_bigint bigint default 0, " + "clm_string varchar(20) default null, " + "clm_decimal decimal default null, " + "clm_float float default null "+ // for later //"clm_timestamp timestamp default null, " + // for later //"clm_varinary varbinary default null" + // for later "); "; String []myOptions = { "-f" + userHome + "/test.csv", //"--procedure=BLAH.insert", //"--reportdir=" + reportdir, //"--table=BLAH", "--maxerrors=50", //"-user", "--user=", "--password=", "--port=", "--separator=,", "--quotechar=\"", "--escape=\\", "--skip=0", "--nowhitespace", //"--strictquotes", "BLAH" }; String []myData = { "1,1,1,11111111,first,1.10,1.11", "2,2,2,222222,second,3.30,NULL", "3,3,3,333333, third ,NULL, 3.33", "4,4,4,444444, NULL ,4.40 ,4.44", "5,5,5,5555555, fifth, 5.50, 5.55", "6,6,NULL,666666, sixth, 6.60, 6.66", "7,NULL,7,7777777, seventh, 7.70, 7.77 ", "11, 1,1,\"1,000\",first,1.10,1.11", //invalid lines below "8, 8", "", "10,10,10,10 101 010,second,2.20,2.22", "12,n ull,12,12121212,twelveth,12.12,12.12" }; int invalidLineCnt = 4; test_Interface( mySchema, myOptions, myData, invalidLineCnt ); } public void testNULL() throws Exception { String mySchema = "create table BLAH (" + "clm_integer integer default 0 not null, " + // column that is partitioned on "clm_tinyint tinyint default 0, " + "clm_smallint smallint default 0, " + "clm_bigint bigint default 0, " + "clm_string varchar(20) default null, " + "clm_decimal decimal default null, " + "clm_float float default null "+ // for later //"clm_timestamp timestamp default null, " + // for later //"clm_varinary varbinary default null" + // for later "); "; String []myOptions = { "-f" + userHome + "/test.csv", //"--procedure=BLAH.insert", //"--reportdir=" + reportdir, //"--table=BLAH", "--maxerrors=50", //"-user", "--user=", "--password=", "--port=", "--separator=,", "--quotechar=\"", "--escape=\\", "--skip=0", "--nowhitespace", //"--strictquotes", "BLAH" }; String []myData = { "1,\\N,1,11111111,\"\"NULL\"\",1.10,1.11", "2,\"\\N\",1,11111111,\"NULL\",1.10,1.11", "3,\\N,1,11111111, \\N ,1.10,1.11", "4,\\N,1,11111111, \"\\N\" ,1.10,1.11", "5,\\N,1,11111111, \" \\N \",1.10,1.11", "6,\\N,1,11111111, \" \\N L \",1.10,1.11", "7,\\N,1,11111111, \"abc\\N\" ,1.10,1.11" }; int invalidLineCnt = 0; test_Interface( mySchema, myOptions, myData, invalidLineCnt ); } /* public void testSimple() throws Exception { simpleSchema = "create table BLAH (" + "clm_integer integer default 0 not null, " + // column that is partitioned on "clm_tinyint tinyint default 0, " + //"clm_smallint smallint default 0, " + //"clm_bigint bigint default 0, " + //"clm_string varchar(10) default null, " + //"clm_decimal decimal default null, " + //"clm_float float default 1.0, "+ // for later //"clm_timestamp timestamp default null, " + // for later //"clm_varinary varbinary default null" + // for later "); "; String []params_simple = { //"--inputfile=" + userHome + "/testdb.csv", //"--procedurename=BLAH.insert", //"--reportdir=" + reportdir, //"--tablename=BLAH", //"--abortfailurecount=50", "-help" }; try { CSVLoader.main(params_simple); // do the test VoltTable modCount; modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0]; System.out.println("data inserted to table BLAH:\n" + modCount); int rowct = modCount.getRowCount(); BufferedReader csvreport = new BufferedReader(new FileReader(new String(reportdir + CSVLoader.reportfile))); int lineCount = 0; String line = ""; String promptMsg = "Number of acknowledged tuples:"; while ((line = csvreport.readLine()) != null) { if (line.startsWith(promptMsg)) { String num = line.substring(promptMsg.length()); lineCount = Integer.parseInt(num.replaceAll("\\s","")); break; } } System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct)); assertEquals(lineCount, rowct); CSVLoader.flush(); } finally { if (client != null) client.close(); client = null; if (localServer != null) { localServer.shutdown(); localServer.join(); } localServer = null; // no clue how helpful this is System.gc(); } } */ public void test_Interface( String my_schema, String[] my_options, String[] my_data, int invalidLineCnt ) throws Exception { try{ BufferedWriter out_csv = new BufferedWriter( new FileWriter( path_csv ) ); for( int i = 0; i < my_data.length; i++ ) out_csv.write( my_data[ i ]+"\n" ); out_csv.flush(); out_csv.close(); } catch( Exception e) { System.err.print( e.getMessage() ); } try{ pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar"); pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml"); builder = new VoltProjectBuilder(); //builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null); //builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');"); builder.addLiteralSchema(my_schema); builder.addPartitionInfo("BLAH", "clm_integer"); boolean success = builder.compile(pathToCatalog, 2, 1, 0); assertTrue(success); MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment); config = new VoltDB.Configuration(); config.m_pathToCatalog = pathToCatalog; config.m_pathToDeployment = pathToDeployment; localServer = new ServerThread(config); client = null; localServer.start(); localServer.waitForInitialization(); client = ClientFactory.createClient(); client.createConnection("localhost"); CSVLoader.main( my_options ); // do the test VoltTable modCount; modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0]; System.out.println("data inserted to table BLAH:\n" + modCount); int rowct = modCount.getRowCount(); BufferedReader csvreport = new BufferedReader(new FileReader(CSVLoader.pathReportfile)); int lineCount = 0; String line = ""; String promptMsg = "Number of acknowledged tuples:"; String promptFailMsg = "Number of failed tuples:"; int invalidlinecnt = 0; while ((line = csvreport.readLine()) != null) { if (line.startsWith(promptMsg)) { String num = line.substring(promptMsg.length()); lineCount = Integer.parseInt(num.replaceAll("\\s","")); } if( line.startsWith(promptFailMsg)){ String num = line.substring(promptFailMsg.length()); invalidlinecnt = Integer.parseInt(num.replaceAll("\\s","")); } } System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct)); assertEquals(lineCount, rowct); assertEquals(invalidLineCnt, invalidlinecnt); } finally { if (client != null) client.close(); client = null; if (localServer != null) { localServer.shutdown(); localServer.join(); } localServer = null; // no clue how helpful this is System.gc(); } } }
package org.jboss.summit2015.beacon.scannerjni; import org.jboss.logging.Logger; import org.jboss.summit2015.beacon.Beacon; import org.jboss.summit2015.beacon.MsgType; import org.jboss.summit2015.beacon.bluez.BeaconInfo; import org.jboss.summit2015.beacon.common.EventsBucket; import org.jboss.summit2015.beacon.common.EventsWindow; import org.jboss.summit2015.beacon.common.MsgPublisher; import org.jboss.summit2015.beacon.common.MsgPublisherFactory; import org.jboss.summit2015.beacon.common.ParseCommand; import org.jboss.summit2015.beacon.common.StatusInformation; import java.io.File; import java.nio.ByteBuffer; import java.util.concurrent.ConcurrentLinkedDeque; public class HCIDumpParser { private static Logger log = Logger.getLogger(HCIDumpParser.class); private static String STOP_MARKER_FILE = "/var/run/scannerd.STOP"; /** Command line argument information */ private ParseCommand parseCommand; /** The interface for the messaging layer publisher */ private MsgPublisher publisher; /** The thread for the publishing beacon_info events via the MsgPublisher */ private Thread consumerThread; /** The beacon_info event consumer class running in background */ private BeaconEventConsumer eventConsumer = new BeaconEventConsumer(); /** Shared queue for producer/consumer message exchange */ private ConcurrentLinkedDeque<EventsBucket> eventExchanger = new ConcurrentLinkedDeque<>(); /** An information class published by the HealthStatus task */ private StatusInformation statusInformation = new StatusInformation(); /** The ScannerView implementation used to output information about the scanner */ private ScannerView scannerView; /** A background status monitor task class */ private HealthStatus statusMonitor = new HealthStatus(); /** The time window of collected beacon_info events */ private EventsWindow timeWindow = new EventsWindow(); private volatile boolean stopped; private int lastRSSI[] = new int[10]; private int heartbeatCount = 0; private long eventCount = 0; private long maxEventCount = 0; private long lastMarkerCheckTime = 0; public HCIDumpParser(ParseCommand cmdArgs) { this.parseCommand = cmdArgs; } public void start() throws Exception { stopped = false; eventConsumer.setParseCommand(parseCommand); String clientID = parseCommand.clientID; if (clientID.isEmpty()) clientID = parseCommand.scannerID; timeWindow.reset(parseCommand.analyzeWindow); // Setup the status information statusInformation.setScannerID(parseCommand.getScannerID()); statusInformation.setStatusInterval(parseCommand.statusInterval); statusInformation.setStatusQueue(parseCommand.getStatusDestinationName()); statusInformation.setBcastAddress(parseCommand.getBcastAddress()); statusInformation.setBcastPort(parseCommand.getBcastPort()); if (parseCommand.isAnalyzeMode()) { log.infof("Running in analyze mode, window=%d seconds, begin=%lld\n", parseCommand.getAnalyzeWindow(), timeWindow.getBegin()); } else if (!parseCommand.isSkipPublish()) { String username = parseCommand.getUsername(); String password = parseCommand.getPassword(); publisher = MsgPublisherFactory.newMsgPublisher(parseCommand.getPubType(), parseCommand.getBrokerURL(), clientID, username, password); publisher.setUseTopics(!parseCommand.isUseQueues()); log.infof("setUseTopics: %s\n", publisher.isUseTopics() ? "true" : "false"); publisher.setDestinationName(parseCommand.getDestinationName()); if (parseCommand.batchCount > 0) { publisher.setUseTransactions(true); log.infof("Enabled transactions\n"); } publisher.start(parseCommand.isAsyncMode()); // Create a thread for the consumer unless running in battery test mode if(!parseCommand.isBatteryTestMode()) { eventConsumer.init(eventExchanger, publisher, statusInformation); consumerThread = new Thread(eventConsumer::publishEvents, "BeaconEventConsumer"); consumerThread.setDaemon(true); consumerThread.start(); log.infof("Started event consumer thread\n"); } } else { log.infof("Skipping publish of parsed beacons\n"); } // If the status interval is > 0, start the health status monitor if(parseCommand.getStatusInterval() > 0) { statusMonitor.start(publisher, statusInformation); } } public void stop() throws Exception { stopped = true; if(consumerThread != null) consumerThread.interrupt(); if(publisher != null) publisher.stop(); statusMonitor.stop(); } /** * Callback from native stack * @param rawInfo - the raw direct ByteBuffer store shared with native stack */ public boolean beaconEvent(byte[] rawInfo) { // First get a read only ByteBuffer view for efficient testing of the event info BeaconInfo info = new BeaconInfo(rawInfo); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds boolean stop = false; long elapsed = info.time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info.time; stop = stopMarkerExists(); log.infof("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; // Check for heartbeat boolean isHeartbeat = parseCommand.heartbeatUUID.compareTo(info.uuid) == 0; if(parseCommand.isBatteryTestMode()) { // Send the raw unaveraged heartbeat info, or ignore non-heartbeat events if(isHeartbeat) sendRawHeartbeat(info); } else { // Merge the event into the current time window EventsBucket bucket = timeWindow.addEvent(info, isHeartbeat); statusInformation.addEvent(info, isHeartbeat); // Now handle the bucket if a new one has been created if (bucket != null) { if (!parseCommand.isSkipPublish()) { eventExchanger.offerLast(bucket); } else { if (parseCommand.isAnalyzeMode()) { printBeaconCounts(bucket); } else { if (!isHeartbeat || (isHeartbeat && !parseCommand.isSkipHeartbeat())) printBeaconCounts(info, bucket); } } // Display either the closest beacon or status if (scannerView != null) { if (scannerView.isDisplayBeaconsMode()) displayClosestBeacon(bucket); else displayStatus(); } } } // If stop is true, notify any callers in waitForStop if(stop) { synchronized (this) { stopped = true; this.notifyAll(); } } return stop; } public synchronized void waitForStop() { try { while(stopped == false) this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } boolean stopMarkerExists() { File test = new File(STOP_MARKER_FILE); boolean stop = test.exists(); if(stop) { log.info("Found STOP marker file, will exit..."); } return stop; } void printBeaconCounts(BeaconInfo beacon, EventsBucket bucket) { log.infof("Window: parsed(%s):\n", beacon.toString()); printBeaconCounts(bucket); } void printBeaconCounts(EventsBucket bucket) { StringBuilder tmp = new StringBuilder(); bucket.toString(tmp); log.infof("%s\n", tmp.toString()); } void sendRawHeartbeat(BeaconInfo info) { Beacon beacon = new Beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major, info.minor, info.power, info.rssi, info.time); beacon.setMessageType(MsgType.SCANNER_HEARTBEAT.ordinal()); publisher.publishStatus(beacon); lastRSSI[heartbeatCount%10] = info.rssi; heartbeatCount ++; if(heartbeatCount % 100 == 0) { log.infof("Last[10].RSSI:"); for(int n = 0; n < 10; n ++) log.infof("%d,", lastRSSI[n]); log.infof("\n"); } } void displayClosestBeacon(EventsBucket bucket) { /* TODO map<int32_t, beacon_info>::const_iterator iter = bucket->begin(); int32_t maxRSSI = -100; const beacon_info *closest = nullptr; const beacon_info *heartbeat = nullptr; while (iter != bucket->end()) { // Skip the heartbeast beacon... if(iter->second.rssi > maxRSSI) { if(scannerUUID.compare(iter->second.uuid) == 0) heartbeat = &iter->second; else { maxRSSI = iter->second.rssi; closest = &iter->second; } } iter++; } if(closest != nullptr) { Beacon closestBeacon(parseCommand.getScannerID(), closest->uuid, closest->code, closest->manufacturer, closest->major, closest->minor, closest->power, closest->calibrated_power, closest->rssi, closest->time); scannerView->displayBeacon(closestBeacon); } else if(heartbeat != nullptr) { // The only beacon seen was the heartbeat beacon, so display it Beacon heartbeatBeacon(parseCommand.getScannerID(), heartbeat->uuid, heartbeat->code, heartbeat->manufacturer, heartbeat->major, heartbeat->minor, heartbeat->power, heartbeat->calibrated_power, heartbeat->rssi, heartbeat->time); scannerView->displayHeartbeat(heartbeatBeacon); } */ } void displayStatus() { scannerView.displayStatus(statusInformation); } }